Compare commits

...
40 Commits
Author SHA1 Message Date
DenozordecandClaude Opus 5.5 fcbf219725 fix(ui): оболочка общего макета v2 и карта сети без наложений по макету v3
Docker images / frontend-image (push) Successful in 2m15s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 1m49s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Successful in 10m21s
Вернуть оболочку общего макета v2 и EvoBGP вместо вложенной панели v3;
читаемые надписи состояния системы в светлой теме. Карта сети: одна
подпись на связь без наложений на карточки, ленты NetFlow вместо бейджей,
страница поэлементно по макету v3, исправлен расчёт скорости NetFlow в KPI.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 08:53:42 +07:00
DenozordecandClaude Opus 5.5 95a0ebeb18 fix(ui): подписи GRE из известных значений и карта над миникартой
Подпись связи собирается из того, что известно: RTT, скорость NetFlow
пары (записи одного роутера складываются, оба конца туннеля — максимум),
«GRE ×N»; «—» — только когда не известно ничего. Не влезающая между
карточками подпись не рисуется, полное значение — в title линии.
«N мс» на карточке скрывается, только если RTT туннеля уже на подписи.

Вписывание оставляет снизу полосу под панель масштаба и миникарту, они
не закрывают объекты; e2e проверяет и эти оверлеи. Подсказки поиска
закрываются, когда фокус уходит из поиска. В инспекторе устройства —
ряд переходов: Терминал, Firewall, GRE-туннели, Трафик, Навести на узел.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 03:35:49 +07:00
DenozordecandClaude Opus 5.5 2b0b9a5fa5 fix(ui): читаемая надпись состояния системы в светлой теме
«Внимание» / «Сбой» и счётчики в окне состояния системы были жёлтым и
красным токеном фона (контраст 1.66 в светлой теме). Текст — токены
*-foreground, как у бейджей ReUI; operational-a11y и server-rail снова
без нарушений контраста.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 03:35:49 +07:00
DenozordecandClaude Opus 5.5 9b2c2327a6 fix(ui): карта сети без наложений подписей и поэлементно как в макете v3
Холст: одна подпись на связь (параллельные GRE — «GRE ×N»), подписи
раскладываются по своей кривой без наложения на карточки и друг на друга,
не влезающая не рисуется; Exit → назначения — ленты NetFlow по скорости
без бейджей; имя хоста без домена, кегль 14→12 px и многоточие вместо
сжатия textLength; флаг справа сверху, WAN→JH — приглушённый пунктир.

Страница: подзаголовок со снимком и NetFlow вместо строки статистики,
панель инструментов в одну строку, поиск с подсказками вместо списка
устройств, масштаб «− % + Вписать Авто-раскладка» снизу слева, миникарта
справа, шкала времени как в макете, инспектор отдельным фреймом с
пустым состоянием, плитки и «Устройство» в две колонки, легенда макета.

KPI: скорость NetFlow считалась как Мбит/с из бит/с (показывало Гбит/с),
склонения «1 узел / 2 узла», Exit-узлы и недоступные GRE в подвалах.
Карта не падает, если /api/ix/topology вернул ответ без links.

Тесты: раскладка подписей и ленты (unit), отсутствие наложений на
наборе как на проде и в сетке JH × Exit (e2e), спеки карты обновлены.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 02:37:57 +07:00
DenozordecandClaude Opus 5.5 ec2fb54e04 fix(ui): вернуть оболочку общего макета v2 и EvoBGP
Оболочка приложения снова как в общем макете v2 (шаблон TplOps) и в EvoBGP
вместо варианта из макета v3:
- основная область без «вставки»-карточки, меню во всю высоту;
- меню: переключатель приложений с пунктом «Настроить на портале»,
  «Поиск и команды ⌘K», «Закреплённые» со звёздочкой, сворачиваемые
  группы, точки проблем у разделов вместо счётчиков;
- шапка: «Главная / раздел / страница», окно «Источники и свежесть
  данных», поиск на телефоне и «Состояние системы» (Норма / Внимание /
  Сбой) с проблемами, метриками и переходом в мониторинг;
- сетка приложений в шапке убрана: её заменяет переключатель в меню.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 00:44:37 +07:00
DenozordecandClaude Opus 5.5 c94d417f1b feat(ui): перенести пилотные разделы на макет v3
Docker images / backend-test (push) Successful in 10m53s
Docker images / frontend-image (push) Successful in 2m15s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 1m54s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 11s
Слияние ветки claude/sad-bassi-fe48a8: этап 0 и пилот интеграции макета v3.

- оболочка: inset-сайдбар, крошки «Главная / …», заголовок страницы
  и индикатор свежести данных; общие блоки reui-kit/ops-blocks;
- дашборд: ёмкость, показатели со спарклайнами, сводка источников,
  вкладки «Обзор / Источники и время получения / История RTT»;
- статистика: вкладки «Обзор / Сводная (куб) / Срезы», демо-куб;
- трафик: вкладки разделов, детали с периодом и скоростями,
  «Доля RX», «Интерфейсы сервера»;
- карта сети: колонки макета, карточки узлов, KPI-полоса, панель
  объекта с вкладками, «Момент времени» и рабочая панель снизу.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 21:30:25 +07:00
Denozordec 63c0fc6506 fix(ix): ограничивать размер сегмента TCP для туннелей VPS
Docker images / backend-test (push) Successful in 10m38s
Docker images / frontend-image (push) Successful in 2m14s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 35s
Docker images / backend-image (push) Successful in 2m2s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 10s
2026-11-25 19:29:56 +07:00
Denozordec 682d6c8d55 fix(mcp): разрешить настройку размера сегмента TCP
Docker images / backend-test (push) Successful in 10m27s
Docker images / backend-image (push) Successful in 2m19s
Docker images / frontend-image (push) Successful in 2m16s
Docker images / updater-image (push) Successful in 38s
Docker images / netflow-agent-image (push) Successful in 45s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
Docker images / prepare-release (push) Successful in 9s
2026-11-25 13:35:20 +07:00
Denozordec a41c70b104 feat(ix): добавить одноразовые ссылки импорта конфигураций
Docker images / updater-image (push) Successful in 42s
Docker images / netflow-agent-image (push) Successful in 36s
Docker images / backend-test (push) Successful in 9m43s
Docker images / backend-image (push) Successful in 1m59s
Docker images / frontend-image (push) Successful in 15m47s
Docker images / notify-webhook (push) Successful in 0s
Docker images / publish-release (push) Successful in 10s
Docker images / prepare-release (push) Successful in 9s
2026-11-25 11:46:51 +07:00
DenozordecandClaude Opus 5.5 dd6e6b0b77 feat(ui): разделы карты сети по макету v3
- панель инструментов: поиск первым, вид «Вся сеть / IX и клиенты»,
  «Сервисы / Страны», окно «Фильтр» со статусами и ролями, справа
  «Слои» и «Легенда»;
- панель объекта: шапка с плиткой роли, адресом и статусом, вкладки
  «Обзор» (RTT, сессии, входящий/исходящий трафик, устройство,
  назначения через узел, ресурсы, действия), «Интерфейсы» (WAN-аплинки
  и трафик интерфейсов за окно NetFlow) и «GRE»;
- «Момент времени» под картой: инциденты из ленты событий за 24 часа
  и метка Live; архив снимков карты бэкенд не хранит;
- рабочая панель под картой: вкладки «Потоки NetFlow», «RTT каналов»,
  «Назначения» и «События», строки выбранного объекта подсвечены;
- на телефоне окно легенды растягивается по ширине экрана.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 00:08:07 +07:00
DenozordecandClaude Opus 5.5 a4694b8481 feat(ui): перерисовать карту сети по колонкам макета v3
- полосы Home Router · WAN · JumpHost · Exit (и IX) · назначения
  с заголовками и счётчиками; WAN-аплинки в своей колонке и не
  наезжают друг на друга;
- узлы — карточки 160×56 с плиткой роли, точкой статуса, именем,
  задержкой, площадкой и флагом; длинное имя ужимается, а не обрезается;
- WAN — «таблетки», назначения — строки с иконкой, категорией,
  скоростью, долей и полосой; при раскрытой стране обе колонки компактные;
- связи — горизонтальные кривые между гранями карточек; подписи RTT
  и NetFlow рисуются поверх карточек и остаются кликабельными;
- легенда — выпадающее окно кнопки «Легенда» в панели инструментов,
  закрыта по умолчанию;
- масштаб, перетаскивание, миникарта, клавиатура и экспорт SVG сохранены;
  ревизия раскладки 8 сбрасывает старые ручные позиции.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 23:41:56 +07:00
DenozordecandClaude Opus 5.5 640726aa86 fix(ui): доводка трафика и карты сети по макету v3
- карта: счётчики онлайн/с проблемами/оффлайн остались только в KPI-полосе,
  подпись NetFlow описывает среднюю скорость всех потоков окна,
  у кнопок статусов читаемое имя «Оффлайн 1»;
- трафик: детали клиента и интерфейса показывают скорости двумя колонками,
  как у сервера; на странице и в панели потоков нет текста мельче text-xs;
- e2e: «Объяснить» открывает вкладку источников с баннером
  «Не обновлены источники», счётчик оффлайн проверяется в KPI-полосе.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 23:10:54 +07:00
DenozordecandClaude Opus 5.5 67b1d9cde2 feat(ui): перенести трафик и карту сети на макет v3
Трафик: шапка деталей с названием, статусом и сегментным периодом;
текущие и пиковые скорости двумя колонками; блоки «Доля RX» и
«Интерфейсы сервера»; сегментная сортировка и поле поиска как в макете;
в карточках списка нет текста мельче text-xs.

Карта сети: KPI-полоса над картой (узлы со статусами-фильтрами,
GRE-туннели, NetFlow за окно, узлы, требующие внимания), прокручиваемая
страница с картой фиксированной высоты, поиск в стиле макета.
На узких экранах KPI-полоса уходит под карту, чтобы карта помещалась
в экран и работал жест панорамирования.

Скриншоты docs/ux-ui обновлены прогоном e2e пилота.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 22:56:03 +07:00
DenozordecandClaude Opus 5.5 8781f68674 fix(ui): демо-куб статистики и честная подпись фактора здоровья
Без живого API статистика показывает демо-куб вместо пустого состояния,
как в макете v3. Фактор «Задержка (RTT)» переименован в «Пробы в норме»:
его полоса — доля проб в норме, а не задержка.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 22:31:02 +07:00
DenozordecandClaude Opus 5.5 5fd028800a feat(ui): перенести дашборд, статистику и трафик на макет v3
Этап 0 и пилот интеграции макета v3:
- оболочка: inset-сайдбар, крошки «Главная / … /», индикатор свежести,
  заголовок страницы PageTitle;
- общие блоки reui-kit/ops-blocks: SectionFrame, CapacityGrid, SparkKpiGrid,
  ToneBadge;
- дашборд: ёмкость, показатели со спарклайнами, сводка источников,
  вкладки «Обзор / Источники и время получения / История RTT»,
  здоровье сети, лента инцидентов, схема Internet path, сводка маршрута,
  таблица «Требует внимания», настройка видимости виджетов;
- статистика: вкладки «Обзор / Сводная (куб) / Срезы», доли объёма;
- трафик: вкладки разделов со счётчиками, рамки списка и деталей,
  кнопка «Месячный отчёт».

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 22:23:16 +07:00
Denozordec 01779d7ee6 fix(scheduler): дождаться освобождения блокировки перед сбором метрик
Docker images / updater-image (push) Successful in 3m22s
Docker images / frontend-image (push) Successful in 3m26s
Docker images / netflow-agent-image (push) Successful in 3m21s
Docker images / backend-test (push) Successful in 25m38s
Docker images / backend-image (push) Successful in 20m27s
Docker images / notify-webhook (push) Successful in 1s
Docker images / publish-release (push) Successful in 9s
Docker images / prepare-release (push) Successful in 9s
2026-11-24 22:01:12 +07:00
Denozordec 1b927dcf68 fix(traffic): показывать показатели интерфейсов при неполных замерах
Docker images / backend-test (push) Successful in 2s
Docker images / backend-image (push) Successful in 15s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 1m18s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 29s
Docker images / frontend-image (push) Successful in 6m50s
Docker images / prepare-release (push) Successful in 9s
2026-11-24 16:37:50 +07:00
Denozordec af82497f20 fix(netflow): исправить учёт трафика по выходным узлам на карте сети
Docker images / backend-test (push) Successful in 10m33s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 2m0s
Docker images / frontend-image (push) Successful in 7m41s
Docker images / publish-release (push) Successful in 33s
Docker images / notify-webhook (push) Successful in 1m55s
Docker images / prepare-release (push) Successful in 12s
2026-11-24 15:41:44 +07:00
Denozordec ca65969728 fix(netflow): исправить подсчёт трафика туннелей на карте сети
Docker images / backend-test (push) Successful in 10m26s
Docker images / frontend-image (push) Successful in 2m15s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 35s
Docker images / backend-image (push) Successful in 2m7s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 11s
2026-11-24 13:59:48 +07:00
Denozordec ee6fd675ac fix(routing): устранить конфликты чтения фильтров и маршрутов
Docker images / backend-test (push) Successful in 10m25s
Docker images / frontend-image (push) Successful in 3m18s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 2m48s
Docker images / publish-release (push) Successful in 10s
Docker images / notify-webhook (push) Successful in 1s
Docker images / prepare-release (push) Successful in 10s
2026-11-24 12:46:31 +07:00
Denozordec 5a46594ec9 fix(ix): объединить туннели по клиентам и показать счётчики трафика
Docker images / backend-test (push) Successful in 10m24s
Docker images / backend-image (push) Successful in 2m0s
Docker images / frontend-image (push) Successful in 2m15s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
Docker images / prepare-release (push) Successful in 11s
2026-11-24 10:48:21 +07:00
Denozordec 31f75a8eed feat(ix): включать действующие интерфейсы в группы резервирования
Docker images / backend-test (push) Successful in 11m40s
Docker images / frontend-image (push) Successful in 3m56s
Docker images / updater-image (push) Successful in 2m38s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / backend-image (push) Successful in 5m2s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 12s
2026-11-24 00:56:00 +07:00
Denozordec 2a759ae5e5 fix(ci): зарегистрировать операции оператора и запускать тесты резервирования
Docker images / backend-test (push) Canceled after 3m3s
Docker images / backend-image (push) Canceled after 0s
Docker images / frontend-image (push) Canceled after 0s
Docker images / updater-image (push) Canceled after 0s
Docker images / netflow-agent-image (push) Canceled after 0s
Docker images / publish-release (push) Canceled after 0s
Docker images / notify-webhook (push) Canceled after 0s
Docker images / prepare-release (push) Successful in 11s
2026-11-24 00:48:04 +07:00
Denozordec fad89c7059 fix(ci): учесть маршруты групп туннелей в реестре покрытия
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 4m7s
Docker images / updater-image (push) Successful in 2m15s
Docker images / netflow-agent-image (push) Successful in 35s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
Docker images / prepare-release (push) Successful in 10s
Docker images / backend-test (push) Failing after 4m9s
2026-11-24 00:38:57 +07:00
Denozordec 350ae34862 feat(ix): добавить управление группами туннелей для резервирования и балансировки
Docker images / backend-test (push) Failing after 4m0s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 3m55s
Docker images / updater-image (push) Successful in 2m11s
Docker images / netflow-agent-image (push) Successful in 37s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
Docker images / prepare-release (push) Successful in 11s
2026-11-24 00:29:50 +07:00
Denozordec 676be13251 fix(ix): открыть добавление протокола из формы клиента
Docker images / backend-test (push) Successful in 10m31s
Docker images / frontend-image (push) Successful in 3m20s
Docker images / updater-image (push) Successful in 1m56s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 3m4s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 12s
2026-11-23 21:48:52 +07:00
Denozordec ca1bc1ab38 feat(ix): добавить два протокола для одного клиента
Docker images / backend-test (push) Successful in 10m29s
Docker images / frontend-image (push) Successful in 2m14s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 1m58s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 11s
Выдавать профиль и скрипт настройки туннеля с прямым доступом по внешнему адресу. Учитывать собственные маршруты возврата при применении черновика.
2026-11-23 18:48:10 +07:00
Denozordec d9f623ccda fix(map): показать текущий трафик туннелей
Docker images / backend-test (push) Successful in 10m29s
Docker images / frontend-image (push) Successful in 2m9s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 31s
Docker images / backend-image (push) Successful in 1m58s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 11s
2026-11-23 14:39:40 +07:00
Denozordec 9951035448 feat(ix): упростить настройку и добавить выдачу конфигов 2026-11-23 14:39:40 +07:00
Denozordec 95be5178d0 fix(ix): учесть новые маршруты в реестре покрытия
Docker images / backend-test (push) Successful in 10m19s
Docker images / frontend-image (push) Successful in 2m11s
Docker images / updater-image (push) Successful in 42s
Docker images / netflow-agent-image (push) Successful in 31s
Docker images / backend-image (push) Successful in 1m58s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 10s
2026-11-23 13:31:03 +07:00
Denozordec c9152bb106 feat(ix): добавить управление клиентами и выходами транзитных узлов
Docker images / backend-test (push) Failing after 3m38s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 2m11s
Docker images / updater-image (push) Successful in 38s
Docker images / netflow-agent-image (push) Successful in 31s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
Docker images / prepare-release (push) Successful in 11s
2026-11-23 13:21:29 +07:00
Denozordec ef3d7b6779 fix(poll): снять квоты журналов полного опроса
Docker images / backend-test (push) Successful in 10m21s
Docker images / frontend-image (push) Successful in 2m8s
Docker images / updater-image (push) Successful in 38s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 1m59s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 11s
2026-11-23 11:35:04 +07:00
Denozordec e11e67b3a1 feat(ix): добавить удаление сегментов
Docker images / backend-test (push) Successful in 10m30s
Docker images / frontend-image (push) Successful in 2m11s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 2m0s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 11s
2026-11-23 11:00:47 +07:00
Denozordec be1cb6381a fix(ix): восстановить применение и подключение клиентов
Docker images / backend-test (push) Successful in 10m17s
Docker images / backend-image (push) Successful in 1m59s
Docker images / frontend-image (push) Successful in 2m10s
Docker images / updater-image (push) Successful in 38s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / notify-webhook (push) Successful in 1s
Docker images / publish-release (push) Successful in 10s
Docker images / prepare-release (push) Successful in 11s
2026-11-23 10:22:45 +07:00
Denozordec 4900101b5e fix(ui): обновить раздел точек обмена и выбор типа узла
Docker images / backend-test (push) Successful in 3s
Docker images / backend-image (push) Successful in 16s
Docker images / frontend-image (push) Successful in 3m34s
Docker images / updater-image (push) Successful in 2m36s
Docker images / netflow-agent-image (push) Successful in 36s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
Docker images / prepare-release (push) Successful in 11s
2026-11-23 02:07:56 +07:00
Denozordec 6f235c700a fix(mcp): учесть маршруты обмена трафиком в реестре
Docker images / backend-test (push) Successful in 10m35s
Docker images / backend-image (push) Successful in 3m10s
Docker images / frontend-image (push) Successful in 2m46s
Docker images / updater-image (push) Successful in 1m21s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
Docker images / prepare-release (push) Successful in 11s
2026-11-23 01:16:01 +07:00
Denozordec d422050a4b feat(ix): добавить точки обмена трафиком
Docker images / backend-test (push) Failing after 4m0s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 5m0s
Docker images / updater-image (push) Successful in 1m56s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
Docker images / prepare-release (push) Successful in 11s
2026-11-23 01:07:49 +07:00
Denozordec 80cd3a18d7 fix(network): исправить исходный адрес пинга и обновление фильтров
Docker images / backend-test (push) Successful in 10m58s
Docker images / frontend-image (push) Successful in 3m56s
Docker images / updater-image (push) Successful in 2m37s
Docker images / netflow-agent-image (push) Successful in 39s
Docker images / backend-image (push) Successful in 3m56s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 13s
Оставить выбор исходного адреса пинга маршрутизатору. Читать правила и рекурсивные шлюзы последовательно, сохранить кэш при конфликте блокировки.
2026-11-22 20:47:38 +07:00
Denozordec f5914b634a fix(mcp): учесть модуль политики в тестах маршрутизации
Docker images / backend-image (push) Successful in 3m6s
Docker images / frontend-image (push) Successful in 3m23s
Docker images / updater-image (push) Successful in 1m45s
Docker images / netflow-agent-image (push) Successful in 36s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m46s
2026-11-22 19:48:17 +07:00
Denozordec aac425c7b2 feat(mcp): расширить управление сетью и исправить разрезы трафика
Docker images / backend-test (push) Failing after 10m39s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 3m11s
Docker images / updater-image (push) Successful in 1m56s
Docker images / netflow-agent-image (push) Successful in 37s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
Docker images / prepare-release (push) Successful in 13s
Добавить переименование интерфейсов и возможность отключать лимиты частоты для сервисных аккаунтов.

Уточнить дедупликацию, учёт интерфейсов и геоданных, фильтрацию сессий и карту потоков.
2026-11-22 19:24:49 +07:00
236 changed files with 13954 additions and 3904 deletions

No files matched your search

+394 -306
View File
@@ -1,349 +1,437 @@
"use client" "use client"
import { useState } from "react" import { useEffect, useMemo, useState } from "react"
import { Button } from "@/components/ui/button"
import Link from "next/link" import Link from "next/link"
import { import {
ActivityIcon,
BellIcon,
CableIcon, CableIcon,
FilterIcon, ChartColumnIcon,
GitMergeIcon, CircleAlertIcon,
HardDriveIcon,
HeartPulseIcon, HeartPulseIcon,
MapIcon, LayoutDashboardIcon,
ServerIcon, ServerIcon,
ShieldIcon, SlidersHorizontalIcon,
TableIcon,
} from "lucide-react" } from "lucide-react"
import { Button, buttonVariants } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Alert, AlertAction, AlertDescription, AlertTitle } from "@/components/reui/alert"
import { Badge } from "@/components/reui/badge"
import { PageHeader } from "@/components/page-header" import { PageHeader } from "@/components/page-header"
import { OpsPanel } from "@/components/ops-panel" import { PageTitle } from "@/components/page-title"
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid" import { DataFreshness } from "@/components/data-freshness"
import { QuickActionGrid } from "@/components/reui-kit/quick-action-grid" import { EmptyState } from "@/components/empty-state"
import { AttentionQueue } from "@/components/reui-kit/attention-queue" import { CapacityGrid, SectionFrame, SparkKpiGrid, ToneBadge, seriesDelta, type Tone } from "@/components/reui-kit/ops-blocks"
import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart" import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart"
import { LatencyChart } from "@/components/dashboard/latency-chart" import { LatencyChart } from "@/components/dashboard/latency-chart"
import { DashboardEventsTimeline } from "@/components/dashboard/dashboard-events-timeline"
import { InternetPathPanel } from "@/components/dashboard/internet-path-panel" import { InternetPathPanel } from "@/components/dashboard/internet-path-panel"
import { DashboardSourcesSummary, dashboardSourceRows, sourceErrorText } from "@/components/dashboard/dashboard-sources-summary"
import {
DashboardAttentionGrid,
DashboardHealth,
DashboardIncidents,
DashboardQuickLinks,
type AttentionGridRow,
} from "@/components/dashboard/dashboard-overview-blocks"
import { DashboardActiveProbesDataGrid } from "@/components/data-grids/dashboard-active-probes-data-grid" import { DashboardActiveProbesDataGrid } from "@/components/data-grids/dashboard-active-probes-data-grid"
import { EmptyState } from "@/components/empty-state"
import { DashboardDataStatus } from "@/components/dashboard/dashboard-data-status"
import { Badge } from "@/components/reui/badge"
import { buttonVariants } from "@/components/ui/button"
import { cn } from "@/lib/utils"
import { fmtRate } from "@/lib/fmt-rate" import { fmtRate } from "@/lib/fmt-rate"
import { DASHBOARD_SOURCES, type DashboardSource, type DashboardSources } from "@/lib/dashboard-source-state"
import { useDashboardLive, type AttentionRow } from "@/hooks/use-dashboard-live" import { useDashboardLive, type AttentionRow } from "@/hooks/use-dashboard-live"
const WIDGETS = {
cap: "Ёмкость",
spark: "Показатели",
sources: "Сводка источников",
health: "Здоровье сети",
timeline: "Лента инцидентов",
path: "Internet path",
attention: "Требует внимания",
latency: "Задержка до серверов",
traffic: "Пропускная способность",
probes: "Активные пробы",
links: "Быстрые переходы",
} as const
type Widget = keyof typeof WIDGETS
const HIDDEN_WIDGETS_LS = "mm:dashboard-hidden-widgets"
function useHiddenWidgets() {
const [hidden, setHidden] = useState<Set<Widget>>(new Set())
useEffect(() => {
try {
const raw = JSON.parse(localStorage.getItem(HIDDEN_WIDGETS_LS) ?? "[]")
if (Array.isArray(raw)) queueMicrotask(() => setHidden(new Set(raw.filter((key): key is Widget => key in WIDGETS))))
} catch {
/* повреждённое значение — показываем все виджеты */
}
}, [])
function toggle(key: Widget, visible: boolean) {
setHidden((previous) => {
const next = new Set(previous)
if (visible) next.delete(key)
else next.add(key)
try {
localStorage.setItem(HIDDEN_WIDGETS_LS, JSON.stringify([...next]))
} catch {
/* хранилище недоступно — настройка действует до перезагрузки */
}
return next
})
}
return { hidden, toggle }
}
function fmtIntRu(n: number): string { function fmtIntRu(n: number): string {
return n.toLocaleString("ru-RU") return n.toLocaleString("ru-RU")
} }
function AttentionRows({ rows }: { rows: AttentionRow[] }) { function averageSeries(series: Record<string, (number | null)[]>): number[] {
const [expanded,setExpanded]=useState(false) const rows = Object.values(series)
const [visible,setVisible]=useState(55) const length = Math.max(0, ...rows.map((values) => values.length))
function renderRow(row: AttentionRow) { const out: number[] = []
return ( for (let i = 0; i < length; i++) {
<Link const values = rows.map((row) => row[i]).filter((v): v is number => typeof v === "number" && Number.isFinite(v))
key={row.id} if (values.length) out.push(values.reduce((sum, v) => sum + v, 0) / values.length)
href={row.href}
className="hover:bg-muted/40 focus-visible:ring-ring flex min-w-0 items-start justify-between gap-2 rounded-md px-1 py-1.5 focus-visible:ring-2"
>
<span className="min-w-0 wrap-anywhere text-sm font-medium">{row.title}</span>
<Badge
size="sm"
variant={row.tone === "warning" ? "warning-light" : "destructive-light"}
className="shrink-0"
>
{row.hint}
</Badge>
</Link>
)
} }
return out
}
return ( function toGridRows(rows: AttentionRow[], kind: AttentionGridRow["kind"]): AttentionGridRow[] {
<div className="flex flex-col gap-0.5"> return rows.map((row) => ({
{rows.slice(0, 5).map(renderRow)} id: row.id,
{rows.length > 5 && ( title: row.title,
<details onToggle={event=>{setExpanded(event.currentTarget.open);if(!event.currentTarget.open)setVisible(55)}}> kind,
<summary className="cursor-pointer rounded-md px-1 py-2 text-xs text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring">Ещё {rows.length - 5}</summary> hint: row.hint,
{expanded && rows.slice(5,visible).map(renderRow)} href: row.href,
{expanded && rows.length>visible && <Button type="button" variant="ghost" size="sm" onClick={()=>setVisible(count=>Math.min(count+50,rows.length))}>Показать ещё {Math.min(50,rows.length-visible)}</Button>} tone: row.tone === "destructive" ? "er" : "wn",
</details> confirmed: row.hint !== "Статус неизвестен",
)} }))
</div>
)
} }
export default function DashboardPage() { export default function DashboardPage() {
const dash = useDashboardLive() const dash = useDashboardLive()
const { hidden, toggle } = useHiddenWidgets()
const [tab, setTab] = useState("over")
const [mockAt] = useState(() => Date.now())
const show = (key: Widget) => !hidden.has(key)
// Демо-режим не опрашивает API: показываем источники полученными в момент открытия страницы.
const sources: DashboardSources = useMemo(
() => dash.isLive ? dash.sources : Object.fromEntries((Object.keys(DASHBOARD_SOURCES) as DashboardSource[]).map((key) => [key, { receivedAt: mockAt, error: null }])),
[dash.isLive, dash.sources, mockAt],
)
const sourceRows = dashboardSourceRows(sources)
const failedSources = sourceRows.filter((row) => row.error)
const received = sourceRows.map((row) => row.receivedAt).filter((at): at is number => at != null)
const freshAt = received.length ? Math.max(...received) : null
const offline = dash.offlineCount const offline = dash.offlineCount
const health = dash.probeDown + dash.probeWarn const problems = dash.probeDown + dash.probeWarn
const serverTrouble = offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0
const serverCaption = !dash.availability.servers ? "нет данных" : !dash.isLive
? "демо"
: serverTrouble
? [offline > 0 ? `${offline} не в сети` : null, dash.unknownServerCount > 0 ? `Статус неизвестен: ${dash.unknownServerCount}` : null, dash.degradedServerCount > 0 ? `Ухудшение: ${dash.degradedServerCount}` : null].filter(Boolean).join(" · ")
: dash.totalServers > 0 ? "все в сети" : "нет серверов"
const latencySeries = dash.latency.kind === "mock" || dash.latency.kind === "live" ? averageSeries(dash.latency.series) : []
const rttNow = latencySeries.length ? Math.round(latencySeries[latencySeries.length - 1]) : null
const probesMeasured = useMemo(() => dash.enabledProbes.filter((p) => p.status !== "unknown"), [dash.enabledProbes])
const avgLoss = probesMeasured.length ? probesMeasured.reduce((sum, p) => sum + (p.loss ?? 0), 0) / probesMeasured.length : null
const okSources = sourceRows.filter((row) => row.tone === "ok").length
const attentionRows = [
...toGridRows(dash.attentionServers, "Сервер"),
...toGridRows(dash.attentionOverlay, "Туннель"),
...toGridRows(dash.attentionProbes, "Проверка"),
]
const emptyNotes = [
dash.attentionServers.length ? null : dash.reliable.servers ? (dash.totalServers > 0 ? "Серверы без проблем" : "Нет серверов") : "Серверы: состояние не подтверждено",
dash.attentionOverlay.length ? null : dash.reliable.overlay ? (dash.overlay.total > 0 ? "Туннели работают" : "Нет туннелей") : "Туннели: состояние не подтверждено",
dash.attentionProbes.length ? null : dash.reliable.probes ? (dash.probeCount > 0 ? "Проверки без ошибок" : "Нет активных проверок") : "Проверки: состояние не подтверждено",
].filter((note): note is string => note != null)
const latencyBody = dash.latency.kind === "loading" ? (
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
) : dash.latency.kind === "empty" ? (
<p className="text-muted-foreground px-4 py-10 text-center text-sm">{dash.latency.message}</p>
) : (
<LatencyChart series={dash.latency.series} labels={dash.latency.labels} />
)
const latencyDescription = dash.latency.kind === "mock" || dash.latency.kind === "live" ? dash.latency.subtitle : dash.latency.kind === "loading" ? "Загрузка…" : "Нет серии RTT"
return ( return (
<div className="flex h-full flex-col"> <div className="flex h-full flex-col">
<PageHeader crumbs={[{ label: "Обзор" }, { label: "Дашборд" }]} /> <PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Дашборд" }]} status={<DataFreshness at={freshAt} live={dash.isLive} />} />
<div className="flex-1 overflow-y-auto"> <div className="flex-1 overflow-y-auto">
<div className="flex flex-col gap-4 px-4 py-4 md:gap-6 md:px-6 md:py-5"> <div className="flex flex-col gap-6 px-4 pt-5 pb-10 md:px-7 md:pt-6">
{dash.isLive && <DashboardDataStatus sources={dash.sources} refreshing={dash.refreshing} onRefresh={dash.retry} />} <PageTitle
icon={<LayoutDashboardIcon />}
<KpiStatGrid title="Дашборд"
aria-label="Сводка дашборда" description="Здоровье сети: индекс, события за период, Internet path, пробы и источники"
isLoading={dash.loading} actions={
items={[ <>
{ <DropdownMenu>
id: "fleet", <DropdownMenuTrigger render={<Button type="button" variant="outline"><SlidersHorizontalIcon data-icon="inline-start" />Настроить виджеты</Button>} />
label: "Серверы онлайн", <DropdownMenuContent align="end" className="w-60">
value: dash.availability.servers ? `${dash.onlineCount} / ${dash.totalServers}` : "—", <DropdownMenuGroup>
hint: !dash.availability.servers ? "нет данных" : !dash.isLive <DropdownMenuLabel>Виджеты дашборда</DropdownMenuLabel>
? "демо" {(Object.keys(WIDGETS) as Widget[]).map((key) => (
: offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0 <DropdownMenuCheckboxItem key={key} checked={show(key)} onCheckedChange={(value) => toggle(key, !!value)}>
? [offline > 0 ? `${offline} не в сети` : null,dash.unknownServerCount > 0 ? `Статус неизвестен: ${dash.unknownServerCount}` : null,dash.degradedServerCount > 0 ? `Ухудшение: ${dash.degradedServerCount}` : null].filter(Boolean).join(" · ") {WIDGETS[key]}
: dash.totalServers > 0 </DropdownMenuCheckboxItem>
? "все в сети" ))}
: "нет серверов", </DropdownMenuGroup>
href: "/servers", </DropdownMenuContent>
icon: <ServerIcon />, </DropdownMenu>
iconClassName: "text-muted-foreground", <Button type="button" onClick={dash.retry} disabled={dash.refreshing}>Обновить данные</Button>
variant: offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0 ? "warning" : "default", </>
}, }
{
id: "overlay",
label: "Туннели работают",
value: dash.availability.overlay ? String(dash.overlay.up) : "—",
hint: !dash.availability.overlay ? "не все источники доступны" : !dash.reliable.overlay ? "Последний успешный снимок; не все источники обновлены" : dash.overlay.total > 0 ? `Не работают: ${dash.overlay.down}` : "нет туннелей",
href: "/gre",
icon: <CableIcon />,
iconClassName: "text-info",
variant: dash.overlay.down > 0 ? "warning" : "default",
},
{
id: "bgp",
label: "Префиксы BGP",
value: dash.bgp?.prefixSum != null ? fmtIntRu(dash.bgp.prefixSum) : "—",
hint: dash.bgp ? `Сессий установлено: ${dash.bgp.establishedCount ?? "неизвестно"}${dash.bgp.prefixSum === null ? " · префиксы неизвестны" : ""}` : "нет данных",
href: "/bgp",
icon: <GitMergeIcon />,
iconClassName: "text-primary",
},
{
id: "health",
label: "Проверки с проблемами",
value: dash.availability.probes && dash.unknownProbeCount===0 ? String(health) : "—",
hint: dash.availability.probes ? `${dash.probeDown} ошибок · ${dash.probeWarn} предупреждений${dash.unknownProbeCount>0?` · неизвестны: ${dash.unknownProbeCount}`:""}` : "нет данных",
href: "/uptime",
icon: <BellIcon />,
iconClassName: health > 0 ? "text-destructive" : "text-muted-foreground",
variant: health > 0 ? "destructive" : "default",
},
]}
/> />
<section aria-labelledby="dashboard-attention-title" className="flex min-w-0 flex-col gap-2"> <div className="flex flex-col gap-5">
<h2 id="dashboard-attention-title" className="text-sm font-semibold">Требует внимания</h2> {failedSources.length > 0 ? (
<AttentionQueue <Alert variant="warning">
className="lg:grid-cols-3" <CircleAlertIcon />
columns={[ <AlertTitle>Не все источники доступны.</AlertTitle>
{ <AlertDescription>
id: "nodes", Последний успешный снимок; не все источники обновлены. Не обновлены: {failedSources.map((row) => row.name).join(", ")}. Проверьте состояние источников ниже.
title: "Серверы", </AlertDescription>
icon: ServerIcon, <AlertAction>
count: dash.attentionServers.length, <Button type="button" size="sm" variant="outline" onClick={() => setTab("src")}>Объяснить</Button>
countVariant: "warning-light", </AlertAction>
emptyTitle: dash.reliable.servers ? (dash.totalServers > 0 ? "Серверы без проблем" : "Нет серверов") : "Состояние не подтверждено", </Alert>
emptyDescription: dash.reliable.servers ? "Нет включённых серверов с ошибками доступности." : "Проверьте состояние источников выше.", ) : null}
children: <AttentionRows rows={dash.attentionServers} />,
},
{
id: "overlay",
title: "Туннели",
icon: CableIcon,
iconClassName: "text-info",
count: dash.attentionOverlay.length,
countVariant: "destructive-light",
emptyTitle: dash.reliable.overlay ? (dash.overlay.total > 0 ? "Туннели работают" : "Нет туннелей") : "Состояние не подтверждено",
emptyDescription: dash.reliable.overlay ? "В GRE, WireGuard и VXLAN проблем не обнаружено." : "Проверьте состояние источников выше.",
children: <AttentionRows rows={dash.attentionOverlay} />,
},
{
id: "probes",
title: "Проверки",
icon: HeartPulseIcon,
iconClassName: "text-destructive",
count: dash.attentionProbes.length,
countVariant: "destructive-light",
emptyTitle: dash.reliable.probes ? (dash.probeCount > 0 ? "Проверки без ошибок" : "Нет активных проверок") : "Состояние не подтверждено",
emptyDescription: dash.reliable.probes ? "Нет ошибок и предупреждений активных проверок." : "Проверьте состояние источников выше.",
children: <AttentionRows rows={dash.attentionProbes} />,
},
]}
/>
</section>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[2fr_1fr]"> {show("cap") ? (
<OpsPanel <CapacityGrid
title="Задержка до серверов" label="Ёмкость сети"
description={ items={[
dash.latency.kind === "mock" || dash.latency.kind === "live" {
? dash.latency.subtitle id: "fleet",
: dash.latency.kind === "loading" title: "Серверы онлайн",
? "Загрузка…" caption: serverCaption,
: "Нет серии RTT" value: dash.availability.servers ? dash.onlineCount : null,
} total: dash.availability.servers ? dash.totalServers : null,
contentClassName="px-3 pb-3" tone: serverTrouble ? "wn" : "ok",
> icon: <ServerIcon />,
{dash.latency.kind === "loading" && ( href: "/servers",
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" /> },
)} {
{dash.latency.kind === "empty" && ( id: "overlay",
<p className="text-muted-foreground px-4 py-10 text-center text-sm">{dash.latency.message}</p> title: "Туннели работают",
)} caption: !dash.availability.overlay ? "не все источники доступны" : !dash.reliable.overlay ? "Последний успешный снимок; не все источники обновлены" : dash.overlay.total > 0 ? `GRE · WireGuard · VXLAN · не работают: ${dash.overlay.down}` : "нет туннелей",
{(dash.latency.kind === "mock" || dash.latency.kind === "live") && ( value: dash.availability.overlay ? dash.overlay.up : null,
<LatencyChart series={dash.latency.series} labels={dash.latency.labels} /> total: dash.availability.overlay ? dash.overlay.total : null,
)} tone: dash.overlay.down > 0 ? "wn" : "ok",
</OpsPanel> icon: <CableIcon />,
href: "/gre",
<OpsPanel },
title="Последние события" {
description="Система и BGP" id: "health",
headerRight={ title: "Проверки с проблемами",
<Link href="/alerts" className={cn(buttonVariants({ variant: "ghost", size: "sm" }), "h-7 text-xs")}> caption: dash.availability.probes ? `${dash.probeDown} ошибок · ${dash.probeWarn} предупреждений${dash.unknownProbeCount > 0 ? ` · неизвестны: ${dash.unknownProbeCount}` : ""}` : "нет данных",
Все → value: dash.availability.probes && dash.unknownProbeCount === 0 ? problems : null,
</Link> total: dash.availability.probes && dash.unknownProbeCount === 0 ? dash.probeCount : null,
} tone: problems > 0 ? "er" : "ok",
> icon: <HeartPulseIcon />,
<DashboardEventsTimeline href: "/uptime",
events={dash.recentEvents} },
loading={dash.eventsLoading} ]}
error={dash.eventsError}
/> />
</OpsPanel> ) : null}
</div>
<div> {show("spark") ? (
<OpsPanel <SparkKpiGrid
title="Пропускная способность" label="Показатели сети"
description={dash.traffic?.demo ? "Суммарный RX / TX · демо" : "Суммарная история RX / TX · 1 ч; значения — последний измеренный снимок"} items={[
headerRight={<Link href="/traffic" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}>Трафик →</Link>} {
contentClassName="px-3 pb-3" id: "bgp",
> title: "Префиксы BGP",
{dash.loading && !dash.traffic ? ( value: dash.bgp?.prefixSum != null ? fmtIntRu(dash.bgp.prefixSum) : "—",
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" /> footnote: dash.bgp ? `Сессий установлено: ${dash.bgp.establishedCount ?? "неизвестно"}${dash.bgp.prefixSum === null ? " · префиксы неизвестны" : ""}` : "нет данных",
) : !dash.traffic ? ( href: "/bgp",
<p className="text-muted-foreground px-4 py-10 text-center text-sm"> },
Нет данных трафика за последний час.{" "} {
<Link href="/traffic" className="underline underline-offset-2"> id: "rtt",
Открыть трафик title: "Средний RTT",
</Link> value: rttNow ?? "—",
</p> unit: rttNow != null ? " мс" : undefined,
) : ( series: latencySeries,
<> delta: seriesDelta(latencySeries, "wn", "ok"),
<div className="flex flex-wrap items-center gap-3 px-2 py-3 text-xs"> footnote: "за 1 ч",
{dash.traffic.demo ? <Badge variant="outline" size="sm">демо</Badge> : !dash.traffic.observationsKnown ? <Badge variant="outline" size="sm">Измерения не подтверждены API</Badge> : null} href: "/uptime",
<span className="tabular-nums">RX {dash.traffic.rxNow===null?"—":fmtRate(dash.traffic.rxNow)}</span> },
<span className="tabular-nums">TX {dash.traffic.txNow===null?"—":fmtRate(dash.traffic.txNow)}</span> {
id: "rx",
title: "RX",
value: dash.traffic?.rxNow != null ? fmtRate(dash.traffic.rxNow) : "—",
series: dash.traffic?.rx.filter((v): v is number => typeof v === "number"),
delta: seriesDelta(dash.traffic?.rx.filter((v): v is number => typeof v === "number")),
footnote: "суммарно · 1 ч",
href: "/traffic",
},
{
id: "tx",
title: "TX",
value: dash.traffic?.txNow != null ? fmtRate(dash.traffic.txNow) : "—",
series: dash.traffic?.tx.filter((v): v is number => typeof v === "number"),
delta: seriesDelta(dash.traffic?.tx.filter((v): v is number => typeof v === "number")),
footnote: "суммарно · 1 ч",
href: "/traffic",
},
]}
/>
) : null}
{show("sources") ? <DashboardSourcesSummary rows={sourceRows} refreshing={dash.refreshing} onRefresh={dash.retry} /> : null}
<Tabs value={tab} onValueChange={(value) => setTab(String(value))} className="gap-5">
<TabsList variant="line" className="h-auto w-full justify-start gap-1 overflow-x-auto border-b p-0">
<TabsTrigger value="over" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">Обзор</TabsTrigger>
<TabsTrigger value="src" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">
Источники и время получения
<Badge variant="secondary" className="font-mono">{sourceRows.length}</Badge>
</TabsTrigger>
<TabsTrigger value="rtt" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">История RTT</TabsTrigger>
</TabsList>
<TabsContent value="over" className="flex flex-col gap-5">
{show("health") ? (
<DashboardHealth
factors={[
{ label: "Потери пакетов", value: avgLoss == null ? "—" : `${avgLoss.toLocaleString("ru-RU", { maximumFractionDigits: 1 })}%`, ratio: probesMeasured.length ? probesMeasured.filter((p) => (p.loss ?? 0) === 0).length / probesMeasured.length : null },
{ label: "Пробы в норме", value: probesMeasured.length ? `${probesMeasured.filter((p) => p.status === "up").length} из ${probesMeasured.length}` : "—", ratio: probesMeasured.length ? probesMeasured.filter((p) => p.status === "up").length / probesMeasured.length : null },
{ label: "Свежесть данных", value: `${okSources} из ${sourceRows.length}`, ratio: sourceRows.length ? okSources / sourceRows.length : null },
{ label: "Серверы в сети", value: dash.availability.servers ? `${dash.onlineCount} из ${dash.totalServers}` : "—", ratio: dash.availability.servers && dash.totalServers > 0 ? dash.onlineCount / dash.totalServers : null },
{ label: "Туннели", value: dash.availability.overlay ? `${dash.overlay.up} из ${dash.overlay.total}` : "—", ratio: dash.availability.overlay && dash.overlay.total > 0 ? dash.overlay.up / dash.overlay.total : null },
]}
/>
) : null}
{show("timeline") ? <DashboardIncidents events={dash.recentEvents} loading={dash.eventsLoading} error={dash.eventsError} /> : null}
{show("path") ? <InternetPathPanel model={dash.internetPath} loading={dash.internetPathLoading} error={dash.isLive ? dash.internetPathError : null} /> : null}
{show("attention") ? <DashboardAttentionGrid rows={attentionRows} emptyNotes={emptyNotes} /> : null}
{show("latency") ? (
<SectionFrame title="Задержка до серверов" description={latencyDescription} panelClassName="px-3.5 pt-3.5">
{latencyBody}
</SectionFrame>
) : null}
{show("traffic") ? (
<SectionFrame
title="Пропускная способность"
description={dash.traffic?.demo ? "Суммарный RX / TX · демо" : "Суммарная история RX / TX · 1 ч; значения — последний измеренный снимок"}
actions={<Link href="/traffic" className={buttonVariants({ variant: "outline", size: "sm" })}>Трафик →</Link>}
panelClassName="px-3.5 pt-3.5 pb-2"
>
{dash.loading && !dash.traffic ? (
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
) : !dash.traffic ? (
<p className="text-muted-foreground px-4 py-10 text-center text-sm">
Нет данных трафика за последний час.{" "}
<Link href="/traffic" className="underline underline-offset-2">Открыть трафик</Link>
</p>
) : (
<>
<div className="flex flex-wrap items-center gap-3 px-1 pb-3 text-xs">
{dash.traffic.demo ? <Badge variant="outline" size="sm">демо</Badge> : !dash.traffic.observationsKnown ? <Badge variant="outline" size="sm">Измерения не подтверждены API</Badge> : null}
<span className="tabular-nums">RX {dash.traffic.rxNow === null ? "—" : fmtRate(dash.traffic.rxNow)}</span>
<span className="tabular-nums">TX {dash.traffic.txNow === null ? "—" : fmtRate(dash.traffic.txNow)}</span>
</div>
<TrafficRxTxChart rx={dash.traffic.rx} tx={dash.traffic.tx} range="1h" embedded />
</>
)}
</SectionFrame>
) : null}
{show("probes") ? (
<SectionFrame
title="Активные пробы"
description={<span className={dash.error && dash.isLive ? "text-destructive" : undefined}>{dash.probesSubtitle}</span>}
icon={<TableIcon />}
actions={<Link href="/uptime" className={buttonVariants({ variant: "outline", size: "sm" })}>Мониторинг →</Link>}
>
{dash.activeProbes.length === 0 && !dash.probesLoading ? (
<EmptyState
className="py-10"
title={dash.availability.probes ? "Нет проб на дашборде" : "Данные проб недоступны"}
description={dash.availability.probes ? "Включите пробу и отметьте ★ на странице мониторинга." : "Повторите обновление данных."}
action={<Link href="/uptime" className={buttonVariants({ variant: "outline", size: "sm" })}>Открыть мониторинг</Link>}
/>
) : (
<DashboardActiveProbesDataGrid probes={dash.activeProbes} catalog={dash.servers} isLoading={dash.probesLoading} emptyDescription="Нет проб с звездой на дашборде." />
)}
</SectionFrame>
) : null}
{show("links") ? (
<DashboardQuickLinks
links={[
{ id: "traffic", title: "Трафик", description: "Приём, передача и потоки IPFIX", href: "/traffic" },
{ id: "map", title: "Карта сети", description: "Топология GRE и WAN", href: "/network-map" },
{ id: "filters", title: "Фильтры", description: "Правила обхода и списки · цепочки filter / nat", href: "/filters" },
{ id: "backups", title: "Бэкапы", description: "Снапшоты и расписание", href: "/backups" },
{ id: "uptime", title: "Мониторинг", description: "Сессии и префиксы · пробы", href: "/uptime" },
]}
/>
) : null}
</TabsContent>
<TabsContent value="src" className="flex flex-col gap-5">
{failedSources.length > 0 ? (
<Alert variant="destructive">
<CircleAlertIcon />
<AlertTitle>Не обновлены источники: {failedSources.length}</AlertTitle>
<AlertDescription>Последние полученные данные сохранены. Если источник ещё не загрузился, его показатели неизвестны.</AlertDescription>
</Alert>
) : null}
<SectionFrame title="Источники и время получения" description="Каждый источник дашборда: состояние, время получения и замера" icon={<ChartColumnIcon />}>
<div className="overflow-x-auto">
<table className="w-full min-w-[640px] text-sm">
<thead className="bg-muted/55 text-muted-foreground text-xs">
<tr className="h-10 border-b text-left">
<th className="px-3.5 font-medium">Источник</th>
<th className="px-3 font-medium">Статус</th>
<th className="px-3 font-medium">Получено</th>
<th className="px-3 font-medium">Замер</th>
<th className="px-3 font-medium">Ошибка</th>
</tr>
</thead>
<tbody>
{sourceRows.map((row) => (
<tr key={row.key} className="h-[52px] border-b last:border-b-0">
<td className="px-3.5 font-mono text-[13px] font-medium">{row.name}</td>
<td className="px-3"><ToneBadge tone={row.tone as Tone}>{row.label}</ToneBadge></td>
<td className="px-3 font-mono text-[12.5px]">{row.receivedAt != null ? new Date(row.receivedAt).toLocaleString("ru-RU") : "—"}</td>
<td className="px-3 font-mono text-[12.5px]">{row.sampledAt ? new Date(row.sampledAt).toLocaleString("ru-RU") : "—"}</td>
<td className="text-muted-foreground px-3 text-xs">{sourceErrorText(row) ?? "—"}</td>
</tr>
))}
</tbody>
</table>
</div> </div>
<TrafficRxTxChart rx={dash.traffic.rx} tx={dash.traffic.tx} range="1h" embedded /> </SectionFrame>
</> </TabsContent>
)}
</OpsPanel>
<TabsContent value="rtt" className="flex flex-col gap-5">
<SectionFrame title="История RTT по источникам" description={latencyDescription} panelClassName="px-3.5 pt-3.5">
{latencyBody}
</SectionFrame>
</TabsContent>
</Tabs>
</div> </div>
<InternetPathPanel
model={dash.internetPath}
loading={dash.internetPathLoading}
error={dash.isLive ? dash.internetPathError : null}
/>
<OpsPanel
title="Активные пробы"
description={
<span className={dash.error && dash.isLive ? "text-destructive" : undefined}>{dash.probesSubtitle}</span>
}
headerRight={
<Link href="/uptime" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}>
Мониторинг →
</Link>
}
contentClassName="px-0 pb-0"
>
{dash.activeProbes.length === 0 && !dash.probesLoading ? (
<EmptyState
className="py-10"
title={dash.availability.probes ? "Нет проб на дашборде" : "Данные проб недоступны"}
description={dash.availability.probes ? "Включите пробу и отметьте ★ на странице мониторинга." : "Повторите обновление данных."}
action={
<Link href="/uptime" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
Открыть мониторинг
</Link>
}
/>
) : (
<DashboardActiveProbesDataGrid
probes={dash.activeProbes}
catalog={dash.servers}
isLoading={dash.probesLoading}
emptyDescription="Нет проб с звездой на дашборде."
/>
)}
</OpsPanel>
<QuickActionGrid
title="Быстрые переходы"
description="Другие разделы управления сетью"
actions={[
{
id: "traffic",
title: "Трафик",
description: "Приём, передача и потоки IPFIX",
href: "/traffic",
icon: <ActivityIcon />,
iconClassName: "text-info",
},
{
id: "map",
title: "Карта сети",
description: "Топология GRE и WAN",
href: "/network-map",
icon: <MapIcon />,
iconClassName: "text-primary",
},
{
id: "filters",
title: "Фильтры",
description: "Правила обхода и списки",
href: "/filters",
icon: <FilterIcon />,
iconClassName: "text-info",
},
{
id: "firewall",
title: "Firewall",
description: "Цепочки filter / nat",
href: "/firewall",
icon: <ShieldIcon />,
iconClassName: "text-warning",
},
{
id: "backups",
title: "Бэкапы",
description: "Снапшоты и расписание",
href: "/backups",
icon: <HardDriveIcon />,
iconClassName: "text-muted-foreground",
},
{
id: "bgp",
title: "BGP",
description: "Сессии и префиксы",
href: "/bgp",
icon: <GitMergeIcon />,
iconClassName: "text-primary",
},
]}
/>
</div> </div>
</div> </div>
</div> </div>
+78 -33
View File
@@ -17,7 +17,7 @@ import { Separator } from "@/components/ui/separator"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { filtersResponseSchema, filtersMutationSchema, filtersGreResponseSchema, filtersRecursiveResponseSchema } from "@/lib/filters-response" import { filtersResponseSchema, filtersMutationSchema, filtersGreResponseSchema, filtersRecursiveResponseSchema } from "@/lib/filters-response"
import { firewallServersSchema } from "@/lib/firewall-response" import { firewallServersSchema } from "@/lib/firewall-response"
import { requestJson } from "@/shared/api/http-client" import { ApiClientError, requestJson } from "@/shared/api/http-client"
import { import {
servers, greTunnels, serverFilterRulesets, filters as mockFiltersCatalog, servers, greTunnels, serverFilterRulesets, filters as mockFiltersCatalog,
type FilterRule, type ServerFilterRuleset, type Server, type GreTunnel, type FilterRule, type ServerFilterRuleset, type Server, type GreTunnel,
@@ -252,7 +252,7 @@ function generateCombinedRouterOSConfig(
// ── shared components ────────────────────────────────────────────────────────── // ── shared components ──────────────────────────────────────────────────────────
function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" }) { function TypeChip({ type }: { type: import("@mmapp/contracts/servers").ServerType }) {
return ( return (
<span className={cn( <span className={cn(
"inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-bold border shrink-0", "inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-bold border shrink-0",
@@ -261,7 +261,7 @@ function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" })
? "bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20" ? "bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20"
: "bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20", : "bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20",
)}> )}>
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : "EN"} {type === "jump-host" ? "JH" : type === "home-router" ? "HR" : type === "ix-node" ? "IX" : "EN"}
</span> </span>
) )
} }
@@ -874,7 +874,7 @@ function CopyRulesSheet({
greByServer: Record<string, GreTunnel[]> greByServer: Record<string, GreTunnel[]>
ensureGreFor?: (serverId: string) => void ensureGreFor?: (serverId: string) => void
recRoutesByServer: Record<string, RecursiveRouteLite[]> recRoutesByServer: Record<string, RecursiveRouteLite[]>
ensureRecursiveFor?: (serverId: string) => void ensureRecursiveFor?: (serverId: string) => Promise<void>
catalogReady?: GatewayReadiness catalogReady?: GatewayReadiness
}) { }) {
const [selected, setSelected] = useState<Set<string>>(() => new Set(sourceRules.map(r => r.id))) const [selected, setSelected] = useState<Set<string>>(() => new Set(sourceRules.map(r => r.id)))
@@ -1229,7 +1229,11 @@ function CopyRulesSheet({
</fieldset> </fieldset>
{targetId && !mappingReady && <div className="px-5 py-3 flex flex-col gap-2"> {targetId && !mappingReady && <div className="px-5 py-3 flex flex-col gap-2">
<p role="alert" className="text-sm text-destructive">Каталоги или сопоставление шлюзов не подтверждены. Копирование маршрутов заблокировано.</p> <p role="alert" className="text-sm text-destructive">Каталоги или сопоставление шлюзов не подтверждены. Копирование маршрутов заблокировано.</p>
<Button variant="outline" disabled={copying} onClick={() => { for (const id of [sourceServerId, targetId]) { ensureGreFor?.(id); ensureRecursiveFor?.(id) } }}>Обновить шлюзы</Button> <Button variant="outline" disabled={copying} onClick={() => {
ensureGreFor?.(sourceServerId)
ensureGreFor?.(targetId)
void ensureRecursiveFor?.(sourceServerId).then(() => ensureRecursiveFor(targetId))
}}>Обновить шлюзы</Button>
</div>} </div>}
{copyError && <p role="alert" className="px-5 py-3 text-sm text-destructive">{copyError}</p>} {copyError && <p role="alert" className="px-5 py-3 text-sm text-destructive">{copyError}</p>}
{copying && <p role="status" className="px-5 py-2 text-sm text-muted-foreground">Ожидание подтверждения копирования…</p>} {copying && <p role="status" className="px-5 py-2 text-sm text-muted-foreground">Ожидание подтверждения копирования…</p>}
@@ -1268,6 +1272,28 @@ function makeApiFetch(backendUrl: string) {
} }
} }
const configurationBusyMessage = "Конфигурация временно занята другой операцией"
function isConfigurationBusy(error: unknown): boolean {
if (!(error instanceof ApiClientError) || error.status !== 409) return false
const payload = error.payload
return (typeof payload === "object" && payload !== null && "code" in payload && payload.code === "CONFIGURATION_BUSY")
|| /^(?:Глобальная конфигурация|Конфигурация сервера) изменяется другой операцией$/.test(error.message)
}
async function readFiltersWithRetry<T>(read: () => Promise<T>, isCurrent: () => boolean): Promise<T> {
for (const delay of [350, 1000]) {
try {
return await read()
} catch (error) {
if (!isConfigurationBusy(error) || !isCurrent()) throw error
await new Promise(resolve => setTimeout(resolve, delay))
if (!isCurrent()) throw error
}
}
return read()
}
function FiltersPage() { function FiltersPage() {
const { mode, backendUrl } = useDataSource() const { mode, backendUrl } = useDataSource()
const mounted = useRef(true) const mounted = useRef(true)
@@ -1336,7 +1362,10 @@ function FiltersPage() {
setGatewayReady(prev => ({ ...prev, [serverId]: { ...prev[serverId], [kind]: false } })) setGatewayReady(prev => ({ ...prev, [serverId]: { ...prev[serverId], [kind]: false } }))
try { try {
const path = kind === "gre" ? "/api/filters/gre-tunnels" : "/api/recursive-routes" const path = kind === "gre" ? "/api/filters/gre-tunnels" : "/api/recursive-routes"
const payload = await apiFetch<unknown>(`${path}?serverId=${encodeURIComponent(serverId)}`) const payload = await readFiltersWithRetry(
() => apiFetch<unknown>(`${path}?serverId=${encodeURIComponent(serverId)}`),
() => mounted.current && gatewayEpoch.current[key] === epoch,
)
if (!mounted.current || gatewayEpoch.current[key] !== epoch) return if (!mounted.current || gatewayEpoch.current[key] !== epoch) return
if (kind === "gre") { if (kind === "gre") {
const parsed = filtersGreResponseSchema.safeParse(payload) const parsed = filtersGreResponseSchema.safeParse(payload)
@@ -1352,7 +1381,9 @@ function FiltersPage() {
setGatewayErrors(prev => ({ ...prev, [serverId]: { ...prev[serverId], [kind]: undefined } })) setGatewayErrors(prev => ({ ...prev, [serverId]: { ...prev[serverId], [kind]: undefined } }))
} catch (error) { } catch (error) {
if (!mounted.current || gatewayEpoch.current[key] !== epoch) return if (!mounted.current || gatewayEpoch.current[key] !== epoch) return
setGatewayErrors(prev => ({ ...prev, [serverId]: { ...prev[serverId], [kind]: error instanceof Error ? error.message : "Каталог шлюзов недоступен" } })) const message = isConfigurationBusy(error) ? configurationBusyMessage
: error instanceof Error ? error.message : "Каталог шлюзов недоступен"
setGatewayErrors(prev => ({ ...prev, [serverId]: { ...prev[serverId], [kind]: message } }))
} }
}, [isLive, apiFetch]) }, [isLive, apiFetch])
const ensureGreTunnels = useCallback((serverId: string) => loadGatewayCatalog(serverId, "gre"), [loadGatewayCatalog]) const ensureGreTunnels = useCallback((serverId: string) => loadGatewayCatalog(serverId, "gre"), [loadGatewayCatalog])
@@ -1374,7 +1405,8 @@ function FiltersPage() {
const [movePending, setMovePending] = useState(false) const [movePending, setMovePending] = useState(false)
const [moveError, setMoveError] = useState<string | null>(null) const [moveError, setMoveError] = useState<string | null>(null)
const moveLock = useRef(false) const moveLock = useRef(false)
const [liveStale, setLiveStale] = useState(false) const [rulesReadFailure, setRulesReadFailure] = useState<"busy" | "unavailable" | null>(null)
const liveStale = rulesReadFailure !== null
const readEpoch = useRef(0) const readEpoch = useRef(0)
const [readyServerId, setReadyServerId] = useState<string | null>(null) const [readyServerId, setReadyServerId] = useState<string | null>(null)
const [rulesReading, setRulesReading] = useState(false) const [rulesReading, setRulesReading] = useState(false)
@@ -1394,7 +1426,7 @@ function FiltersPage() {
setRulesets(buildRulesets(servers, serverFilterRulesets)) setRulesets(buildRulesets(servers, serverFilterRulesets))
setSelectedServerId(servers[0]?.id ?? "") setSelectedServerId(servers[0]?.id ?? "")
setLiveLoadState("idle") setLiveLoadState("idle")
setLiveStale(false) setRulesReadFailure(null)
}) })
return return
} }
@@ -1454,8 +1486,9 @@ function FiltersPage() {
setReadyServerId(null) setReadyServerId(null)
setRulesReading(true) setRulesReading(true)
try { try {
const payload = await apiFetch<unknown>( const payload = await readFiltersWithRetry(
`/api/filters/rules?serverId=${encodeURIComponent(serverId)}`, () => apiFetch<unknown>(`/api/filters/rules?serverId=${encodeURIComponent(serverId)}`),
() => mounted.current && epoch === readEpoch.current,
) )
if (epoch !== readEpoch.current) return false if (epoch !== readEpoch.current) return false
const parsed = filtersResponseSchema.safeParse(payload) const parsed = filtersResponseSchema.safeParse(payload)
@@ -1469,35 +1502,47 @@ function FiltersPage() {
if (!has) return [...prev, { serverId, rules: liveRules }] if (!has) return [...prev, { serverId, rules: liveRules }]
return prev.map((rs) => rs.serverId === serverId ? { ...rs, rules: liveRules } : rs) return prev.map((rs) => rs.serverId === serverId ? { ...rs, rules: liveRules } : rs)
}) })
setLiveStale(false) setRulesReadFailure(null)
setReadyServerId(serverId) setReadyServerId(serverId)
setRulesReceipt(prev => ({ ...prev, [serverId]: { at: new Date().toISOString(), kind: "read" } })) setRulesReceipt(prev => ({ ...prev, [serverId]: { at: new Date().toISOString(), kind: "read" } }))
return true return true
} catch (err) { } catch (err) {
if (epoch !== readEpoch.current) return false if (epoch !== readEpoch.current) return false
setLiveStale(true) const busy = isConfigurationBusy(err)
toast.error("Не удалось прочитать правила с роутера", { description: String(err) }) setRulesReadFailure(busy ? "busy" : "unavailable")
if (!busy) toast.error("Не удалось прочитать правила с роутера", {
description: err instanceof Error ? err.message : "Ошибка чтения правил",
})
return false return false
} finally { } finally {
if (epoch === readEpoch.current) setRulesReading(false) if (epoch === readEpoch.current) setRulesReading(false)
} }
}, [isLive, apiFetch]) }, [isLive, apiFetch])
const loadServerFilters = useCallback(async (serverId: string) => {
const gre = ensureGreTunnels(serverId)
const rules = loadLiveRules(serverId)
const epoch = readEpoch.current
await rules
// Both these GETs record observations under the same exclusive application lock.
if (mounted.current && epoch === readEpoch.current) await ensureRecursiveRoutes(serverId)
await gre
}, [loadLiveRules, ensureGreTunnels, ensureRecursiveRoutes])
useEffect(() => { useEffect(() => {
if (!isLive || !selectedServerId || liveLoadState !== "idle") return if (!isLive || !selectedServerId || liveLoadState !== "idle") return
if (!liveServers.some((s) => s.id === selectedServerId)) return if (!liveServers.some((s) => s.id === selectedServerId)) return
void Promise.all([ void loadServerFilters(selectedServerId)
loadLiveRules(selectedServerId), }, [isLive, selectedServerId, liveLoadState, liveServers, loadServerFilters])
ensureGreTunnels(selectedServerId),
ensureRecursiveRoutes(selectedServerId),
])
}, [isLive, selectedServerId, liveLoadState, liveServers, ensureGreTunnels, ensureRecursiveRoutes, loadLiveRules])
const allServers = !isLive ? servers : liveServers const allServers = !isLive ? servers : liveServers
const allTunnels = !isLive ? greTunnels : (greByServer[selectedServerId] ?? []) const allTunnels = !isLive ? greTunnels : (greByServer[selectedServerId] ?? [])
const selectedServer = allServers.find(s => s.id === selectedServerId) ?? allServers[0] const selectedServer = allServers.find(s => s.id === selectedServerId) ?? allServers[0]
const totalRules = rulesets.reduce((s, r) => s + r.rules.length, 0) const totalRules = rulesets.reduce((s, r) => s + r.rules.length, 0)
const mutationsLocked = (isLive && !can("mm:filters:write")) || movePending || (isLive && (applyBusy || historyRestoring || rulesReading || readyServerId !== selectedServerId || liveStale || liveLoadState !== "idle")) const mutationsLocked = (isLive && !can("mm:filters:write")) || movePending || (isLive && (applyBusy || historyRestoring || rulesReading || readyServerId !== selectedServerId || liveStale || liveLoadState !== "idle"))
const gatewayMessages = [...new Set(Object.values(gatewayErrors[selectedServerId] ?? {}))]
.filter((message): message is string => Boolean(message) && !(rulesReadFailure === "busy" && message === configurationBusyMessage))
const gatewaysBusy = gatewayMessages.every(message => message === configurationBusyMessage)
const filterRailItems = useMemo<ServerTileItem[]>(() => ( const filterRailItems = useMemo<ServerTileItem[]>(() => (
allServers.map((s) => ({ allServers.map((s) => ({
@@ -1518,7 +1563,7 @@ function FiltersPage() {
readEpoch.current += 1 readEpoch.current += 1
setReadyServerId(null) setReadyServerId(null)
setRulesReading(false) setRulesReading(false)
setLiveStale(false) setRulesReadFailure(null)
setSheetOpen(false) setSheetOpen(false)
setPendingDelete(null) setPendingDelete(null)
setDeleteError(null) setDeleteError(null)
@@ -1552,7 +1597,9 @@ function FiltersPage() {
if (!mounted.current) return { ok: false, error: "Источник данных изменён" } if (!mounted.current) return { ok: false, error: "Источник данных изменён" }
if (applyLock.current || applyBusy || historyRestoring) return { ok: false, error: "Дождитесь завершения текущей операции" } if (applyLock.current || applyBusy || historyRestoring) return { ok: false, error: "Дождитесь завершения текущей операции" }
if (isLive && (liveStale || liveLoadState !== "idle" || (serverId === selectedServerId && readyServerId !== serverId))) { if (isLive && (liveStale || liveLoadState !== "idle" || (serverId === selectedServerId && readyServerId !== serverId))) {
const error = "Роутер недоступен — изменения заблокированы" const error = rulesReadFailure === "busy"
? configurationBusyMessage + ". Изменения недоступны до обновления правил."
: "Роутер недоступен — изменения заблокированы"
toast.error(error) toast.error(error)
return { ok: false, error } return { ok: false, error }
} }
@@ -1589,23 +1636,19 @@ function FiltersPage() {
applyLock.current = false applyLock.current = false
setApplyBusy(false) setApplyBusy(false)
} }
}, [isLive, apiFetch, applyBusy, historyRestoring, liveStale, liveLoadState, readyServerId, selectedServerId]) }, [isLive, apiFetch, applyBusy, historyRestoring, liveStale, rulesReadFailure, liveLoadState, readyServerId, selectedServerId])
const refreshFromRouter = useCallback(async () => { const refreshFromRouter = useCallback(async () => {
if (!isLive || !selectedServerId || !mounted.current || applyLock.current || applyBusy || historyRestoring) return if (!isLive || !selectedServerId || !mounted.current || applyLock.current || applyBusy || historyRestoring) return
applyLock.current = true applyLock.current = true
setApplyBusy(true) setApplyBusy(true)
try { try {
await loadLiveRules(selectedServerId) await loadServerFilters(selectedServerId)
await Promise.all([
ensureGreTunnels(selectedServerId),
ensureRecursiveRoutes(selectedServerId),
])
} finally { } finally {
applyLock.current = false applyLock.current = false
setApplyBusy(false) setApplyBusy(false)
} }
}, [isLive, selectedServerId, applyBusy, historyRestoring, loadLiveRules, ensureGreTunnels, ensureRecursiveRoutes]) }, [isLive, selectedServerId, applyBusy, historyRestoring, loadServerFilters])
useEffect(() => () => { historyEpoch.current += 1; readEpoch.current += 1 }, [selectedServerId, backendUrl, isLive]) useEffect(() => () => { historyEpoch.current += 1; readEpoch.current += 1 }, [selectedServerId, backendUrl, isLive])
@@ -1653,7 +1696,7 @@ function FiltersPage() {
if (!await loadLiveRules(selectedServerId)) throw new Error("Версия применена, но актуальные правила не прочитаны — обновите данные") if (!await loadLiveRules(selectedServerId)) throw new Error("Версия применена, но актуальные правила не прочитаны — обновите данные")
} }
if (!mounted.current) return if (!mounted.current) return
setLiveStale(false) setRulesReadFailure(null)
setReadyServerId(selectedServerId) setReadyServerId(selectedServerId)
await loadRevisions() await loadRevisions()
if (!mounted.current) return if (!mounted.current) return
@@ -1879,15 +1922,17 @@ function FiltersPage() {
<Button variant="outline" size="sm" onClick={() => setLoadAttempt(n => n + 1)}>Повторить загрузку</Button> <Button variant="outline" size="sm" onClick={() => setLoadAttempt(n => n + 1)}>Повторить загрузку</Button>
</div> </div>
)} )}
{isLive && Object.values(gatewayErrors[selectedServerId] ?? {}).some(Boolean) && <div className="border-b px-6 py-3 flex items-center gap-3"> {isLive && gatewayMessages.length > 0 && <div className="border-b px-6 py-3 flex items-center gap-3">
<p role="alert" className="text-xs text-destructive">{Object.values(gatewayErrors[selectedServerId] ?? {}).filter(Boolean).join(" · ")}. Сохранены последние каталоги шлюзов.</p> <p role={gatewaysBusy ? "status" : "alert"} className={cn("text-xs", gatewaysBusy ? "text-muted-foreground" : "text-destructive")}>{gatewayMessages.join(" · ")}. Сохранены последние каталоги шлюзов.</p>
<Button variant="outline" size="sm" disabled={applyBusy} onClick={() => { void ensureGreTunnels(selectedServerId); void ensureRecursiveRoutes(selectedServerId) }}>Обновить шлюзы</Button> <Button variant="outline" size="sm" disabled={applyBusy} onClick={() => { void ensureGreTunnels(selectedServerId); void ensureRecursiveRoutes(selectedServerId) }}>Обновить шлюзы</Button>
</div>} </div>}
{isLive && rulesReading && <p role="status" className="border-b px-6 py-2 text-xs text-muted-foreground">Чтение актуальных правил устройства… Изменения временно заблокированы.</p>} {isLive && rulesReading && <p role="status" className="border-b px-6 py-2 text-xs text-muted-foreground">Чтение актуальных правил устройства… Изменения временно заблокированы.</p>}
{isLive && liveStale && liveLoadState !== "error" && ( {isLive && liveStale && liveLoadState !== "error" && (
<div className="shrink-0 border-b border-amber-500/30 bg-amber-500/10 px-6 py-2.5 text-xs text-amber-700 dark:text-amber-400 flex items-center gap-2"> <div className="shrink-0 border-b border-amber-500/30 bg-amber-500/10 px-6 py-2.5 text-xs text-amber-700 dark:text-amber-400 flex items-center gap-2">
<AlertTriangleIcon className="size-3.5 shrink-0" /> <AlertTriangleIcon className="size-3.5 shrink-0" />
Роутер недоступен — показан кэш. Изменения заблокированы, пока не удастся прочитать CHR. {rulesReadFailure === "busy"
? configurationBusyMessage + ". Показаны последние правила. Изменения недоступны до обновления правил."
: "Роутер недоступен — показан кэш. Изменения заблокированы, пока не удастся прочитать CHR."}
</div> </div>
)} )}
<div className="border-b px-4 py-3 flex items-center gap-3 flex-wrap shrink-0 md:px-6"> <div className="border-b px-4 py-3 flex items-center gap-3 flex-wrap shrink-0 md:px-6">
+2 -1
View File
@@ -1,5 +1,6 @@
"use client" "use client"
import { serverTypeSchema } from "@mmapp/contracts/servers"
import { can } from "@/lib/auth" import { can } from "@/lib/auth"
import { z } from "zod" import { z } from "zod"
@@ -174,7 +175,7 @@ function mapBackendServer(s: BackendServer): InventoryServer {
const ipsecInventorySchema = z.array(z.object({ const ipsecInventorySchema = z.array(z.object({
id: z.number().int().positive(), name: z.string(), host: z.string(), enabled: z.boolean(), id: z.number().int().positive(), name: z.string(), host: z.string(), enabled: z.boolean(),
country: z.string().optional().default("UN"), country: z.string().optional().default("UN"),
type: z.enum(["jump-host", "exit-node", "home-router"]).optional(), type: serverTypeSchema.optional(),
status: z.enum(["online", "offline", "degraded"]).nullable().optional(), status: z.enum(["online", "offline", "degraded"]).nullable().optional(),
latency: z.number().nullable().optional(), asn: z.string().optional(), latency: z.number().nullable().optional(), asn: z.string().optional(),
})).refine(rows => new Set(rows.map(row => row.id)).size === rows.length) })).refine(rows => new Set(rows.map(row => row.id)).size === rows.length)
+209
View File
@@ -0,0 +1,209 @@
"use client"
import { useEffect, useState, type ReactNode } from "react"
import type { IxBondBundle, IxBondCandidate, IxBondCatalog, IxBondEdit, IxBondMode, IxSavedBond, IxSegment } from "@mmapp/contracts/internet-exchange"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Field, FieldLabel } from "@/components/ui/field"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { requestJson } from "@/shared/api/http-client"
import { nodeLabel, type IxNode } from "./ix-view"
import { IxExistingTransport } from "./ix-existing-transport"
import { toast } from "sonner"
import { copyIxImportLink } from "./ix-import-link"
const modes = [
{ value: "failover", label: "Основной и резервные" },
{ value: "equal", label: "Параллельно, поровну" },
{ value: "weighted", label: "Параллельно, по весам" },
] as const
type Member = IxBondEdit["members"][number]
type Ref = Pick<Member, "segmentId" | "interfaceName" | "serverId">
export type IxRowBondAction = (binding: Pick<Ref, "interfaceName" | "serverId">) => { label: string; open: () => void } | undefined
const memberKey = (m: Pick<Member, "segmentId" | "interfaceName" | "serverId">) => [m.segmentId, m.serverId, m.interfaceName].join("/")
const memberRef = ({ segmentId, serverId, appliedRevision, interfaceName }: IxBondCandidate): Member => ({ segmentId, serverId, appliedRevision, interfaceName, weight: 1 })
const modeLabel = (mode: IxBondMode) => modes.find(item => item.value === mode)?.label
export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly, download, live, children }: {
segmentId: string; segments: IxSegment[]; backendUrl: string; nodes: IxNode[]; readOnly: boolean; live: boolean
download: (filename: string, text: string) => void
children: (action: IxRowBondAction, catalog: IxBondCatalog, groups: (clientId: string) => ReactNode, unassigned: ReactNode) => ReactNode
}) {
const [catalog, setCatalog] = useState<IxBondCatalog>({ groups: [], candidates: [] })
const [reload, setReload] = useState(0)
const [draft, setDraft] = useState<IxBondEdit | null>(null)
const [direct, setDirect] = useState("")
const [error, setError] = useState("")
const [busy, setBusy] = useState(false)
const [remove, setRemove] = useState(false)
const [confirmedMembers, setConfirmedMembers] = useState("")
const [importing, setImporting] = useState(false)
const [initialInterface, setInitialInterface] = useState<Pick<Ref, "serverId" | "interfaceName">>()
useEffect(() => {
if (!live) return
const ctl = new AbortController()
void requestJson<IxBondCatalog>(backendUrl, "/api/ix/linux-bonds", { signal: ctl.signal })
.then(result => { if (!ctl.signal.aborted) setCatalog(result) })
.catch(e => { if (!ctl.signal.aborted) setError(e.message) })
return () => ctl.abort()
}, [backendUrl, segmentId, reload, live])
const available = new Map(catalog.candidates.map(c => [memberKey(c), c]))
for (const m of [...catalog.groups.flatMap(g => g.members), ...(draft?.members ?? [])]) {
if (!m.existing) continue
const segment = segments.find(s => s.id === m.segmentId)
available.set(memberKey(m), { ...m, ...m.existing, name: m.existing.linuxInterface, segmentName: segment?.configuration.name ?? m.segmentId,
appliedRevision: segment?.appliedRevision ?? m.appliedRevision, destinations: [...new Set(m.existing.destinations)].sort() })
}
const label = (c: IxBondCandidate) => [c.name, c.segmentName, nodeLabel(nodes, c.serverId), c.kind === "wireguard" ? "WG" : "GRE/IPsec", c.endpoint, c.interfaceName].join(" · ")
function open(group?: IxSavedBond, first?: IxBondCandidate) {
setError("")
setRemove(false)
setConfirmedMembers("")
setImporting(false)
setInitialInterface(undefined)
setDirect(group?.directCidrs.join("\n") ?? "")
setDraft(group ? {
id: group.id, revision: group.revision, name: group.name, mode: group.mode, directCidrs: group.directCidrs,
members: group.members.map(m => ({ ...m, appliedRevision: available.get(memberKey(m))?.appliedRevision ?? m.appliedRevision })),
} : { revision: 0, name: first?.name ?? "", mode: "failover", members: first ? [memberRef(first)] : [], directCidrs: [] })
}
async function perform(action: () => Promise<void>) {
if (busy || readOnly) return
setBusy(true)
setError("")
try { await action() } catch (e) { setError(e instanceof Error ? e.message : "Ошибка операции с группой") }
finally { setBusy(false) }
}
const patch = (fields: Partial<IxBondEdit>) => setDraft(old => old && { ...old, ...fields })
const ownedGroups = catalog.groups.filter(g => g.members.some(m => m.segmentId === segmentId))
const previous = catalog.groups.find(g => g.id === draft?.id)
const owner = previous?.ownerSegmentId ?? segmentId
const root = "/api/ix/segments/" + owner + "/linux-bonds"
const occupied = new Set(catalog.groups.filter(g => g.id !== draft?.id).flatMap(g => g.members.map(memberKey)))
const selected = (draft?.members ?? []).flatMap(m => available.get(memberKey(m)) ?? [])
const identity = previous?.clientId ?? selected.find(m => m.clientId)?.clientId
const first = selected[0]
const choices = catalog.candidates.filter(c => c.destinations.length && !occupied.has(memberKey(c)) && (!identity || !c.clientId || c.clientId === identity) &&
(!first || c.address.includes(":") === first.address.includes(":") && JSON.stringify(c.destinations) === JSON.stringify(first.destinations) &&
!selected.some(m => [m.address, m.probe].some(ip => ip === c.address || ip === c.probe))) &&
!draft?.members.some(m => memberKey(m) === memberKey(c)))
.map(c => ({ value: memberKey(c), label: label(c) }))
const needsConfirmation = selected.length > 1 && selected.some(c => !c.clientId && !previous?.members.some(m => memberKey(m) === memberKey(c)))
const selectionKey = selected.map(memberKey).sort().join(",")
const issue = error && <p role="alert" className="text-sm text-destructive">{error}</p>
const renderGroups = (clientId: string) => ownedGroups.filter(g => g.clientId === clientId).map(g => <div key={g.id} className="grid gap-1.5">
<span className="font-medium">{g.name} · {modeLabel(g.mode)}</span>
<ol className="grid gap-1 text-sm">{g.members.map((m, i) => {
const c = available.get(memberKey(m))
const role = g.mode === "failover" ? (i ? "Резерв " + i : "Основной") : "Вес " + (g.mode === "weighted" ? m.weight : 1)
return <li key={memberKey(m)}>{role} · {c ? label(c) : m.interfaceName + " · недоступен"}
{c && c.appliedRevision !== m.appliedRevision ? " · изменена ревизия" : ""}</li>
})}</ol>
{!readOnly && <div className="flex flex-wrap gap-2">
<Button size="sm" variant="outline" disabled={busy} onClick={() => open(g)}>Изменить</Button>
<Button size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
const bundle = await requestJson<IxBondBundle>(backendUrl, "/api/ix/segments/" + g.ownerSegmentId + "/linux-bonds/" + g.id + "/export",
{ method: "POST", body: JSON.stringify({ revision: g.revision }) })
download("ix-bond-" + g.id + ".json", JSON.stringify(bundle, null, 2))
})}>Скачать для ix-client</Button>
<Button size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
try {
await copyIxImportLink(backendUrl, `/api/ix/segments/${g.ownerSegmentId}/linux-bonds/${g.id}/export`, { revision: g.revision })
toast.success("Ссылка скопирована. На VPS откройте ix-client → L.")
} catch (error) {
toast.error(error instanceof Error ? error.message : "Не удалось скопировать ссылку")
}
})}>Скопировать ссылку для ix-client</Button>
</div>}
</div>)
const rows = children(binding => {
const k = memberKey({ ...binding, segmentId })
const current = ownedGroups.find(g => g.members.some(m => memberKey(m) === k))
const candidate = available.get(k)
if (current) return { label: "Открыть группу «" + current.name + "»", open: () => open(current) }
if (candidate?.destinations.length) return { label: "Создать группу с этим туннелем", open: () => open(undefined, candidate) }
const site = segments.find(s => s.id === segmentId)?.configuration.sites.find(s => s.serverId === binding.serverId)
const saved = site?.interfaces.find(b => b.name === binding.interfaceName)
if (saved && saved.kind !== "uplink" && !saved.peerServerId && !saved.linux && !saved.provisionWireguard && !saved.provisionGre &&
!saved.provisionTransit && !site?.neighbors.some(p => p.binding === saved.name)) {
return { label: "Создать группу с этим туннелем", open: () => { open(); setInitialInterface(binding); setImporting(true) } }
}
}, catalog, renderGroups, live && !readOnly &&
<Button size="sm" variant="outline" onClick={() => open()}>Создать группу вручную</Button>)
if (!live) return <>{rows}</>
return <>{rows}{!draft && issue}
<Sheet open={!!draft} onOpenChange={value => !value && !busy && setDraft(null)}>
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-xl">
<SheetHeader><SheetTitle>Группа туннелей VPS</SheetTitle>
<SheetDescription>Выберите применённые подключения одного VPS. В режиме резервирования первый туннель в списке основной.</SheetDescription>
</SheetHeader>
{draft && <form className="flex min-h-0 flex-1 flex-col" onSubmit={e => {
e.preventDefault()
if (importing || needsConfirmation && confirmedMembers !== selectionKey) return
void perform(async () => {
await requestJson(backendUrl, root, { method: "POST", body: JSON.stringify({ ...draft,
directCidrs: direct.split(/[\s,]+/).filter(Boolean) }) })
setDraft(null); setReload(n => n + 1)
})
}}>
<div className="grid min-h-0 gap-4 overflow-y-auto px-4">
{issue}
<Field><FieldLabel htmlFor="ix-bond-name">Имя группы</FieldLabel><Input id="ix-bond-name" value={draft.name} required maxLength={80} onChange={e => patch({ name: e.target.value })} /></Field>
<Field><FieldLabel htmlFor="ix-bond-mode">Режим</FieldLabel>
<Select value={draft.mode} items={[...modes]} onValueChange={v => v && patch({ mode: v })}>
<SelectTrigger id="ix-bond-mode"><SelectValue /></SelectTrigger>
<SelectContent>{modes.map(m => <SelectItem key={m.value} value={m.value}>{m.label}</SelectItem>)}</SelectContent>
</Select></Field>
{draft.members.map((m, index) => {
const candidate = available.get(memberKey(m))
return <div key={memberKey(m)} className="grid gap-2 rounded-md border p-2 text-sm">
<span>{index + 1}. {candidate ? label(candidate) : m.interfaceName + " · недоступен"}</span>
{draft.mode === "weighted" && <Field><FieldLabel htmlFor={"ix-bond-weight-" + index}>Вес</FieldLabel>
<Input id={"ix-bond-weight-" + index} type="number" min={1} max={100} required value={m.weight}
onChange={e => patch({ members: draft.members.map((item, n) => n === index ? { ...item, weight: Number(e.target.value) } : item) })} /></Field>}
<div className="flex gap-2">
<Button size="sm" variant="outline" type="button" disabled={!index} onClick={() => {
const members = [...draft.members]; members.splice(index - 1, 0, ...members.splice(index, 1)); patch({ members })
}}>Выше</Button>
<Button size="sm" variant="outline" type="button" onClick={() => patch({ members: draft.members.filter((_, i) => i !== index) })}>Исключить</Button>
</div>
</div>
})}
<Field><FieldLabel htmlFor="ix-bond-member">Добавить туннель этого VPS</FieldLabel>
<Select<string> key={draft.members.length} value={null} items={choices} disabled={!choices.length || draft.members.length >= 16} onValueChange={v => {
const c = v && available.get(v)
if (c) patch({ members: [...draft.members, memberRef(c)] })
}}>
<SelectTrigger id="ix-bond-member"><SelectValue placeholder="Выберите интерфейс" /></SelectTrigger>
<SelectContent alignItemWithTrigger={false}>{choices.map(c => <SelectItem key={c.value} value={c.value}>{c.label}</SelectItem>)}</SelectContent>
</Select></Field>
{!choices.length && draft.members.length < 2 && <p className="text-sm text-muted-foreground">Для второго туннеля нужны другой внутренний адрес, то же семейство и одинаковые назначения. Проверьте привязку к VPS и применение подключения на его площадке.</p>}
{importing ? <IxExistingTransport backendUrl={backendUrl} segments={segments} segmentId={segmentId} nodes={nodes} initial={initialInterface}
members={[...draft.members, ...catalog.groups.filter(g => g.id !== draft.id).flatMap(g => g.members)]} destinations={first?.destinations ?? []}
cancel={() => setImporting(false)} add={m => { patch({ members: [...draft.members, m] }); setImporting(false) }} />
: <Button type="button" variant="outline" disabled={draft.members.length >= 16} onClick={() => { setInitialInterface(undefined); setImporting(true) }}>Добавить из интерфейсов RouterOS</Button>}
{needsConfirmation && <Field orientation="horizontal"><Checkbox id="ix-bond-same-vps" checked={confirmedMembers === selectionKey}
onCheckedChange={checked => setConfirmedMembers(checked ? selectionKey : "")} />
<FieldLabel htmlFor="ix-bond-same-vps">Подтверждаю, что выбранные интерфейсы настроены на одном VPS</FieldLabel></Field>}
<Field><FieldLabel htmlFor="ix-bond-direct">Прямой выход для сетей (CIDR)</FieldLabel>
<Textarea id="ix-bond-direct" rows={3} value={direct} onChange={e => setDirect(e.target.value)} /></Field>
</div>
<SheetFooter>
<Button type="submit" disabled={busy || readOnly || importing || draft.members.length < 2 || needsConfirmation && confirmedMembers !== selectionKey}>Сохранить</Button>
{draft.id && <Button type="button" variant="outline" disabled={busy || readOnly} onClick={() => {
if (!remove) { setRemove(true); return }
void perform(async () => {
await requestJson(backendUrl, root + "/" + draft.id, { method: "DELETE", body: JSON.stringify({ revision: draft.revision }) })
setDraft(null); setReload(n => n + 1)
})
}}>{remove ? "Подтвердить удаление группы" : "Удалить группу"}</Button>}
<Button type="button" variant="outline" disabled={busy} onClick={() => setDraft(null)}>Отмена</Button>
</SheetFooter>
</form>}
</SheetContent>
</Sheet>
</>
}
+68
View File
@@ -0,0 +1,68 @@
"use client"
import { useState } from "react"
import { ixExistingTransportSchema, type IxBondEdit, type IxSegment } from "@mmapp/contracts/internet-exchange"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
type Member = IxBondEdit["members"][number]
export function IxExistingTransport({ backendUrl, segmentId, segments, nodes, members, destinations, initial, add, cancel }: {
backendUrl: string; segmentId: string; segments: IxSegment[]; nodes: IxNode[]; members: Member[]; destinations: string[]
add: (ref: Member) => void; cancel: () => void
initial?: Pick<Member, "serverId" | "interfaceName">
}) {
const sites = segments.filter(s => s.appliedRevision).flatMap(segment => segment.configuration.sites.map(site => ({
value: segment.id + "/" + site.serverId, label: segment.configuration.name + " · " + nodeLabel(nodes, site.serverId), segment, site,
})))
const [selection, setSelection] = useState(sites.find(s => s.segment.id === segmentId && (!initial || s.site.serverId === initial.serverId))?.value ?? "")
const site = sites.find(s => s.value === selection)
const inventory = useIxNodeInventory(backendUrl, site?.site.serverId ?? 0, site?.segment.id)
const [iface, setIface] = useState(initial?.interfaceName ?? "")
const [linuxInterface, setLinuxInterface] = useState("")
const [probe, setProbe] = useState("")
const [address, setAddress] = useState("")
const [endpoint, setEndpoint] = useState("")
const [peer, setPeer] = useState("")
const [routes, setRoutes] = useState(destinations.join("\n"))
const interfaces = (inventory.inventory?.interfaces ?? []).filter(i => /^(wg|wireguard|gre|gre-tunnel)$/.test(i.type) && !i.disabled && i.addresses.length &&
!site?.site.interfaces.some(b => b.name === i.name && (b.linux || b.provisionWireguard || b.provisionGre || b.provisionTransit || b.peerServerId)) &&
!site?.site.neighbors.some(p => p.binding === i.name) && !members.some(m => m.serverId === site?.site.serverId && m.interfaceName === i.name))
const active = interfaces.find(i => i.name === iface)
const wg = active?.type === "wg" || active?.type === "wireguard"
const probes = active?.addresses.map(a => a.split("/")[0]) ?? []
const selectedProbe = probes.includes(probe) ? probe : probes[0] ?? ""
const input = ixExistingTransportSchema.safeParse({ ...(wg ? { kind: "wireguard", clientPublicKey: peer.trim() } : { kind: "gre-ipsec", remoteEndpoint: peer.trim() }),
linuxInterface: linuxInterface.trim(), probe: selectedProbe, address: address.trim(), endpoint: endpoint.trim(), destinations: routes.trim().split(/[\s,]+/) })
return <div className="grid gap-3 rounded-md border p-3">
<Field><FieldLabel htmlFor="ix-adopt-site">Площадка и узел IX</FieldLabel>
<Select value={selection} items={sites} onValueChange={v => { setSelection(v ?? ""); setIface(""); setProbe(""); setPeer(""); setEndpoint("") }}>
<SelectTrigger id="ix-adopt-site"><SelectValue /></SelectTrigger><SelectContent>{sites.map(s => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}</SelectContent>
</Select></Field>
<Field><FieldLabel htmlFor="ix-adopt-interface">Интерфейс RouterOS</FieldLabel>
<Select value={iface || null} items={interfaces.map(i => ({ value: i.name, label: i.name }))} onValueChange={v => {
setIface(v ?? ""); setProbe(interfaces.find(i => i.name === v)?.addresses[0]?.split("/")[0] ?? ""); setPeer("")
}}><SelectTrigger id="ix-adopt-interface"><SelectValue placeholder="Выберите WG или GRE" /></SelectTrigger>
<SelectContent>{interfaces.map(i => <SelectItem value={i.name} key={i.name}>{i.name}</SelectItem>)}</SelectContent></Select>
<FieldDescription>{inventory.error ?? (inventory.loading ? "Читаем интерфейсы узла…" : "Доступны включённые интерфейсы с внутренним IP. Настройки RouterOS сохраняются.")}</FieldDescription></Field>
{active && <>
<Field><FieldLabel htmlFor="ix-adopt-linux">Имя интерфейса на VPS</FieldLabel><Input id="ix-adopt-linux" value={linuxInterface} onChange={e => setLinuxInterface(e.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-adopt-probe">Адрес IX внутри туннеля</FieldLabel>
<Select value={selectedProbe} items={probes.map(value => ({ value, label: value }))} onValueChange={v => setProbe(v ?? "")}>
<SelectTrigger id="ix-adopt-probe"><SelectValue /></SelectTrigger><SelectContent>{probes.map(v => <SelectItem key={v} value={v}>{v}</SelectItem>)}</SelectContent>
</Select></Field>
<Field><FieldLabel htmlFor="ix-adopt-address">Адрес VPS внутри туннеля</FieldLabel><Input id="ix-adopt-address" value={address} onChange={e => setAddress(e.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-adopt-endpoint">Внешний адрес IX</FieldLabel><Input id="ix-adopt-endpoint" value={endpoint} onChange={e => setEndpoint(e.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-adopt-peer">{wg ? "Публичный ключ WireGuard VPS" : "Внешний IPv4 VPS"}</FieldLabel><Input id="ix-adopt-peer" value={peer} onChange={e => setPeer(e.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-adopt-routes">Назначения через туннель (CIDR)</FieldLabel><Textarea id="ix-adopt-routes" rows={2} value={routes} onChange={e => setRoutes(e.target.value)} /></Field>
</>}
<div className="flex gap-2"><Button type="button" variant="outline" size="sm" disabled={!site || !active || !input.success} onClick={() => {
if (input.success && site?.segment.appliedRevision && active) add({ segmentId: site.segment.id, serverId: site.site.serverId,
appliedRevision: site.segment.appliedRevision, interfaceName: active.name, existing: input.data, weight: 1 })
}}>Включить в список</Button><Button type="button" size="sm" variant="ghost" onClick={cancel}>Отмена выбора</Button></div>
</div>
}
+117
View File
@@ -0,0 +1,117 @@
"use client"
import { useState } from "react"
import type { IxNodeInventory, IxSegment, IxTransitRequest } from "@mmapp/contracts/internet-exchange"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
export function publicEndpoint(inventory?: IxNodeInventory) {
if (!inventory) return ""
const wan = new Set(inventory.defaultRoutes.filter(route => route.family === 4).map(route => route.interface))
const addresses = new Set(inventory.interfaces.filter(iface => !iface.disabled && wan.has(iface.name))
.flatMap(iface => iface.addresses.filter(address => !address.includes(":")).map(address => address.split("/")[0])))
return addresses.size === 1 ? [...addresses][0] : ""
}
export function transitName(segment: IxSegment, serverId: number, target: number, family: 4 | 6) {
const used = segment.configuration.sites.find(site => site.serverId === serverId)?.groups ?? []
const base = "via-" + target.toString(36) + "-v" + family
let name = base
for (let i = 2; used.some(group => group.id === name); i++) name = base + "-" + i
return name
}
function TransitEditor({ segment, nodes, backendUrl, busy, save, cancel }: {
segment: IxSegment; nodes: IxNode[]; backendUrl: string; busy: boolean
save: (input: IxTransitRequest) => void; cancel: () => void
}) {
const [serverId, setServerId] = useState(segment.configuration.sites[0].serverId)
const [targetServerId, setTargetServerId] = useState(0)
const [local, setLocal] = useState("")
const [remote, setRemote] = useState("")
const [name, setName] = useState("")
const [probe, setProbe] = useState("")
const [family, setFamily] = useState<4 | 6>(4)
const origin = useIxNodeInventory(backendUrl, serverId, segment.id)
const target = useIxNodeInventory(backendUrl, targetServerId, segment.id)
const localEndpoint = local || publicEndpoint(origin.inventory)
const remoteEndpoint = remote || publicEndpoint(target.inventory)
const exitName = name || transitName(segment, serverId, targetServerId, family)
const sourceChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
const targets = nodes.filter(node => node.enabled && node.id !== serverId && ["ix-node", "exit-node"].includes(node.type ?? ""))
.map(node => ({ value: String(node.id), label: node.name + (node.type === "ix-node" ? " · IX" : " · ExitNode") }))
return <form className="flex min-h-0 flex-1 flex-col" onSubmit={event => {
event.preventDefault()
if (!busy && targetServerId && localEndpoint && remoteEndpoint && exitName) {
save({ revision: segment.revision, name: exitName, serverId, targetServerId, localEndpoint, remoteEndpoint, family, probe: probe || undefined })
}
}}>
<div className="grid min-h-0 gap-4 overflow-y-auto px-4">
{sourceChoices.length > 1 && <Field><FieldLabel htmlFor="ix-egress-source">Узел входа</FieldLabel>
<Select items={sourceChoices} value={String(serverId)} onValueChange={value => {
if (value) { setServerId(Number(value)); setTargetServerId(0); setLocal(""); setRemote("") }
}}>
<SelectTrigger className="w-full" id="ix-egress-source"><SelectValue /></SelectTrigger>
<SelectContent>{sourceChoices.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
</Select></Field>}
<Field><FieldLabel htmlFor="ix-egress-target">Выходной узел</FieldLabel>
<Select items={targets} value={targetServerId ? String(targetServerId) : null}
onValueChange={value => { setTargetServerId(Number(value)); setRemote("") }}>
<SelectTrigger className="w-full" id="ix-egress-target"><SelectValue placeholder="Другой IX или ExitNode" /></SelectTrigger>
<SelectContent>{targets.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
</Select></Field>
<details key={serverId + ":" + targetServerId + ":" + (origin.loading || target.loading)} open={!!targetServerId && (!publicEndpoint(origin.inventory) || !publicEndpoint(target.inventory)) && !origin.loading && !target.loading}>
<summary className="cursor-pointer text-sm font-medium">Параметры туннеля</summary>
<div className="mt-3 grid gap-3">
<Field><FieldLabel htmlFor="ix-egress-name">Имя выхода</FieldLabel>
<Input id="ix-egress-name" value={exitName} pattern="[a-z][a-z0-9-]{0,23}" onChange={event => setName(event.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-egress-local">Внешний IPv4 узла входа</FieldLabel>
<Input id="ix-egress-local" value={localEndpoint} required onChange={event => setLocal(event.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-egress-remote">Внешний IPv4 выходного узла</FieldLabel>
<Input id="ix-egress-remote" value={remoteEndpoint} required onChange={event => setRemote(event.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-egress-probe">Контрольный адрес</FieldLabel>
<Input id="ix-egress-probe" value={probe} placeholder="Адрес второго конца туннеля" onChange={event => setProbe(event.target.value)} />
<FieldDescription>Для проверки выхода за пределами туннеля укажите доступную цель за удалённым узлом.</FieldDescription>
</Field>
<Field><FieldLabel htmlFor="ix-egress-family">Семейство трафика</FieldLabel>
<Select value={String(family)} items={[{ value: "4", label: "IPv4" }, { value: "6", label: "IPv6" }]}
onValueChange={value => { setFamily(value === "6" ? 6 : 4); setProbe("") }}>
<SelectTrigger className="w-full" id="ix-egress-family"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="4">IPv4</SelectItem><SelectItem value="6">IPv6</SelectItem></SelectContent>
</Select>
{family === 6 && <FieldDescription>Для выхода в Интернет IPv6 нужен маршрутизируемый префикс Linux с обратным маршрутом до выходной CHR.</FieldDescription>}
</Field>
</div>
</details>
{(origin.error || target.error) && <p role="status" className="text-sm text-muted-foreground">{origin.error ?? target.error}</p>}
</div>
<SheetFooter>
<Button type="submit" disabled={busy || !targetServerId || !localEndpoint || !remoteEndpoint}>Сохранить</Button>
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button>
</SheetFooter>
</form>
}
export function IxExits({ segment, nodes, backendUrl, busy, error, save }: {
segment: IxSegment; nodes: IxNode[]; backendUrl: string; busy: boolean; error: string
save: (input: IxTransitRequest) => Promise<boolean>
}) {
const [open, setOpen] = useState(false)
return <>
<Button size="sm" className="w-fit" disabled={busy} onClick={() => setOpen(true)}>Добавить удалённый выход</Button>
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
<SheetHeader><SheetTitle>Удалённый выход</SheetTitle>
<SheetDescription>WireGuard, обратные маршруты и IPv4 SNAT будут подготовлены на обоих узлах.</SheetDescription>
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
</SheetHeader>
{open && <TransitEditor segment={segment} nodes={nodes} backendUrl={backendUrl} busy={busy}
save={input => void save(input).then(success => { if (success) setOpen(false) })} cancel={() => setOpen(false)} />}
</SheetContent>
</Sheet>
</>
}
+12
View File
@@ -0,0 +1,12 @@
import { requestJson } from "@/shared/api/http-client"
export async function copyIxImportLink(backendUrl: string, path: string, params: object) {
const link = new URL(backendUrl.replace(/\/$/, "") + "/api/ix/import", window.location.origin)
if (link.protocol !== "https:" || !navigator.clipboard) throw new Error("Для одноразовой ссылки откройте Manager по HTTPS")
const { code } = await requestJson<{ code: string }>(backendUrl, path, {
method: "POST", body: JSON.stringify({ ...params, importLink: true }),
})
if (!/^[A-Za-z0-9_-]{32}$/.test(code)) throw new Error("Manager вернул неверный код импорта")
link.hash = code
await navigator.clipboard.writeText(link.toString())
}
+376
View File
@@ -0,0 +1,376 @@
"use client"
import { useMemo, useState, type ReactNode } from "react"
import { type ColumnDef, useTable } from "@tanstack/react-table"
import { EllipsisIcon, PencilIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
import type { IxBondCatalog, IxLinuxBinding, IxLinuxClientRequest, IxSegment, IxSite } from "@mmapp/contracts/internet-exchange"
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
import { Badge } from "@/components/reui/badge"
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
import { Button } from "@/components/ui/button"
import { ButtonGroup } from "@/components/ui/button-group"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Field, FieldDescription, FieldLabel, FieldTitle } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { Textarea } from "@/components/ui/textarea"
import { isIpv4String } from "@/lib/gre-endpoint-resolve"
import { formatBytes } from "@/lib/fmt-rate"
import { publicEndpoint, transitName } from "./ix-exits"
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
import type { IxRowBondAction } from "./ix-client-bonds"
type Binding = IxSite["interfaces"][number]
type ClientSelection = { site: IxSite; binding: Binding; addProtocol?: boolean; chooseTransport?: boolean }
type FormState = {
serverId: number
name: string
kind: IxLinuxClientRequest["kind"] | "both"
hub: string
peer: string
key: string
localAddress: string
peerAddress: string
prefixes: string
destinations: string
exit: string
enabled: boolean
transitLocal: string
transitRemote: string
}
const lines = (value: string) => value.split(/[,\n]/).map(line => line.trim()).filter(Boolean)
const protocols = [
{ kind: "wireguard", label: "WireGuard" },
{ kind: "gre-ipsec", label: "GRE/IPsec" },
] as const
function hasCompanion(site: IxSite, binding: Binding) {
const clientId = binding.linux?.clientId
return !!clientId && site.interfaces.some(item => item.kind !== binding.kind && item.linux?.clientId === clientId)
}
function groupLabel(group: IxSite["groups"][number], site: IxSite, nodes: IxNode[]) {
const target = site.interfaces.find(binding => binding.name === group.primary.interface)?.peerServerId
const label = target ? "Через " + nodeLabel(nodes, target) : group.primary.viaMain ? "Интернет с этого IX" : group.id
return [label, group.backup && "с резервом"].filter(Boolean).join(" · ")
}
function ClientForm({ segment, edit, setAddProtocol, nodes, backendUrl, catalog, busy, save, cancel }: {
segment: IxSegment; edit: ClientSelection | null; nodes: IxNode[]; backendUrl: string
catalog: IxBondCatalog
setAddProtocol: (add: boolean) => void
busy: boolean; save: (input: IxLinuxClientRequest) => Promise<void>; cancel: () => void
}) {
const existing = edit?.binding
const companion = edit?.addProtocol ? existing : undefined
const binding = companion ? undefined : existing
const paired = !!edit && hasCompanion(edit.site, edit.binding)
const initialForm = (addProtocol: boolean): FormState => {
const current = addProtocol ? undefined : existing
const tunnel = current?.provisionWireguard ?? current?.provisionGre
return {
serverId: edit?.site.serverId ?? segment.configuration.sites[0].serverId,
name: existing?.linux?.name ?? "",
kind: addProtocol ? (existing?.kind === "wireguard" ? "gre-ipsec" : "wireguard")
: current?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard",
hub: existing?.localEndpoint ?? existing?.provisionWireguard?.hubEndpoint ?? "",
peer: existing?.linux?.peerEndpoint ?? existing?.endpoint ?? "",
key: current?.provisionWireguard?.credentialId ? "" : current?.provisionWireguard?.peerPublicKey ?? "",
localAddress: tunnel?.localAddress ?? "", peerAddress: tunnel?.peerAddress ?? "",
prefixes: current?.prefixes.join("\n") ?? "", destinations: current?.linux?.destinations.join("\n") ?? "",
exit: current?.linux?.exit ?? "isolated", enabled: current?.linux?.enabled ?? true,
transitLocal: "", transitRemote: "",
}
}
const [currentForm, setCurrentForm] = useState(() => initialForm(false))
const [companionForm, setCompanionForm] = useState(() => initialForm(true))
const form = companion ? companionForm : currentForm
const setForm = companion ? setCompanionForm : setCurrentForm
const wireguard = form.kind !== "gre-ipsec"
const gre = form.kind !== "wireguard"
const [rotate, setRotate] = useState(false)
const [vpsId, setVpsId] = useState("")
const currentGroup = edit && catalog.groups.find(g => g.members.some(m => m.segmentId === segment.id &&
m.serverId === edit.site.serverId && m.interfaceName === edit.binding.name))
const currentVps = currentGroup?.clientId ?? existing?.linux?.clientId
const knownVps = useMemo(() => {
const labels = new Map<string, string>()
for (const c of catalog.candidates) if (c.clientId) labels.set(c.clientId, c.name + " · " + c.segmentName)
for (const group of catalog.groups) labels.set(group.clientId, group.name)
if (currentVps && !labels.has(currentVps)) labels.set(currentVps, existing?.linux?.name ?? "Текущий VPS")
return [...labels].map(([value, label]) => ({ value, label: label + " · " + value.slice(0, 8) }))
}, [catalog, currentVps, existing])
const origin = useIxNodeInventory(backendUrl, form.serverId, segment.id)
const site = segment.configuration.sites.find(site => site.serverId === form.serverId)
const suggested = publicEndpoint(origin.inventory)
const hub = form.hub.trim() || suggested
const targetId = form.exit.startsWith("remote:") ? Number(form.exit.slice(7)) : 0
const target = useIxNodeInventory(backendUrl, targetId, segment.id)
const localEndpoint = form.transitLocal.trim() || suggested || (form.hub.includes(":") ? "" : form.hub.trim())
const remoteEndpoint = form.transitRemote.trim() || publicEndpoint(target.inventory)
const family = form.kind !== "both" && form.peerAddress.includes(":") ? 6 : 4
const patch = (fields: Partial<FormState>) => setForm(value => ({ ...value, ...fields }))
const nodeChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
const groups = site?.groups.filter(group => group.onFailure === "block" && group.gateway.includes(":") === (family === 6)) ?? []
const local = groups.find(group => group.id === "ix-wan" + family && group.primary.viaMain)
const targets = nodes.filter(node => node.enabled && node.id !== form.serverId && ["ix-node", "exit-node"].includes(node.type ?? ""))
const exits = [
{ value: "isolated", label: "Только разрешённые сети" },
{ value: local?.id ?? "local-wan", label: local ? groupLabel(local, site!, nodes) : "Интернет с этого IX" },
...groups.filter(group => group !== local).map(group => ({ value: group.id, label: groupLabel(group, site!, nodes) + " · " + group.id })),
...targets.filter(node => !groups.some(group => site?.interfaces.some(link => link.name === group.primary.interface && link.peerServerId === node.id)))
.map(node => ({ value: "remote:" + node.id, label: "Через " + node.name + (node.type === "exit-node" ? " · ExitNode" : " · IX") })),
]
const valid = !!form.name.trim() && !!hub && (!gre || isIpv4String(form.peer.trim()) && isIpv4String(hub)) &&
(!targetId || !!localEndpoint && !!remoteEndpoint) && exits.some(exit => exit.value === form.exit)
const destinationsField = <Field><FieldLabel htmlFor="ix-linux-destinations">Разрешённые сети IX</FieldLabel>
<Textarea id="ix-linux-destinations" rows={2} value={form.destinations} placeholder="По одному CIDR на строку" onChange={event => patch({ destinations: event.target.value })} />
<FieldDescription>Перечислите префиксы для доступа через IX, например 10.2.0.0/24.</FieldDescription></Field>
return <form className="flex min-h-0 flex-1 flex-col" onSubmit={event => {
event.preventDefault()
if (!valid || busy) return
void save({
revision: segment.revision, serverId: form.serverId, interfaceName: binding?.name, name: form.name,
vpsClientId: !companion && vpsId && vpsId !== currentVps ? vpsId : undefined,
kind: wireguard ? "wireguard" : "gre-ipsec", additionalGre: form.kind === "both" || undefined, companionOf: companion?.name,
hubEndpoint: hub, peerEndpoint: form.peer.trim() || undefined,
peerPublicKey: wireguard ? form.key.trim() || undefined : undefined,
localAddress: form.kind === "both" ? undefined : form.localAddress.trim() || undefined,
peerAddress: form.kind === "both" ? undefined : form.peerAddress.trim() || undefined,
prefixes: lines(form.prefixes), destinations: lines(form.destinations), exit: form.exit === "isolated" || targetId ? undefined : form.exit,
transit: targetId ? { targetServerId: targetId, name: transitName(segment, form.serverId, targetId, family), family,
localEndpoint, remoteEndpoint } : undefined,
enabled: form.enabled, rotate: !!binding && rotate,
})
}}>
<div className="grid min-h-0 gap-4 overflow-y-auto px-4 pb-4">
<Field><FieldLabel htmlFor="ix-linux-name">Имя клиента</FieldLabel>
<Input id="ix-linux-name" value={form.name} placeholder="vps-01" readOnly={!!companion} required onChange={event => patch({ name: event.target.value })} /></Field>
{!companion && !!knownVps.length && <Field><FieldLabel htmlFor="ix-linux-vps">Привязка к VPS</FieldLabel>
<Select value={vpsId || currentVps || "separate"} disabled={!!currentGroup} items={[{ value: "separate", label: "Отдельное подключение" }, ...knownVps]}
onValueChange={v => setVpsId(v && v !== "separate" ? v : "")}>
<SelectTrigger id="ix-linux-vps"><SelectValue /></SelectTrigger>
<SelectContent>{!currentVps && <SelectItem value="separate">Отдельное подключение</SelectItem>}
{knownVps.map(v => <SelectItem key={v.value} value={v.value}>{v.label}</SelectItem>)}</SelectContent>
</Select>{currentGroup && <FieldDescription>Привязка задана группой «{currentGroup.name}».</FieldDescription>}</Field>}
{nodeChoices.length > 1 && <Field><FieldLabel htmlFor="ix-linux-node">Узел IX</FieldLabel>
<Select value={String(form.serverId)} items={nodeChoices} disabled={!!edit}
onValueChange={value => value && patch({ serverId: Number(value), hub: "", exit: "isolated" })}>
<SelectTrigger id="ix-linux-node" className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>{nodeChoices.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
</Select></Field>}
<Field>
<FieldTitle id="ix-linux-transport">Протоколы подключения</FieldTitle>
<ButtonGroup aria-labelledby="ix-linux-transport" className="max-w-full">
{protocols.map(({ kind, label }) => {
const choosing = !!companion && edit?.chooseTransport
const selected = choosing ? form.kind === kind : paired || !!companion || form.kind === "both" || form.kind === kind
return <Button key={kind} type="button" size="sm" variant={selected ? "secondary" : "outline"} aria-pressed={selected}
disabled={busy || (choosing ? form.kind === kind : existing ? paired || existing.kind === kind : form.kind === kind)}
onClick={() => choosing ? patch({ kind }) : existing ? setAddProtocol(!companion)
: patch({ kind: form.kind === "both" ? (kind === "wireguard" ? "gre-ipsec" : "wireguard") : "both" })}>{label}</Button>
})}
</ButtonGroup>
{form.kind === "both" ? <FieldDescription>Оба туннеля получат свои адреса в одной VRF сегмента.</FieldDescription>
: companion ? <FieldDescription>Настройки ниже относятся к новому туннелю в той же VRF.</FieldDescription>
: paired ? <FieldDescription>Оба протокола настроены. Здесь редактируется {binding?.kind === "gre-ipsec" ? "GRE/IPsec" : "WireGuard"}.</FieldDescription>
: edit ? <FieldDescription>Выберите второй протокол, чтобы добавить туннель в ту же VRF.</FieldDescription>
: <FieldDescription>Можно отметить оба протокола.</FieldDescription>}
</Field>
<Field><FieldLabel htmlFor="ix-linux-peer">Внешний адрес Linux</FieldLabel>
<Input id="ix-linux-peer" value={form.peer} placeholder="123.123.123.123" required={gre} onChange={event => patch({ peer: event.target.value })} />
<FieldDescription>{gre ? "Фиксированный IPv4 на VPS для GRE/IPsec. Ответы на SSH по этому адресу пойдут напрямую." : form.exit === "isolated"
? "Для WireGuard это поле необязательно." : "Укажите публичный IP VPS, чтобы сохранить доступ по SSH при выходе через IX."}</FieldDescription></Field>
<Field><FieldLabel htmlFor="ix-linux-exit">Выход трафика</FieldLabel>
<Select value={form.exit} items={exits} onValueChange={value => { if (value) patch({ exit: value, transitLocal: "", transitRemote: "" }) }}>
<SelectTrigger id="ix-linux-exit" className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>{exits.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
</Select>
{!!targetId && <FieldDescription>IX создаст туннель до {nodeLabel(nodes, targetId)} для выхода в Интернет.</FieldDescription>}
</Field>
{!!targetId && !publicEndpoint(target.inventory) && (target.loading ? <p role="status" className="text-sm text-muted-foreground">Читаем WAN выходного узла…</p> :
<Field><FieldLabel htmlFor="ix-transit-target">IPv4 выходного узла</FieldLabel>
<Input id="ix-transit-target" value={form.transitRemote} onChange={event => patch({ transitRemote: event.target.value })} />
<FieldDescription>Укажите адрес интерфейса CHR для межузлового туннеля.</FieldDescription></Field>)}
{!!targetId && !suggested && !origin.loading && <Field><FieldLabel htmlFor="ix-transit-source">IPv4 узла IX для транзита</FieldLabel>
<Input id="ix-transit-source" value={localEndpoint} onChange={event => patch({ transitLocal: event.target.value })} /></Field>}
{form.exit === "isolated" && destinationsField}
<details className="grid gap-3" key={form.serverId + ":" + origin.loading + ":" + gre}
open={!origin.loading && (!hub || gre && !isIpv4String(hub)) || undefined}>
<summary className="cursor-pointer text-sm font-medium">Параметры туннеля</summary>
<div className="mt-3 grid gap-3">
<Field><FieldLabel htmlFor="ix-linux-hub">Внешний адрес IX</FieldLabel>
<Input id="ix-linux-hub" value={form.hub || suggested} onChange={event => patch({ hub: event.target.value })} />
<FieldDescription>{origin.loading ? "Читаем адрес WAN с CHR…" : suggested ? "Адрес WAN для подключения VPS." : "Введите адрес IX, доступный с VPS."}</FieldDescription>
</Field>
{wireguard && <Field><FieldLabel htmlFor="ix-linux-key">Публичный ключ Linux</FieldLabel>
<Input id="ix-linux-key" value={form.key} placeholder="Создать автоматически" onChange={event => patch({ key: event.target.value })} />
<FieldDescription>Укажите ключ только для своей пары WireGuard.</FieldDescription></Field>}
{form.exit !== "isolated" && destinationsField}
{form.kind !== "both" && <><Field><FieldLabel htmlFor="ix-linux-tunnel-local">Адрес IX в туннеле (CIDR)</FieldLabel>
<Input id="ix-linux-tunnel-local" value={form.localAddress} placeholder="Автоматический IPv4" onChange={event => patch({ localAddress: event.target.value })} /></Field>
<Field><FieldLabel htmlFor="ix-linux-tunnel-peer">Адрес Linux в туннеле</FieldLabel>
<Input id="ix-linux-tunnel-peer" value={form.peerAddress} placeholder="Автоматический IPv4" onChange={event => patch({ peerAddress: event.target.value })} /></Field></>}
<Field><FieldLabel htmlFor="ix-linux-prefixes">Сети за Linux</FieldLabel>
<Textarea id="ix-linux-prefixes" rows={2} value={form.prefixes} onChange={event => patch({ prefixes: event.target.value })} /></Field>
</div>
</details>
{binding && <div className="flex flex-wrap gap-2">
<Button type="button" size="sm" variant={form.enabled ? "outline" : "secondary"} aria-pressed={!form.enabled}
onClick={() => patch({ enabled: !form.enabled })}>{form.enabled ? "Приостановить доступ" : "Возобновить доступ"}</Button>
{form.kind === "gre-ipsec" && <Button type="button" size="sm" variant={rotate ? "secondary" : "outline"}
aria-pressed={rotate} onClick={() => setRotate(!rotate)}>Выпустить новый PSK</Button>}
</div>}
</div>
<SheetFooter>{(gre || !form.key) && <p className="text-sm text-muted-foreground">После подтверждения файлы подключения будут доступны в таблице.</p>}
<Button type="submit" disabled={!valid || busy}>{companion ? "Добавить туннель" : "Сохранить"}</Button>
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button></SheetFooter>
</form>
}
function TunnelTable({ data, columns, busy }: {
data: IxLinuxBinding[]; columns: ColumnDef<DataGridFeatures, IxLinuxBinding>[]; busy: boolean
}) {
const table = useTable({ features: dataGridFeatures, manualPagination: true, data, columns,
getRowId: row => row.serverId + ":" + row.interfaceName })
return <DataGridShell table={table} recordCount={data.length} isLoading={busy && !data.length} loadingMode="skeleton" emptyMessage="В сегменте пока нет Linux-клиентов" />
}
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, copyImport, inspect, bondAction, catalog, renderGroups, manualGroup }: {
segment: IxSegment; nodes: IxNode[]; backendUrl: string; applied: IxLinuxBinding[]; readOnly: boolean; busy: boolean; error?: string
save: (input: IxLinuxClientRequest) => Promise<boolean>; refresh: () => void
view: (binding: IxLinuxBinding, transportOnly?: boolean) => void; revoke: (binding: IxLinuxBinding) => void
copyImport: (binding: IxLinuxBinding) => void; inspect: (binding: IxLinuxBinding) => void
bondAction: IxRowBondAction; catalog: IxBondCatalog
renderGroups: (clientId: string) => ReactNode; manualGroup: ReactNode
}) {
const [open, setOpen] = useState(false)
const [edit, setEdit] = useState<ClientSelection | null>(null)
const rows = useMemo(() => {
const saved = segment.configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.linux ? [{
serverId: site.serverId, interfaceName: binding.name, kind: binding.kind as IxLinuxBinding["kind"],
policy: binding.linux, name: binding.linux.name, enabled: binding.linux.enabled,
connection: applied.find(item => item.serverId === site.serverId && item.interfaceName === binding.name)?.connection,
}] : []))
return [...saved, ...applied.filter(binding => !saved.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName))]
}, [segment, applied])
const clients = new Map<string, { name: string; tunnels: IxLinuxBinding[]; hasGroups: boolean }>()
const relevantGroups = catalog.groups.filter(group => group.members.some(member => member.segmentId === segment.id))
const tunnelKey = (binding: Pick<IxLinuxBinding, "serverId" | "interfaceName">) => binding.serverId + ":" + binding.interfaceName
const affiliations = new Map(relevantGroups.flatMap(group => group.members.filter(member => member.segmentId === segment.id)
.map(member => [tunnelKey(member), group.clientId] as const)))
for (const row of rows) {
const key = affiliations.get(tunnelKey(row)) ?? row.policy?.clientId ?? tunnelKey(row)
const client = clients.get(key) ?? { name: row.name ?? row.interfaceName, tunnels: [], hasGroups: false }
if (row.name && !client.tunnels.some(tunnel => tunnel.name)) client.name = row.name
client.tunnels.push(row)
clients.set(key, client)
}
for (const group of relevantGroups) {
const client = clients.get(group.clientId) ?? { name: group.name, tunnels: [], hasGroups: false }
client.hasGroups = true
clients.set(group.clientId, client)
}
const columns = useMemo<ColumnDef<DataGridFeatures, IxLinuxBinding>[]>(() => [
{ id: "name", header: "Интерфейс", size: 195, cell: ({ row }) => <div className="grid gap-0.5">
<span className="break-all font-medium">{row.original.interfaceName}</span>
<span className="text-xs text-muted-foreground">{nodeLabel(nodes, row.original.serverId)}</span>
</div> },
{ id: "transport", header: "Туннель", size: 105, cell: ({ row }) => row.original.kind === "wireguard" ? "WireGuard" : "GRE/IPsec" },
{ id: "egress", header: "Выход трафика", size: 205, cell: ({ row }) => {
const client = row.original
const site = segment.configuration.sites.find(item => item.serverId === client.serverId)
const binding = site?.interfaces.find(item => item.name === client.interfaceName)
const group = site?.groups.find(item => item.id === client.policy?.exit)
const label = site && group ? groupLabel(group, site, nodes) : client.policy ? client.policy.exit ?? "Только сети IX" : "По настройкам интерфейса"
return readOnly || !site || !binding?.linux ? label : <Button type="button" size="sm" variant="link" className="max-w-full"
disabled={busy} aria-label={"Доступ и выход клиента " + client.name} onClick={() => { setEdit({ site, binding }); setOpen(true) }}>
<span className="truncate">{label}</span><PencilIcon aria-hidden />
</Button>
} },
{ id: "state", header: "Состояние", size: 160, cell: ({ row }) => {
const binding = row.original
if (!binding.policy) return <div className="grid gap-1"><Badge className="w-fit" variant="secondary">Прежняя настройка</Badge>
{!catalog.candidates.some(c => c.segmentId === segment.id && c.serverId === binding.serverId && c.interfaceName === binding.interfaceName) &&
<span className="text-xs text-muted-foreground">Параметры ручного туннеля проверяются при добавлении из RouterOS.</span>}</div>
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName)
const site = segment.configuration.sites.find(item => item.serverId === binding.serverId)
if (!site?.interfaces.some(item => item.name === binding.interfaceName)) return <Badge variant="warning-light">Ожидает отзыва</Badge>
if (!live || JSON.stringify(binding.policy) !== JSON.stringify(live.policy)) return <Badge variant="warning-light">Ожидает сохранения</Badge>
if (!binding.enabled) return <Badge variant="secondary">Приостановлен</Badge>
const { state, rx, tx } = binding.connection ?? {}
return <div className="grid gap-1">
<Badge className="w-fit" variant={state === "connected" ? "success-light" : "secondary"}>
{state === "connected" ? "Подключён" : state === "waiting" ? "Ожидает туннель" : "Нет данных"}
</Badge>
{(rx !== undefined || tx !== undefined) && <span className="text-xs text-muted-foreground" title="Счётчики на узле IX">
RX {rx !== undefined ? formatBytes(Number(rx)) : "—"} · TX {tx !== undefined ? formatBytes(Number(tx)) : "—"}
</span>}
</div>
} },
{ id: "actions", header: "Действия", size: 140, cell: ({ row }) => {
const binding = row.original
const site = segment.configuration.sites.find(site => site.serverId === binding.serverId)
const saved = site?.interfaces.find(candidate => candidate.name === binding.interfaceName)
const paired = !!site && !!saved && hasCompanion(site, saved)
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName && item.enabled !== false)
const bond = !readOnly && bondAction(binding)
return <div className="flex flex-wrap gap-1">
{live && <Button size="sm" variant="outline" disabled={busy} aria-label={"Получить конфиг " + (binding.name ?? binding.interfaceName) +
(paired ? binding.kind === "wireguard" ? " · WireGuard" : " · GRE/IPsec" : "")}
onClick={() => view(live)}>Конфиг Linux</Button>}
{(bond || binding.policy && (live || !readOnly && saved?.linux)) && <DropdownMenu>
<DropdownMenuTrigger render={<Button type="button" size="icon-sm" variant="ghost" disabled={busy} aria-label={"Действия клиента " +
(binding.name ?? binding.interfaceName) + (paired ? " · " + binding.interfaceName : "")} />}>
<EllipsisIcon aria-hidden />
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{bond && <DropdownMenuItem onClick={bond.open}>{bond.label}</DropdownMenuItem>}
{live && (binding.policy || catalog.candidates.some(c => c.segmentId === segment.id && c.serverId === live.serverId && c.interfaceName === live.interfaceName)) &&
<DropdownMenuItem onClick={() => view(live, true)}>Конфиг для группы ix-client</DropdownMenuItem>}
{!readOnly && live?.policy && (live.managedWireguard || live.kind === "gre-ipsec") &&
<DropdownMenuItem onClick={() => copyImport(live)}>Скопировать ссылку для ix-client</DropdownMenuItem>}
{live?.policy && <DropdownMenuItem onClick={() => inspect(live)}>Проверить путь</DropdownMenuItem>}
{!readOnly && site && saved?.linux && <DropdownMenuItem
onClick={() => { setEdit({ site, binding: saved, addProtocol: true, chooseTransport: true }); setOpen(true) }}>Добавить туннель</DropdownMenuItem>}
{!readOnly && saved?.linux && <DropdownMenuItem variant="destructive" onClick={() => revoke(binding)}>Отозвать доступ…</DropdownMenuItem>}
</DropdownMenuContent>
</DropdownMenu>}
</div>
} },
], [nodes, applied, segment, readOnly, busy, view, copyImport, revoke, inspect, bondAction, catalog.candidates])
return <Frame spacing="sm" className="min-w-0">
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
<FrameTitle>Linux-клиенты</FrameTitle>
<div className="flex flex-wrap items-center gap-2">
<Button type="button" size="icon-sm" variant="outline" aria-label="Обновить клиентов" disabled={busy || !segment.appliedRevision} onClick={refresh}><RefreshCwIcon /></Button>
{!readOnly && <Button type="button" size="sm" disabled={busy} onClick={() => { setEdit(null); setOpen(true) }}><PlusIcon />Подключить Linux</Button>}
{manualGroup}
</div>
</FrameHeader>
{clients.size ? [...clients].map(([key, client]) => <FramePanel key={key} className="grid min-w-0 gap-3 p-0">
<section aria-label={"Клиент " + client.name} className="grid min-w-0 gap-3">
<h3 className="px-4 pt-3 text-sm font-semibold">{client.name}</h3>
{!!client.tunnels.length && <TunnelTable data={client.tunnels} columns={columns} busy={busy} />}
{client.hasGroups && <div className="grid gap-3 px-4 pb-4">
<h4 className="text-sm font-medium">Группы туннелей</h4>
{renderGroups(key)}
</div>}
</section>
</FramePanel>) : <FramePanel className="min-w-0 p-0"><TunnelTable data={rows} columns={columns} busy={busy} /></FramePanel>}
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
<SheetHeader><SheetTitle>{edit?.chooseTransport ? "Добавить туннель" : edit?.addProtocol ? "Добавить другой протокол" : edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
<SheetDescription>Укажите VPS и выберите, куда направлять его трафик.</SheetDescription>
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
</SheetHeader>
{open && <ClientForm segment={segment} edit={edit} nodes={nodes} backendUrl={backendUrl} catalog={catalog} busy={busy}
setAddProtocol={addProtocol => setEdit(selection => selection && { ...selection, addProtocol })}
save={async input => { if (await save(input)) setOpen(false) }} cancel={() => setOpen(false)} />}
</SheetContent>
</Sheet>
</Frame>
}
+254
View File
@@ -0,0 +1,254 @@
"use client"
import { useId, useState, type ReactNode } from "react"
import Link from "next/link"
import { PlusIcon, XIcon } from "lucide-react"
import type { IxNodeInventory, IxSite } from "@mmapp/contracts/internet-exchange"
import { Button } from "@/components/ui/button"
import { Field, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Checkbox } from "@/components/ui/checkbox"
import { Textarea } from "@/components/ui/textarea"
type Binding = IxSite["interfaces"][number]
type Group = IxSite["groups"][number]
type Path = Group["primary"]
type Peer = IxSite["neighbors"][number]
type Choice = { value: string; label: string; disabled?: boolean }
function TextField({ label, value, edit, numeric, placeholder }: {
label: string; value: string | number; edit: (value: string) => void; numeric?: boolean; placeholder?: string
}) {
const id = useId()
return <Field className="min-w-0">
<FieldLabel htmlFor={id}>{label}</FieldLabel>
<Input id={id} value={value} inputMode={numeric ? "numeric" : undefined} placeholder={placeholder}
onChange={event => { if (!numeric || /^\d*$/.test(event.target.value)) edit(event.target.value) }} />
</Field>
}
function Pick<T extends string>({ label, value, options, edit, disabled }: {
label: string; value?: T; options: readonly { value: T; label: string; disabled?: boolean }[]; edit: (value: T) => void; disabled: boolean
}) {
const id = useId()
return <Field className="min-w-0">
<FieldLabel htmlFor={id}>{label}</FieldLabel>
<Select value={value ?? null} items={options} disabled={disabled}
onValueChange={next => { if (next !== null) edit(next) }}>
<SelectTrigger className="w-full" id={id}><SelectValue placeholder="Выберите значение" /></SelectTrigger>
<SelectContent>{options.map(item => <SelectItem key={item.value} value={item.value} disabled={item.disabled}>{item.label}</SelectItem>)}</SelectContent>
</Select>
</Field>
}
function Flag({ label, checked, edit, disabled }: {
label: string; checked: boolean; edit: (value: boolean) => void; disabled: boolean
}) {
const id = useId()
return <Field orientation="horizontal" className="w-fit">
<Checkbox id={id} checked={checked} onCheckedChange={edit} disabled={disabled} />
<FieldLabel htmlFor={id}>{label}</FieldLabel>
</Field>
}
function Lines({ label, value, edit }: { label: string; value: string[]; edit: (value: string[]) => void }) {
const id = useId()
return <Field className="min-w-0">
<FieldLabel htmlFor={id}>{label}</FieldLabel>
<Textarea id={id} value={value.join("\n")} rows={2} placeholder="По одному префиксу на строку"
onChange={event => edit(event.target.value.split("\n"))}
onBlur={event => edit(event.target.value.split("\n").map(line => line.trim()).filter(Boolean))} />
</Field>
}
function Entries<T>({ title, items, edit, make, addLabel, max, readOnly, children, label, visible }: {
title: string; items: T[]; edit: (items: T[]) => void; make: () => T
addLabel: string; max: number; readOnly: boolean; children: (item: T, edit: (item: T) => void) => ReactNode
label?: (item: T) => string; visible?: (item: T) => boolean
}) {
const [expanded, setExpanded] = useState<number | null>(null)
const rows = items.map((item, index) => ({ item, index })).filter(({ item }) => !visible || visible(item))
return <section className="grid min-w-0 gap-2 border-t py-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<h4 className="text-sm font-medium">{title} <span className="text-muted-foreground">· {rows.length}</span></h4>
{!readOnly && <Button type="button" variant="outline" size="sm" disabled={items.length >= max}
onClick={() => { setExpanded(items.length); edit([...items, make()]) }}><PlusIcon aria-hidden />{addLabel}</Button>}
</div>
{rows.map(({ item, index }) => <div key={index} className="min-w-0 border-s-2 ps-3">
<Button type="button" size="sm" variant="ghost" aria-expanded={expanded === index}
onClick={() => setExpanded(expanded === index ? null : index)}>{label?.(item) || "Запись " + (index + 1)}</Button>
{expanded === index && <fieldset disabled={readOnly} className="grid gap-3 py-2">
{children(item, update => edit(items.map((entry, position) => position === index ? update : entry)))}
{!readOnly && <Button type="button" size="sm" className="w-fit" variant="ghost" aria-label={title + " — удалить запись " + (index + 1)}
onClick={() => { setExpanded(null); edit(items.filter((_, position) => position !== index)) }}><XIcon aria-hidden />Удалить</Button>}
</fieldset>}
</div>)}
</section>
}
const columns = "grid min-w-0 gap-3 sm:grid-cols-2"
const none = {value: "", label: "Нет"}
const emptyPath = (name: string): Path => ({ interface: name, nextHop: "", probe: "" })
const emptyWireGuard = { peerPublicKey: "", listenPort: 51820, localAddress: "", peerAddress: "" }
const kinds = [
{ value: "wireguard", label: "WireGuard" }, { value: "gre-ipsec", label: "GRE/IPsec" }, { value: "uplink", label: "Аплинк" },
] as const
function InterfaceFields({ value, edit, peers, readOnly, segmentName, inventory }: {
value: Binding; edit: (value: Binding) => void; peers: Choice[]; readOnly: boolean; segmentName: string
inventory: IxNodeInventory["interfaces"]
}) {
const wireGuard = value.provisionWireguard
const choices = inventory.filter(item => item.name === value.name || value.kind === "uplink" ||
(value.kind === "wireguard" ? ["wg", "wireguard"] : ["gre", "gre-tunnel"]).includes(item.type))
.map(item => ({ value: item.name, label: [item.name, item.addresses.join(", "), item.restriction].filter(Boolean).join(" · "),
disabled: item.name !== value.name && (item.disabled || !!item.restriction) }))
if (value.name && !choices.some(item => item.value === value.name)) choices.unshift({ value: value.name, label: value.name, disabled: false })
return <>
<div className={columns}>
{wireGuard || !inventory.length ? <TextField label="Имя интерфейса" value={value.name} edit={name => edit({ ...value, name })} />
: <Pick label="Интерфейс CHR" value={value.name || undefined} options={choices} disabled={readOnly}
edit={name => edit({ ...value, name })} />}
<Pick label="Тип подключения" value={value.kind} options={kinds} disabled={readOnly}
edit={kind => edit({ ...value, kind, ...(kind !== "wireguard" && {provisionWireguard: undefined}), ...(kind !== "uplink" && {natIpv4: undefined}) })} />
<Pick label="Удалённый узел" value={value.peerServerId ? String(value.peerServerId) : ""} options={[{ value: "", label: "Внешний сервер" }, ...peers]} disabled={readOnly}
edit={id => edit({ ...value, peerServerId: id ? Number(id) : undefined })} />
<TextField label="Локальный внешний адрес" value={value.localEndpoint ?? ""} edit={address => edit({ ...value, localEndpoint: address || undefined })} />
<TextField label="Удалённый внешний адрес" value={value.endpoint ?? ""} edit={address => edit({ ...value, endpoint: address || undefined })} />
</div>
<Lines label="Префиксы подключения" value={value.prefixes} edit={prefixes => edit({ ...value, prefixes })} />
{value.kind === "gre-ipsec" && <p className="text-sm text-muted-foreground">
Создайте выделенный туннель в разделе <Link className="underline" href="/gre">GRE-туннели</Link>.
Укажите комментарий <code>IX:{segmentName || "<имя сегмента>"}</code>, включите IPsec и отключите FastPath.
IX проверит обязательную транспортную политику GRE между указанными IPv4-адресами.
</p>}
{(value.kind === "uplink" || (value.kind === "wireguard" && !wireGuard)) && <p className="text-sm text-muted-foreground">
Для подключения существующего интерфейса выделите его под этот сегмент и задайте комментарий <code>IX:{segmentName || "<имя сегмента>"}</code>.
</p>}
{value.kind === "uplink" && <Flag label="NAT IPv4" checked={!!value.natIpv4} disabled={readOnly} edit={natIpv4 => edit({ ...value, natIpv4 })} />}
{value.kind === "wireguard" && <Flag label="Создать интерфейс и пир WireGuard на узле IX" checked={!!wireGuard} disabled={readOnly}
edit={enabled => edit({ ...value, provisionWireguard: enabled ? { ...emptyWireGuard } : undefined })} />}
{wireGuard && <div className={columns}>
<TextField label="Публичный ключ пира" value={wireGuard.peerPublicKey} edit={peerPublicKey => edit({ ...value, provisionWireguard: { ...wireGuard, peerPublicKey } })} />
<TextField label="Порт WireGuard на IX" numeric value={wireGuard.listenPort || ""} edit={port => edit({ ...value, provisionWireguard: { ...wireGuard, listenPort: Number(port) } })} />
<TextField label="Локальный адрес туннеля (CIDR)" value={wireGuard.localAddress} edit={localAddress => edit({ ...value, provisionWireguard: { ...wireGuard, localAddress } })} />
<TextField label="Адрес пира в туннеле" value={wireGuard.peerAddress} edit={peerAddress => edit({ ...value, provisionWireguard: { ...wireGuard, peerAddress } })} />
<TextField label="Внешний адрес IX для шаблона Linux" value={wireGuard.hubEndpoint ?? ""} edit={address => edit({ ...value, provisionWireguard: { ...wireGuard, hubEndpoint: address || undefined } })} />
<TextField label="Порт удалённого WireGuard" numeric value={wireGuard.endpointPort ?? ""} edit={port => edit({ ...value, provisionWireguard: { ...wireGuard, endpointPort: port ? Number(port) : undefined } })} />
</div>}
</>
}
function PathFields({ title, value, edit, interfaces, inventory, readOnly }: {
title: string; value: Path; edit: (value: Path) => void; interfaces: Choice[]; inventory: IxNodeInventory["interfaces"]; readOnly: boolean
}) {
const choices = value.viaMain ? inventory.filter(item => !interfaces.some(choice => choice.value === item.name) && !item.disabled)
.map(item => ({ value: item.name, label: item.name })) : [...interfaces]
if (value.interface && !choices.some(item => item.value === value.interface)) choices.unshift({ value: value.interface, label: value.interface })
return <fieldset className="grid min-w-0 gap-3 rounded-md border p-3 sm:grid-cols-3">
<legend className="px-1 text-sm font-medium">{title}</legend>
<div className="sm:col-span-3"><Flag label="WAN из таблицы main" checked={!!value.viaMain} disabled={readOnly}
edit={viaMain => edit({ ...emptyPath(""), viaMain })} /></div>
<Pick label="Интерфейс пути" value={value.interface || undefined} options={choices} edit={name => edit({ ...value, interface: name })} disabled={readOnly} />
<TextField label="Адрес следующего шлюза" value={value.nextHop} edit={nextHop => edit({ ...value, nextHop })} />
<TextField label="Контрольный адрес" value={value.probe} edit={probe => edit({ ...value, probe })} />
</fieldset>
}
function GroupFields({ value, edit, interfaces, inventory, alternatives, readOnly }: {
value: Group; edit: (value: Group) => void; interfaces: Choice[]; inventory: IxNodeInventory["interfaces"]
alternatives: Group[]; readOnly: boolean
}) {
const selectedBackup = alternatives.find(other => other.primary.interface === value.backup?.interface &&
other.primary.nextHop === value.backup?.nextHop && other.primary.probe === value.backup?.probe)
return <>
<Pick label="Резервный выход" value={value.backup ? selectedBackup?.id ?? ":manual" : ""} disabled={readOnly}
options={[none, ...alternatives.map(other => ({ value: other.id, label: other.id })), { value: ":manual", label: "Указать другой шлюз" }]}
edit={id => edit({ ...value, backup: id === ":manual" ? emptyPath(interfaces.find(item => item.value !== value.primary.interface)?.value ?? "")
: alternatives.find(other => other.id === id)?.primary })} />
<div className={columns}>
<TextField label="Имя группы шлюзов" value={value.id} edit={id => edit({ ...value, id })} />
<TextField label="Служебный адрес шлюза" value={value.gateway} edit={gateway => edit({ ...value, gateway })} />
<Pick label="Если оба пути недоступны" value={value.onFailure} disabled={readOnly} options={[
{value: "block", label: "Отбрасывать трафик"}, {value: "segment-exit", label: "Использовать выход сегмента"},
]} edit={onFailure => edit({ ...value, onFailure })} />
</div>
<PathFields title="Основной путь" value={value.primary} interfaces={interfaces} inventory={inventory} readOnly={readOnly} edit={primary => edit({ ...value, primary })} />
{value.backup && <PathFields title="Резервный путь" value={value.backup} interfaces={interfaces} inventory={inventory}
readOnly={readOnly} edit={backup => edit({ ...value, backup })} />}
</>
}
function PeerFields({ value, edit, interfaces, groups, readOnly }: {
value: Peer; edit: (value: Peer) => void; interfaces: Choice[]; groups: Choice[]; readOnly: boolean
}) {
const publicFeed = value.type === "public-feed"
return <>
<div className={columns}>
<TextField label="Имя BGP-соседа" value={value.id} edit={id => edit({ ...value, id })} />
<Pick label="Тип BGP-соседа" value={value.type} disabled={readOnly} options={[
{value: "member", label: "Участник IX"}, {value: "exchange", label: "Вторая площадка"}, {value: "public-feed", label: "Публичный фид"},
]} edit={type => edit({ ...value, type, ...(type === "public-feed" ? { group: undefined, exportPrefixes: [] } : { rules: [] }) })} />
<TextField label="Адрес BGP-соседа" value={value.address} edit={address => edit({ ...value, address })} />
<TextField label="Локальный адрес BGP" value={value.localAddress} edit={localAddress => edit({ ...value, localAddress })} />
<TextField label="ASN соседа" numeric value={value.remoteAs || ""} edit={asn => edit({ ...value, remoteAs: Number(asn) })} />
<Pick label="Интерфейс BGP" value={value.binding} options={interfaces} disabled={readOnly} edit={binding => edit({ ...value, binding })} />
<Pick label="Лимит префиксов" value={String(value.limit)} options={[10, 100, 1000, 10000].map(limit => ({value: String(limit), label: String(limit)}))}
disabled={readOnly} edit={limit => edit({ ...value, limit: Number(limit) as Peer["limit"] })} />
{!publicFeed && <Pick label="Группа шлюзов для импорта" value={value.group} options={groups} disabled={readOnly} edit={group => edit({ ...value, group })} />}
</div>
<Lines label="Префиксы импорта" value={value.prefixes} edit={prefixes => edit({ ...value, prefixes })} />
{publicFeed
? <Entries title="Правила по BGP community" items={value.rules} edit={rules => edit({ ...value, rules })}
make={() => ({ community: "", group: groups[0]?.value ?? "" })} max={100} addLabel="Добавить правило" readOnly={readOnly}>
{(rule, update) => <div className={columns}>
<TextField label="BGP community" value={rule.community} placeholder="65000:10" edit={community => update({ ...rule, community })} />
<Pick label="Группа шлюзов правила" value={rule.group} options={groups} edit={group => update({ ...rule, group })} disabled={readOnly} />
</div>}
</Entries>
: <Lines label="Префиксы экспорта" value={value.exportPrefixes} edit={exportPrefixes => edit({ ...value, exportPrefixes })} />}
</>
}
export function IxSiteEditor({ site, edit, peers, readOnly, segmentName, inventory }: {
site: IxSite; edit: (fields: Partial<IxSite>) => void; peers: Choice[]; readOnly: boolean; segmentName: string
inventory: IxNodeInventory["interfaces"]
}) {
const interfaces = site.interfaces.filter(item => item.name).map(item => ({ value: item.name, label: item.name }))
const groups = site.groups.filter(item => item.id).map(item => ({ value: item.id, label: item.id }))
return <div className="grid min-w-0 gap-2">
<Entries<Binding> title="Интерфейсы маршрутизации" label={item => item.name} visible={item => !item.linux && !item.provisionTransit} items={site.interfaces} edit={interfaces => edit({ interfaces })}
make={() => ({ name: "", kind: "wireguard", prefixes: [] })} max={80} addLabel="Добавить интерфейс" readOnly={readOnly}>
{(value, update) => <InterfaceFields value={value} edit={update} peers={peers} readOnly={readOnly} segmentName={segmentName} inventory={inventory} />}
</Entries>
<Entries<Group> title="Выходы и резерв" label={item => item.id} items={site.groups} edit={groups => edit({ groups })}
make={() => ({ id: "", gateway: "", primary: emptyPath(interfaces[0]?.value ?? ""), onFailure: "block" })}
max={24} addLabel="Добавить группу шлюзов" readOnly={readOnly}>
{(value, update) => <GroupFields value={value} edit={update} interfaces={interfaces} inventory={inventory}
alternatives={site.groups.filter(group => group.id !== value.id && group.primary.interface !== value.primary.interface &&
group.gateway.includes(":") === value.gateway.includes(":"))} readOnly={readOnly} />}
</Entries>
<Entries title="Статические маршруты" label={item => item.prefix} items={site.routes} edit={routes => edit({ routes })}
make={() => ({ prefix: "", group: groups[0]?.value ?? "" })} max={250} addLabel="Добавить маршрут" readOnly={readOnly}>
{(route, update) => <div className={columns}>
<TextField label="Префикс маршрута" value={route.prefix} edit={prefix => update({ ...route, prefix })} />
<Pick label="Группа шлюзов маршрута" value={route.group} options={groups} edit={group => update({ ...route, group })} disabled={readOnly} />
</div>}
</Entries>
<Entries<Peer> title="BGP-соседи" label={item => item.id} items={site.neighbors} edit={neighbors => edit({ neighbors })} max={16} addLabel="Добавить BGP-соседа" readOnly={readOnly}
make={() => ({ id: "", type: "member", address: "", localAddress: "", remoteAs: 0,
binding: interfaces[0]?.value ?? "", group: groups[0]?.value, prefixes: [], exportPrefixes: [], rules: [], limit: 1000 })}>
{(value, update) => <PeerFields value={value} edit={update} interfaces={interfaces} groups={groups} readOnly={readOnly} />}
</Entries>
<details className="rounded-lg border">
<summary className="cursor-pointer px-3 py-2 text-sm font-medium">Выходы по умолчанию и маршруты отбрасывания</summary>
<fieldset disabled={readOnly} className="grid gap-3 border-t p-3">
{[0, 1].map(index => <Pick key={index} label={"Группа выхода " + (index + 1)} value={site.exits[index] ?? ""}
options={[none, ...groups.filter(group => group.value !== site.exits[1 - index])]} disabled={readOnly}
edit={id => { const exits = [...site.exits]; exits[index] = id; edit({ exits: exits.filter(Boolean) }) }} />)}
<Lines label="Префиксы отбрасывания" value={site.discardNetworks} edit={discardNetworks => edit({ discardNetworks })} />
</fieldset>
</details>
</div>
}
+198
View File
@@ -0,0 +1,198 @@
"use client"
import { useEffect, useMemo, useState } from "react"
import { type ColumnDef, useTable } from "@tanstack/react-table"
import { FileTextIcon, PlusIcon, XIcon } from "lucide-react"
import type { IxConfiguration, IxNodeInventory, IxSegment, IxSite, IxSiteObservation } from "@mmapp/contracts/internet-exchange"
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
import { EmptyState } from "@/components/empty-state"
import { Badge } from "@/components/reui/badge"
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { requestJson } from "@/shared/api/http-client"
import { IxSiteEditor } from "./ix-site-editor"
export type IxNode = { id: number; name: string; site: string; country: string; enabled: boolean; type?: string }
type Route = IxSiteObservation["routes"][number]
export const nodeLabel = (nodes: readonly IxNode[], id: number) => nodes.find(node => node.id === id)?.name || `Узел ${id}`
export const newSite = (): IxSite => ({
serverId: 0, autonomousSystem: 64512, routerId: "", autoRouterId: true,
interfaces: [], groups: [], exits: [], routes: [], neighbors: [], discardNetworks: [],
})
export function SegmentStatus({ segment }: { segment: IxSegment }) {
return segment.revision === segment.appliedRevision
? <Badge variant="success-light">Применена</Badge>
: <Badge variant="warning-light">{segment.appliedRevision ? "Есть черновик" : "Черновик"}</Badge>
}
export function SegmentGrid({ rows, nodes, loading, open, empty }: {
rows: IxSegment[]; nodes: IxNode[]; loading: boolean; open: (segment: IxSegment) => void; empty: React.ReactNode
}) {
const columns = useMemo<ColumnDef<DataGridFeatures, IxSegment>[]>(() => [
{ id: "name", header: "Сегмент", size: 210, cell: ({ row }) => (
<Button type="button" variant="link" size="sm" className="max-w-full justify-start" onClick={() => open(row.original)}>
<span className="truncate">{row.original.configuration.name}</span>
</Button>
) },
{ id: "sites", header: "Площадки", size: 230, cell: ({ row }) => row.original.configuration.sites.map(site => nodeLabel(nodes, site.serverId)).join(", ") },
{ id: "clients", header: "Linux-клиенты", size: 125, cell: ({ row }) =>
<span className="tabular-nums">{row.original.configuration.sites.reduce((total, site) => total + site.interfaces.filter(item => item.linux).length, 0)}</span> },
{ id: "state", header: "Состояние", size: 140, cell: ({ row }) => <SegmentStatus segment={row.original} /> },
], [nodes, open])
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns, getRowId: row => row.id })
return <DataGridShell table={table} recordCount={rows.length} isLoading={loading} loadingMode="skeleton" emptyMessage={empty} />
}
export function useIxNodeInventory(backendUrl: string, serverId: number, segmentId?: string) {
const path = serverId > 0 ? `/api/ix/nodes/${serverId}/inventory${segmentId ? "?segmentId=" + segmentId : ""}` : null
const [result, setResult] = useState<{ path: string; inventory?: IxNodeInventory; error?: string }>()
const [refresh, setRefresh] = useState(0)
useEffect(() => {
if (!path) return
const controller = new AbortController()
void requestJson<IxNodeInventory>(backendUrl, path, { signal: controller.signal }).then(inventory => {
if (!Array.isArray(inventory?.interfaces) || !Array.isArray(inventory.defaultRoutes)) throw new Error("Неполный каталог интерфейсов")
if (!controller.signal.aborted) setResult({ path, inventory })
}).catch(() => {
if (!controller.signal.aborted) setResult({ path, error: "Не удалось прочитать интерфейсы CHR" })
})
return () => controller.abort()
}, [backendUrl, path, refresh])
return { ...(result?.path === path ? result : undefined), loading: path !== null && result?.path !== path,
reload: () => { setResult(undefined); setRefresh(value => value + 1) } }
}
function IxInventoryFields({ site, segmentId, backendUrl, fieldId, peers, readOnly, segmentName, edit }: {
site: IxSite; segmentId?: string; backendUrl: string; fieldId: string; peers: { value: string; label: string }[]
readOnly: boolean; segmentName: string; edit: (fields: Partial<IxSite>) => void
}) {
const { inventory, error, loading, reload } = useIxNodeInventory(backendUrl, site.serverId, segmentId)
const suggested = site.routerId || (site.autoRouterId ? inventory?.routerId ?? "" : "")
return <>
<Field className="min-w-0">
<FieldLabel htmlFor={fieldId + "-router"}>Router ID</FieldLabel>
<Input id={fieldId + "-router"} value={suggested} placeholder="Подбирается автоматически" readOnly={readOnly}
onChange={event => edit({ routerId: event.target.value, autoRouterId: !event.target.value })} />
<FieldDescription>{suggested ? site.autoRouterId ? "Назначен автоматически" : "Задан вручную" :
loading ? "Проверяем занятые идентификаторы…" : "Свободный ID будет выбран при сохранении."}</FieldDescription>
</Field>
<div className="grid min-w-0 gap-3 sm:col-span-2 lg:col-span-3">
{site.serverId > 0 && <div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-sm text-muted-foreground" role="status">
{loading ? "Читаем интерфейсы CHR…" : error ?? `Интерфейсы CHR · ${inventory?.interfaces?.length ?? 0}`}
</span>
<Button type="button" size="sm" variant="outline" disabled={loading} onClick={reload}>Обновить интерфейсы</Button>
</div>}
<IxSiteEditor site={site} segmentName={segmentName} readOnly={readOnly} edit={edit} peers={peers}
inventory={inventory?.interfaces ?? []} />
</div>
</>
}
export function ConfigurationFields({ configuration, nodes, peers, readOnly, change, backendUrl, segmentId, section }: {
section: "configuration" | "routes"
configuration: IxConfiguration; nodes: IxNode[]; peers: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void
backendUrl: string; segmentId?: string
}) {
function updateSite(index: number, fields: Partial<IxSite>) {
change({ ...configuration, sites: configuration.sites.map((site, position) => position === index ? { ...site, ...fields } : site) })
}
const canAddSite = configuration.sites.length < 2 && nodes.filter(node => node.enabled).length > configuration.sites.length
return <div className="grid min-w-0 gap-3">
{section === "configuration" && <Frame spacing="sm">
<FrameHeader><FrameTitle>Сегмент</FrameTitle></FrameHeader>
<FramePanel>
<Field className="max-w-md">
<FieldLabel htmlFor="ix-name">Имя сегмента</FieldLabel>
<Input id="ix-name" placeholder="ix-central" value={configuration.name} readOnly={readOnly}
onChange={event => change({ ...configuration, name: event.target.value })} />
{!readOnly && <FieldDescription>Латинские строчные буквы, цифры и дефисы.</FieldDescription>}
</Field>
</FramePanel>
</Frame>}
{configuration.sites.map((site, index) => {
const fieldId = `ix-site-${index}`
const choices = nodes.filter(node => node.id === site.serverId || (node.enabled && !configuration.sites.some((other, i) => i !== index && other.serverId === node.id)))
return <Frame key={fieldId} spacing="sm">
<FrameHeader className="flex-row items-center justify-between gap-2">
<div className="min-w-0">
<FrameTitle>{section === "configuration" ? "Площадка " + (index + 1) : nodeLabel(nodes, site.serverId)}</FrameTitle>
</div>
{section === "configuration" && !readOnly && configuration.sites.length > 1 && <Button type="button" size="icon-sm" variant="ghost"
aria-label={`Убрать площадку ${index + 1}`}
onClick={() => change({ ...configuration, sites: configuration.sites.filter((_, position) => position !== index) })}>
<XIcon aria-hidden />
</Button>}
</FrameHeader>
<FramePanel className="grid gap-4">
<div className="grid min-w-0 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{section === "configuration" && <Field className="min-w-0">
<FieldLabel htmlFor={fieldId}>Узел IX</FieldLabel>
<Select
value={site.serverId ? String(site.serverId) : null}
items={choices.map(node => ({ value: String(node.id), label: node.name }))}
disabled={readOnly}
onValueChange={value => { if (value && Number(value) !== site.serverId) updateSite(index, { ...newSite(), serverId: Number(value) }) }}
>
<SelectTrigger id={fieldId} className="w-full"><SelectValue placeholder="Выберите узел" /></SelectTrigger>
<SelectContent>
{choices.map(node => <SelectItem key={node.id} value={String(node.id)} disabled={!node.enabled}>{node.name}</SelectItem>)}
</SelectContent>
</Select>
</Field>}
{section === "routes" && <Field className="min-w-0">
<FieldLabel htmlFor={fieldId + "-asn"}>Локальный ASN</FieldLabel>
<Input id={fieldId + "-asn"} inputMode="numeric" value={site.autonomousSystem || ""} readOnly={readOnly}
onChange={event => { if (/^\d*$/.test(event.target.value)) updateSite(index, { autonomousSystem: Number(event.target.value) }) }} />
</Field>}
{section !== "configuration" && <IxInventoryFields site={site} segmentId={segmentId} backendUrl={backendUrl} fieldId={fieldId}
readOnly={readOnly} segmentName={configuration.name} edit={fields => updateSite(index, fields)}
peers={peers.filter(node => node.id !== site.serverId && (node.enabled || site.interfaces.some(binding => binding.peerServerId === node.id)))
.map(node => ({ value: String(node.id), label: node.name }))} />}
</div>
</FramePanel>
</Frame>
})}
{section === "configuration" && !readOnly && canAddSite && <Button type="button" variant="outline" size="sm" className="w-fit"
onClick={() => change({ ...configuration, sites: [...configuration.sites, newSite()] })}>
<PlusIcon aria-hidden />Добавить площадку
</Button>}
</div>
}
const routeColumns: ColumnDef<DataGridFeatures, Route>[] = [
{ id: "prefix", header: "Префикс", size: 160, cell: ({ row }) => <span className="font-mono">{row.original.prefix}</span> },
{ id: "gateway", header: "Шлюз", size: 140, cell: ({ row }) => row.original.gateway || "—" },
{ id: "immediate", header: "Фактический next hop", size: 200, cell: ({ row }) => row.original.immediateGateway ?? "—" },
{ id: "active", header: "Состояние", size: 112, cell: ({ row }) => row.original.active
? <Badge variant="success-light">Активен</Badge>
: <Badge variant="secondary">Неактивен</Badge> },
]
export function RouteGrid({ observation, nodes }: { observation: IxSiteObservation; nodes: IxNode[] }) {
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: observation.routes, columns: routeColumns })
return <Frame spacing="sm" className="min-w-0">
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
<div className="min-w-0">
<FrameTitle className="wrap-anywhere">{nodeLabel(nodes, observation.serverId)}</FrameTitle>
<FrameDescription>{new Date(observation.observedAt).toLocaleString("ru-RU")}</FrameDescription>
</div>
{observation.available ? <Badge variant="info-light">
BGP {observation.neighbors.filter(peer => peer.established).length} из {observation.neighbors.length}
</Badge> : <Badge variant="warning-light">Состояние недоступно</Badge>}
</FrameHeader>
{observation.available && <FramePanel className="min-w-0 p-0">
<div className="overflow-x-auto">
<DataGridShell table={table} recordCount={observation.routes.length}
emptyMessage={<EmptyState icon={<FileTextIcon />} title="Маршруты не найдены" className="py-8" />} />
</div>
</FramePanel>}
</Frame>
}
+560
View File
@@ -0,0 +1,560 @@
"use client"
import { useEffect, useRef, useState } from "react"
import Link from "next/link"
import { ArrowLeftIcon, CircleAlertIcon, NetworkIcon, PlusIcon, RefreshCwIcon, Trash2Icon } from "lucide-react"
import { ixSegmentConfigurationSchema, type IxChange, type IxConfiguration, type IxLinuxAccess, type IxLinuxBinding, type IxLinuxClientRequest, type IxLinuxPath, type IxTransitRequest, type IxWebPlan, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
import { EmptyState } from "@/components/empty-state"
import { PageHeader } from "@/components/page-header"
import { ServerRailLayout, ServerRailMobileButton } from "@/components/server-rail-layout"
import { ALL_SERVERS_ID } from "@/components/server-tile-rail"
import { Button } from "@/components/ui/button"
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Textarea } from "@/components/ui/textarea"
import { can, ensureAuthConfig } from "@/lib/auth"
import { useDataSource } from "@/lib/data-source"
import { requestJson } from "@/shared/api/http-client"
import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, SegmentStatus, type IxNode } from "./ix-view"
import { IxLinuxClients } from "./ix-linux-clients"
import { IxExits } from "./ix-exits"
import { IxClientBonds } from "./ix-client-bonds"
import { copyIxImportLink } from "./ix-import-link"
type Tab = "configuration" | "routes" | "linux"
const title = "Точки обмена трафиком"
const describe = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить операцию IX"
const json = (value: unknown) => JSON.stringify(value, null, 2)
const post = (value: unknown) => ({ method: "POST", body: JSON.stringify(value) })
function download(name: string, content: string) {
const url = URL.createObjectURL(new Blob([content], { type: "text/plain;charset=utf-8" }))
const link = document.createElement("a")
link.href = url
link.download = name
link.click()
setTimeout(() => URL.revokeObjectURL(url), 1000)
}
const actionLabels = { create: "Создать", update: "Обновить", delete: "Удалить" } as const
function RouterOsChanges({ changes, nodes }: { changes: IxWebPlan["changes"]; nodes: IxNode[] }) {
if (!changes.length) return null
return <ul className="max-h-56 min-w-0 divide-y overflow-auto rounded-md border">
{changes.map((operation, index) => <li key={index} className="min-w-0 p-2.5 text-sm">
<details>
<summary className="cursor-pointer wrap-anywhere">{actionLabels[operation.action]} · {nodeLabel(nodes, operation.serverId)} · <code>{operation.path}</code>
{operation.target && <> · <code>{operation.target}</code></>}
</summary>
<dl className="grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 py-2 text-xs">
{operation.placeBefore && <><dt className="text-muted-foreground">Перед объектом</dt><dd className="font-mono">{operation.placeBefore}</dd></>}
{Object.entries(operation.fields).map(([key, value]) => <div key={key} className="contents">
<dt className="max-w-32 wrap-anywhere text-muted-foreground">{key}</dt>
<dd className="wrap-anywhere font-mono">{value}</dd>
</div>)}
</dl>
</details>
</li>)}
</ul>
}
export default function IxPage() {
const { backendUrl, mode, prefsHydrated } = useDataSource()
const [segments, setSegments] = useState<IxSegment[]>([])
const [nodes, setNodes] = useState<IxNode[]>([])
const [peers, setPeers] = useState<IxNode[]>([])
const [selected, setSelected] = useState<IxSegment | null>(null)
const [draft, setDraft] = useState<IxConfiguration | null>(null)
const [advanced, setAdvanced] = useState<string | null>(null)
const [filter, setFilter] = useState("")
const [activeNode, setActiveNode] = useState(ALL_SERVERS_ID)
const [observations, setObservations] = useState<IxSiteObservation[] | null>(null)
const [linuxBindings, setLinuxBindings] = useState<IxLinuxBinding[]>([])
const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding & { transportOnly: boolean }) | null>(null)
const [linuxPath, setLinuxPath] = useState<(IxLinuxPath & Pick<IxLinuxBinding, "name" | "interfaceName">) | null>(null)
const [review, setReview] = useState("")
const [reviewError, setReviewError] = useState("")
const [plan, setPlan] = useState<IxWebPlan | null>(null)
const [removalPlan, setRemovalPlan] = useState<IxWebPlan | null>(null)
const [tab, setTab] = useState<Tab>("configuration")
const [loading, setLoading] = useState(true)
const [busy, setBusy] = useState(false)
const [error, setError] = useState("")
const [notice, setNotice] = useState("")
const [write, setWrite] = useState(false)
const heading = useRef<HTMLHeadingElement>(null)
const focusAfterNavigation = useRef(false)
const inDetail = draft !== null
async function load(signal?: AbortSignal) {
if (signal?.aborted) return
setWrite(can("mm:network:write"))
const [segmentsResult, nodesResult] = await Promise.all([
requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100", { signal }),
requestJson<{ items: IxNode[]; peers?: IxNode[] }>(backendUrl, "/api/ix/nodes", { signal }),
])
if (signal?.aborted) return
setSegments(segmentsResult.items)
setNodes(nodesResult.items)
setPeers(nodesResult.peers ?? nodesResult.items)
}
useEffect(() => {
if (!prefsHydrated || mode !== "live") return
const controller = new AbortController()
void ensureAuthConfig().then(() => {
if (controller.signal.aborted) return
setLoading(true)
setError("")
return load(controller.signal)
})
.catch(error => { if (!controller.signal.aborted) setError(describe(error)) })
.finally(() => { if (!controller.signal.aborted) setLoading(false) })
return () => controller.abort()
// Reload when the project data source changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [backendUrl, mode, prefsHydrated])
useEffect(() => {
if (focusAfterNavigation.current) {
focusAfterNavigation.current = false
heading.current?.focus()
}
}, [inDetail])
const rows = segments.filter(segment => (activeNode === ALL_SERVERS_ID ||
segment.configuration.sites.some(site => String(site.serverId) === activeNode)) &&
segment.configuration.name.includes(filter.trim().toLowerCase()))
const enabledNodes = nodes.filter(node => node.enabled && (activeNode === ALL_SERVERS_ID || String(node.id) === activeNode))
const live = prefsHydrated && mode === "live"
const canCreate = live && write && !loading && enabledNodes.length > 0
const savedConfiguration = selected ? json(selected.configuration) : null
const dirty = (advanced ?? json(draft)) !== savedConfiguration
const canPlan = live && write && selected !== null && selected.appliedRevision !== selected.revision && !dirty
function invalidateReview() {
setPlan(null)
setReview("")
setReviewError("")
setRemovalPlan(null)
setNotice("")
}
function open(segment: IxSegment | null, defaultTab: Tab = segment ? "linux" : "configuration") {
focusAfterNavigation.current = !inDetail
setSelected(segment)
setDraft(segment?.configuration ?? { name: "", sites: [{ ...newSite(), serverId: enabledNodes.length === 1 ? enabledNodes[0].id : 0 }] })
setAdvanced(null)
setObservations(null)
setLinux(null)
setLinuxPath(null)
setLinuxBindings([])
setTab(defaultTab)
setError("")
invalidateReview()
if (defaultTab === "linux" && segment?.appliedRevision) void perform(() => loadLinuxBindings(segment))
}
function close() {
focusAfterNavigation.current = true
setDraft(null)
setRemovalPlan(null)
setError("")
setNotice("")
}
function change(): IxChange {
const configuration = ixSegmentConfigurationSchema.parse(advanced === null && draft
? { ...draft, sites: draft.sites.map(site => ({ ...site, routerId: site.routerId || (site.autoRouterId ? "0.0.0.0" : "") })) }
: JSON.parse(advanced ?? "null"))
return { ...(selected ? { id: selected.id } : {}), revision: selected?.revision ?? 0, configuration }
}
async function perform(work: () => Promise<void>) {
setBusy(true)
setError("")
setNotice("")
try { await work(); return true } catch (error) { setError(describe(error)); return false }
finally { setBusy(false) }
}
async function save() {
if (selected && !dirty) {
await reviewSegment(selected, selected.configuration.name)
return
}
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl, "/api/ix/segments", post(change()))
await reviewSegment(segment, segment.configuration.name)
}
async function prepare(segment: IxSegment, resume = false) {
setPlan(null)
setReviewError("")
try {
setPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + segment.id + "/plan", post({
revision: segment.revision, ...(resume && { resume }),
})))
} catch (error) {
setReviewError(describe(error))
}
}
async function prepareRemoval() {
if (!selected) return
setRemovalPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + selected.id + "/removal-plan", post({ revision: selected.revision })))
}
async function removeSegment() {
if (!selected || !removalPlan) return
setRemovalPlan(null)
await requestJson<void>(backendUrl, "/api/ix/segments/" + selected.id, {
method: "DELETE", body: JSON.stringify({ revision: removalPlan.revision, digest: removalPlan.digest }),
})
setSegments(current => current.filter(segment => segment.id !== selected.id))
close()
setNotice("Сегмент " + selected.configuration.name + " удалён")
}
async function apply() {
if (!selected || !plan || !canPlan) return
setPlan(null)
try {
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl,
"/api/ix/segments/" + selected.id + "/apply", post({ revision: plan.revision, digest: plan.digest, ...(plan.resume && { resume: true }) }))
setSelected(segment)
setDraft(segment.configuration)
setAdvanced(null)
setObservations(null)
setLinux(null)
setLinuxPath(null)
setLinuxBindings([])
setSegments(current => current.map(item => item.id === segment.id ? segment : item))
setReview("")
setReviewError("")
setNotice("Конфигурация IX применена")
if (tab === "linux" || selected.appliedRevision === null) {
setTab("linux")
await loadLinuxBindings(segment).catch(error => setError(describe(error)))
} else if (tab === "routes") {
await observe(segment).catch(error => setError(describe(error)))
}
} catch (error) {
setReviewError(describe(error))
}
}
async function observe(segment = selected) {
if (!segment?.appliedRevision) return
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${segment.id}/status`)
setObservations(sites)
}
async function loadLinuxBindings(segment = selected) {
if (!segment) return
setLinux(null)
const { items } = await requestJson<{ items: IxLinuxBinding[] }>(backendUrl, `/api/ix/segments/${segment.id}/linux`)
setLinuxBindings(items)
}
async function exportLinux(binding: IxLinuxBinding, transportOnly = false) {
if (!selected) return
setLinux(null)
const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName })
if (transportOnly) query.set("transportOnly", "true")
if (binding.managedWireguard && write) {
const access = await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
post({ serverId: binding.serverId, interfaceName: binding.interfaceName, ...(transportOnly && { transportOnly }) }))
download(access.filename, access.template)
setNotice("Конфигурация WireGuard скачана")
return
}
const access = binding.policy && binding.kind === "gre-ipsec" && write
? await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
post({ serverId: binding.serverId, interfaceName: binding.interfaceName, ...(transportOnly && { transportOnly }) }))
: await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
setLinux({ ...binding, ...access, transportOnly })
}
async function copyLinuxImport(binding: IxLinuxBinding) {
if (!selected) return
await copyIxImportLink(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`, {
serverId: binding.serverId, interfaceName: binding.interfaceName,
})
setNotice("Ссылка скопирована. На VPS откройте ix-client → L. Ссылка действует до 5 минут.")
}
async function inspectLinux(binding: IxLinuxBinding) {
if (!selected) return
setLinuxPath(null)
const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName })
const path = await requestJson<IxLinuxPath>(backendUrl, `/api/ix/segments/${selected.id}/linux/path?${query}`)
setLinuxPath({ name: binding.name, interfaceName: binding.interfaceName, ...path })
}
async function stageClient(input: IxLinuxClientRequest | IxLinuxBinding) {
if (!selected || dirty || !write) return
const path = `/api/ix/segments/${selected.id}`
const result = "revision" in input
? await requestJson<{ segment: IxSegment; interfaceName: string }>(backendUrl, path + "/linux", post(input))
: await requestJson<{ segment: IxSegment }>(backendUrl, path + "/linux/revoke",
post({ revision: selected.revision, serverId: input.serverId, interfaceName: input.interfaceName }))
await reviewSegment(result.segment, "revision" in input ? "Доступ клиента " + input.name : "Отзыв доступа " + (input.name ?? input.interfaceName))
}
async function stageTransit(input: IxTransitRequest) {
if (!selected || dirty || !write) return
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl,
`/api/ix/segments/${selected.id}/transit`, post(input))
await reviewSegment(segment, "Выход через " + nodeLabel(peers, input.targetServerId))
}
async function reviewSegment(segment: IxSegment, title: string) {
setSelected(segment)
setDraft(segment.configuration)
setAdvanced(null)
setSegments(current => current.some(item => item.id === segment.id)
? current.map(item => item.id === segment.id ? segment : item) : [segment, ...current])
setLinux(null)
setLinuxPath(null)
setReview(title)
await prepare(segment)
}
function closeReview() {
if (busy) return
setReview("")
setPlan(null)
setReviewError("")
setNotice("Изменения сохранены в черновике. Нажмите «Сохранить», чтобы вернуться к подтверждению.")
}
function showTab(next: Tab) {
if (next === tab || busy) return
if (advanced !== null) {
try { setDraft(change().configuration); setAdvanced(null) } catch (error) { setError(describe(error)); return }
}
setError("")
setTab(next)
if (next === "routes" && observations === null && selected?.appliedRevision) void perform(observe)
if (next === "linux" && selected?.appliedRevision) void perform(loadLinuxBindings)
}
const settingsProps = draft && {
configuration: draft, nodes, peers, backendUrl, segmentId: selected?.id, readOnly: !live || !write || busy,
change: (value: IxConfiguration) => { setDraft(value); invalidateReview() },
}
const listEmpty = error ? "Не удалось загрузить список" :
filter.trim() ? "Сегменты не найдены" : !live ? "Подключите backend" : "Нет сегментов IX"
const listDescription = error ? "Повторите загрузку списка." : filter.trim() ? "Попробуйте другое имя сегмента." :
!live ? "Откройте раздел в режиме «Живые»." : enabledNodes.length ? undefined : "Сначала добавьте сервер типа IX Node."
return <ServerRailLayout items={nodes.map(node => ({ ...node, id: String(node.id), type: "ix-node", selectable: node.enabled }))}
selectedId={activeNode} allCount={nodes.length} loading={loading} showCount={false} preserveSelection onSelect={id => {
if (busy || id === activeNode) return
setActiveNode(id)
setFilter("")
const forNode = segments.filter(segment => segment.configuration.sites.some(site => String(site.serverId) === id))
if (forNode.length === 1) open(forNode[0], "linux")
else close()
}}
header={<PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]}
actions={<ServerRailMobileButton />} />}>
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto">
<div className="flex w-full min-w-0 flex-col gap-4 p-4 md:gap-5 md:p-6" aria-busy={busy}>
{inDetail && <Button type="button" variant="ghost" size="sm" className="w-fit" disabled={busy} onClick={close}>
<ArrowLeftIcon aria-hidden />Все сегменты
</Button>}
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<h1 ref={heading} tabIndex={-1} className="text-xl font-semibold tracking-tight wrap-anywhere md:text-2xl">
{inDetail ? selected?.configuration.name ?? "Новый сегмент" : title}
</h1>
{inDetail && selected && <SegmentStatus segment={selected} />}
</div>
{inDetail ? (selected && <p className="mt-1 text-sm text-muted-foreground">
Ревизия {selected.revision}{selected.appliedRevision && selected.appliedRevision !== selected.revision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
</p>) : <p className="mt-1 text-sm text-muted-foreground">Сегменты IX, площадки и маршрутизация</p>}
</div>
{inDetail && live && write && <div className="flex flex-wrap items-center gap-2">
{(dirty || canPlan) && <Button type="button" size="sm" disabled={busy} onClick={() => void perform(save)}>Сохранить</Button>}
{selected && <AlertDialog open={removalPlan !== null}
onOpenChange={open => { if (open) void perform(prepareRemoval); else setRemovalPlan(null) }}>
<AlertDialogTrigger render={<Button type="button" variant="outline" size="sm" disabled={busy} />}>
<Trash2Icon aria-hidden />Удалить сегмент
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="wrap-anywhere">Удалить {selected.configuration.name}?</AlertDialogTitle>
<AlertDialogDescription>
{selected.appliedRevision
? "Этот сегмент перестанет передавать трафик. Управляемая конфигурация будет удалена с узлов IX."
: "Черновик будет удалён из списка сегментов. Конфигурация роутеров останется прежней."}
</AlertDialogDescription>
</AlertDialogHeader>
{removalPlan && <RouterOsChanges changes={removalPlan.changes} nodes={nodes} />}
<AlertDialogFooter>
<AlertDialogCancel>Отмена</AlertDialogCancel>
<AlertDialogAction variant="destructive" disabled={busy} onClick={() => void perform(removeSegment)}>Удалить</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>}
</div>}
{!inDetail && <div className="flex flex-wrap items-center gap-2">
<Button type="button" size="icon-sm" variant="outline" disabled={busy || loading || !live} aria-label="Обновить список"
onClick={() => void perform(() => load())}><RefreshCwIcon aria-hidden /></Button>
{canCreate && <Button type="button" size="sm" onClick={() => open(null)} disabled={busy}><PlusIcon aria-hidden />Добавить сегмент</Button>}
</div>}
</div>
{error && <Alert variant="destructive"><CircleAlertIcon aria-hidden /><AlertTitle>Ошибка IX</AlertTitle><AlertDescription className="wrap-anywhere">{error}</AlertDescription></Alert>}
{notice && <p role="status" className="text-sm text-muted-foreground">{notice}</p>}
{!draft ? <Frame spacing="sm" className="min-w-0">
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
<div><FrameTitle>Сегменты</FrameTitle><FrameDescription>{live && !loading ? `Найдено: ${rows.length}` : ""}</FrameDescription></div>
<Input type="search" aria-label="Поиск сегментов" placeholder="Найти сегмент" className="w-full sm:w-56"
value={filter} onChange={event => setFilter(event.target.value)} />
</FrameHeader>
<FramePanel className="min-w-0 p-0">
<div className="overflow-x-auto">
<SegmentGrid rows={rows} nodes={nodes} loading={!prefsHydrated || (live && loading)} open={open} empty={
<EmptyState icon={<NetworkIcon aria-hidden />} title={listEmpty} description={listDescription}
action={live && !filter.trim() && !error && enabledNodes.length === 0 ? <Button render={<Link href="/servers" />} nativeButton={false} size="sm" variant="outline">Открыть серверы</Button> : undefined} />
} />
</div>
</FramePanel>
</Frame> : <Tabs value={tab} onValueChange={value => showTab(value as Tab)} className="min-w-0 gap-3">
<div className="min-w-0 overflow-x-auto border-b pb-1">
<TabsList variant="line" aria-label="Разделы сегмента">
{selected && <>
<TabsTrigger value="linux">Linux-клиенты</TabsTrigger>
<TabsTrigger value="routes">Маршрутизация</TabsTrigger>
</>}
<TabsTrigger value="configuration">Настройки IX</TabsTrigger>
</TabsList>
</div>
<TabsContent value="configuration" className="grid min-w-0 gap-3">
{advanced === null ? settingsProps && <ConfigurationFields {...settingsProps} section="configuration" /> : <Frame spacing="sm">
<FrameHeader><FrameTitle>Конфигурация JSON</FrameTitle><FrameDescription>Интерфейсы, группы шлюзов, маршруты и BGP-политики.</FrameDescription></FrameHeader>
<FramePanel>
<Textarea aria-label="Конфигурация JSON" spellCheck={false} readOnly={!live || !write || busy} rows={14}
className="font-mono" value={advanced} onChange={event => { setAdvanced(event.target.value); invalidateReview() }} />
</FramePanel>
</Frame>}
<div className="flex flex-wrap items-center gap-2">
{advanced === null ? <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => setAdvanced(json(draft))}>
{write ? "Редактировать JSON" : "Показать JSON"}
</Button> : <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
setDraft(change().configuration)
setAdvanced(null)
})}>К форме</Button>}
</div>
</TabsContent>
<TabsContent value="routes" className="grid min-w-0 gap-3">
{selected && !dirty && live && write && <IxExits segment={selected} nodes={peers} backendUrl={backendUrl} busy={busy}
error={error} save={input => perform(() => stageTransit(input))} />}
{settingsProps && <ConfigurationFields {...settingsProps} section="routes" />}
{!!selected?.appliedRevision && <>
<div className="flex flex-wrap gap-2">
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(observe)}>
<RefreshCwIcon aria-hidden />Обновить состояние
</Button>
</div>
{busy && observations === null && <Skeleton className="h-28 w-full" role="status" aria-label="Загрузка маршрутов" />}
{observations?.map(site => <RouteGrid key={site.serverId} observation={site} nodes={nodes} />)}
</>}
</TabsContent>
<TabsContent value="linux" className="grid min-w-0 gap-3">
{selected ? <IxClientBonds key={selected.id + ":" + selected.appliedRevision} segmentId={selected.id} segments={segments}
backendUrl={backendUrl} nodes={peers} readOnly={!write || busy || dirty} live={live} download={download}>
{(bondAction, catalog, renderGroups, manualGroup) => <IxLinuxClients segment={selected} nodes={peers} backendUrl={backendUrl}
bondAction={bondAction} catalog={catalog} renderGroups={renderGroups} manualGroup={manualGroup}
applied={linuxBindings} busy={busy} error={error} readOnly={!live || !write || dirty}
save={input => perform(() => stageClient(input))} revoke={binding => void perform(() => stageClient(binding))}
refresh={() => void perform(loadLinuxBindings)} view={(binding, transportOnly) => void perform(() => exportLinux(binding, transportOnly))}
copyImport={binding => void perform(() => copyLinuxImport(binding))}
inspect={binding => void perform(() => inspectLinux(binding))} />}
</IxClientBonds>
: <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />}
{linuxPath && <Frame spacing="sm">
<FrameHeader>
<FrameTitle>Маршруты клиента · {linuxPath.name ?? linuxPath.interfaceName}</FrameTitle>
<FrameDescription>{linuxPath.policy ?? "Только сети IX"} · {new Date(linuxPath.observedAt).toLocaleString("ru-RU")}</FrameDescription>
</FrameHeader>
<FramePanel className="grid gap-2 text-sm">
<p className="text-muted-foreground">Чтение FIB CHR. Доставку пакетов проверяют с Linux-клиента.</p>
{linuxPath.routes.length ? <ul className="grid gap-2">{linuxPath.routes.map((route, index) => <li key={index}>
<code>{route.prefix}</code> · {route.immediateGateway || route.gateway || "—"} · {route.active ? "активен" : "неактивен"}
</li>)}</ul> : <p>Подходящих маршрутов сейчас нет.</p>}
</FramePanel>
</Frame>}
{linux && <Frame spacing="sm">
<FrameHeader>
<FrameTitle>Конфигурация Linux · {linux.interfaceName}</FrameTitle>
<FrameDescription>Ревизия {linux.revision} · {nodeLabel(nodes, linux.serverId)}</FrameDescription>
</FrameHeader>
<FramePanel className="grid min-w-0 gap-3">
<p className="text-sm text-muted-foreground">{linux.transportOnly
? "Подготовьте туннель на VPS с указанным именем интерфейса. Маршруты назначит ix-client после включения группы."
: linux.kind === "wireguard"
? linux.managedWireguard ? "Готовый файл с ключом доступен пользователю с правом управления сетью."
: "Подставьте приватный ключ Linux. После установки проверьте, куда направляются трафик и соединение управления."
: linux.policy && write ? "Скачайте оба файла в одну папку на VPS. Скрипт установит профиль strongSwan и поднимет GRE. SSH по внешнему IPv4 VPS останется прямым."
: "Для подключения нужен индивидуальный PSK, выданный оператором."}</p>
{(!linux.policy || linux.kind === "wireguard") && <pre className="max-h-64 min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.template}</pre>}
<Button type="button" variant="outline" size="sm" className="w-fit" onClick={() => download(linux.filename, linux.template)}>
Скачать {linux.managedWireguard ? "шаблон" : linux.filename}
</Button>
{linux.setup && <>
{linux.policy && write ? <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{
"sudo apt install charon-systemd strongswan-swanctl\nsudo systemctl start strongswan\nsudo sh ./" +
linux.filename.replace(/\.conf$/, "-setup.sh")
}</pre> : <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre>}
<Button type="button" variant="outline" size="sm" className="w-fit"
onClick={() => download(linux.filename.replace(/\.conf$/, "-setup.sh"), "#!/bin/sh\nset -eu\n" + linux.setup + "\n")}>Скачать скрипт GRE</Button>
</>}
{linux.bgp && <p className="wrap-anywhere text-sm text-muted-foreground">
BGP · ASN Linux {linux.bgp.localAs} · ASN IX {linux.bgp.remoteAs} · сосед {linux.bgp.neighbor}
{linux.bgp.advertisedPrefixes.length > 0 && <> · анонсы Linux {linux.bgp.advertisedPrefixes.join(", ")}</>}
</p>}
</FramePanel>
</Frame>}
</TabsContent>
</Tabs>}
<Dialog open={!!review} onOpenChange={open => { if (!open) closeReview() }}>
<DialogContent showCloseButton={!busy} className="max-h-[85dvh] overflow-y-auto sm:max-w-xl">
<DialogHeader>
<DialogTitle>Подтвердите сохранение</DialogTitle>
<DialogDescription>{review} · ревизия {selected?.revision}. После подтверждения изменения вступят в силу на узлах IX.</DialogDescription>
</DialogHeader>
{reviewError ? <Alert variant="destructive"><AlertTitle>Не удалось подтвердить состояние IX</AlertTitle>
<AlertDescription>{reviewError}</AlertDescription></Alert>
: plan ? <>
<p className="text-sm font-medium">{plan.changes.length ? "Операций RouterOS: " + plan.changes.length : "RouterOS уже настроена. Будет отмечена применённая ревизия."}</p>
<RouterOsChanges changes={plan.changes} nodes={peers} />
</> : <p role="status" className="text-sm text-muted-foreground">{busy ? "Проверяем конфигурацию на узлах…" : "Обновите сравнение перед сохранением."}</p>}
<DialogFooter>
<Button type="button" variant="outline" disabled={busy} onClick={closeReview}>Отмена</Button>
{reviewError && selected && <Button type="button" variant="outline" disabled={busy}
onClick={() => void perform(() => prepare(selected, true))}>Сверить и продолжить</Button>}
{plan ? <Button type="button" disabled={busy || !canPlan} onClick={() => void perform(apply)}>Подтвердить</Button>
: reviewError && selected && <Button type="button" disabled={busy} onClick={() => void perform(() => prepare(selected))}>Повторить проверку</Button>}
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</div>
</ServerRailLayout>
}
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -35,7 +35,7 @@ interface BackendServer {
id: number id: number
name: string name: string
host: string host: string
type?: "jump-host" | "exit-node" | "home-router" type?: import("@mmapp/contracts/servers").ServerType
site: string site: string
country: string country: string
asn: string asn: string
@@ -329,11 +329,11 @@ function RouteSheet({
) )
} }
function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" }) { function TypeChip({ type }: { type: import("@mmapp/contracts/servers").ServerType }) {
return ( return (
<Badge size="xs" className="shrink-0 text-foreground" <Badge size="xs" className="shrink-0 text-foreground"
variant={type === "home-router" ? "success-light" : type === "jump-host" ? "primary-light" : "info-light"}> variant={type === "home-router" ? "success-light" : type === "jump-host" ? "primary-light" : "info-light"}>
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : "EN"} {type === "jump-host" ? "JH" : type === "home-router" ? "HR" : type === "ix-node" ? "IX" : "EN"}
</Badge> </Badge>
) )
} }
+27 -12
View File
@@ -38,6 +38,8 @@ import { cn } from "@/lib/utils"
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid" import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
import { DataPageCard } from "@/components/data-page-card" import { DataPageCard } from "@/components/data-page-card"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { ButtonGroup } from "@/components/ui/button-group"
import { Field, FieldTitle } from "@/components/ui/field"
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
import { import {
Sheet, SheetContent, SheetHeader, SheetTitle, Sheet, SheetContent, SheetHeader, SheetTitle,
@@ -591,6 +593,7 @@ function ServersPageContent() {
"jump-host": serverList.filter(s => s.type === "jump-host").length, "jump-host": serverList.filter(s => s.type === "jump-host").length,
"exit-node": serverList.filter(s => s.type === "exit-node").length, "exit-node": serverList.filter(s => s.type === "exit-node").length,
"home-router":serverList.filter(s => s.type === "home-router").length, "home-router":serverList.filter(s => s.type === "home-router").length,
"ix-node": serverList.filter(s => s.type === "ix-node").length,
online: serverList.filter(s => s.status === "online").length, online: serverList.filter(s => s.status === "online").length,
}), [serverList]) }), [serverList])
@@ -599,6 +602,7 @@ function ServersPageContent() {
{ value: "jump-host", label: "JumpHost" }, { value: "jump-host", label: "JumpHost" },
{ value: "exit-node", label: "Exit Node" }, { value: "exit-node", label: "Exit Node" },
{ value: "home-router", label: "Home Router" }, { value: "home-router", label: "Home Router" },
{ value: "ix-node", label: "IX Node" },
] ]
const isHomeRouter = form.type === "home-router" const isHomeRouter = form.type === "home-router"
@@ -770,18 +774,29 @@ function ServersPageContent() {
value={form.name} onChange={e => set("name", e.target.value)} /> value={form.name} onChange={e => set("name", e.target.value)} />
</FormField> </FormField>
<FormField label="Тип узла" required> <Field>
<SegmentedControl <FieldTitle id="server-node-type-label">Тип узла <span aria-hidden className="text-destructive">*</span></FieldTitle>
className="max-w-full flex-wrap" <ButtonGroup aria-labelledby="server-node-type-label" className="max-w-full">
value={form.type} {([
onChange={v => set("type", v)} ["home-router", "Home Router"],
options={[ ["jump-host", "JumpHost"],
{ value: "home-router", label: "Home Router" }, ["exit-node", "Exit Node"],
{ value: "jump-host", label: "JumpHost" }, ["ix-node", "IX Node"],
{ value: "exit-node", label: "Exit Node" }, ] as const).map(([value, label]) => (
]} <Button
/> key={value}
</FormField> type="button"
variant={form.type === value ? "default" : "outline"}
size="sm"
aria-pressed={form.type === value}
className="h-auto min-h-7 min-w-0 flex-auto shrink whitespace-normal py-1"
onClick={() => set("type", value)}
>
{label}
</Button>
))}
</ButtonGroup>
</Field>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<FormField label="Площадка" required hint="MSK, SPB, FRA…"> <FormField label="Площадка" required hint="MSK, SPB, FRA…">
+202 -168
View File
@@ -1,17 +1,22 @@
"use client" "use client"
import { Suspense, useCallback, useEffect, useMemo, useState } from "react" import { Suspense, useCallback, useEffect, useMemo, useState, type ReactNode } from "react"
import { useSearchParams } from "next/navigation" import { useSearchParams } from "next/navigation"
import { import {
ActivityIcon, ActivityIcon,
ChartColumnIcon,
DatabaseIcon, DatabaseIcon,
GaugeIcon, GaugeIcon,
GlobeIcon,
ServerIcon, ServerIcon,
UsersIcon, UsersIcon,
} from "lucide-react" } from "lucide-react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { PageHeader } from "@/components/page-header" import { PageHeader } from "@/components/page-header"
import { PageTitle } from "@/components/page-title"
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid" import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
import { CapacityGrid, type CapacityItem } from "@/components/reui-kit/ops-blocks"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { DataPageCard } from "@/components/data-page-card" import { DataPageCard } from "@/components/data-page-card"
import { DataPageToolbar } from "@/components/data-page-toolbar" import { DataPageToolbar } from "@/components/data-page-toolbar"
import { SegmentedControl } from "@/components/form-kit" import { SegmentedControl } from "@/components/form-kit"
@@ -35,6 +40,7 @@ import {
} from "@/lib/statistics-dims" } from "@/lib/statistics-dims"
import { statisticsContextError, STATISTICS_CONTEXT_KEYS } from "@/lib/statistics-context" import { statisticsContextError, STATISTICS_CONTEXT_KEYS } from "@/lib/statistics-context"
import { readStatisticsRange } from "@/lib/statistics-range" import { readStatisticsRange } from "@/lib/statistics-range"
import { demoStatistics, demoStatisticsPivot } from "@/lib/statistics-demo"
import { useDataSource } from "@/lib/data-source" import { useDataSource } from "@/lib/data-source"
import { fmtBps, formatBytes } from "@/lib/fmt-rate" import { fmtBps, formatBytes } from "@/lib/fmt-rate"
import { import {
@@ -102,8 +108,13 @@ function readDim(sp: URLSearchParams): StatisticsSliceKind {
return t && isStatisticsSliceKind(t) ? t : "users" return t && isStatisticsSliceKind(t) ? t : "users"
} }
function readView(sp: URLSearchParams): "explore" | "pivot" { type StatisticsView = "overview" | "explore" | "pivot"
return sp.get("view") === "pivot" ? "pivot" : "explore"
/** Вкладка макета v3: Обзор, Срезы (explore) или Сводная (pivot); старые ссылки с разрезом открывают Срезы. */
function readView(sp: URLSearchParams): StatisticsView {
const v = sp.get("view")
if (v === "pivot" || v === "explore" || v === "overview") return v
return sp.has("dim") || sp.has("tab") || SLICE_KEYS.some((key) => sp.has(key)) ? "explore" : "overview"
} }
function readPlanes(sp: URLSearchParams): "unique" | "all" { function readPlanes(sp: URLSearchParams): "unique" | "all" {
@@ -241,7 +252,9 @@ function StatisticsPageInner() {
const pivotCol = useMemo(() => readPivotDim(searchParams, "pivotCol", "service"), [searchParams]) const pivotCol = useMemo(() => readPivotDim(searchParams, "pivotCol", "service"), [searchParams])
const [retry, setRetry] = useState(0) const [retry, setRetry] = useState(0)
const requestKey = JSON.stringify({ backendUrl, isLive, range, slices, view, pivotRow, pivotCol, planes, retry, rangeError, paramsError }) // Обзор и Срезы читают один и тот же куб — смена этих вкладок не перезапрашивает данные.
const pivotView = view === "pivot"
const requestKey = JSON.stringify({ backendUrl, isLive, range, slices, pivotView, pivotRow, pivotCol, planes, retry, rangeError, paramsError })
const [result, setResult] = useState<{ const [result, setResult] = useState<{
key: string; data: StatisticsDto; pivot: StatisticsPivotDto; error: string | null key: string; data: StatisticsDto; pivot: StatisticsPivotDto; error: string | null
} | null>(null) } | null>(null)
@@ -249,7 +262,9 @@ function StatisticsPageInner() {
const loading = isLive && !rangeError && !paramsError && current === null const loading = isLive && !rangeError && !paramsError && current === null
const error = rangeError ?? paramsError ?? current?.error ?? null const error = rangeError ?? paramsError ?? current?.error ?? null
const dataReady = isLive && current !== null && !error const dataReady = isLive && current !== null && !error
const pivot = dataReady ? current.pivot : EMPTY_PIVOT // Демо-режим без API: показываем демо-куб, чтобы раздел выглядел как с данными.
const demo = useMemo(() => (isLive || rangeError ? null : demoStatistics(range.from, range.to, planes)), [isLive, rangeError, range, planes])
const pivot = dataReady ? current.pivot : demo && !paramsError ? demoStatisticsPivot(pivotRow, pivotCol) : EMPTY_PIVOT
const updateParams = useCallback( const updateParams = useCallback(
(patch: Record<string, string | undefined>) => { (patch: Record<string, string | undefined>) => {
@@ -295,7 +310,7 @@ function StatisticsPageInner() {
const dto = await getStatistics(backendUrl, query) const dto = await getStatistics(backendUrl, query)
if (cancelled) return if (cancelled) return
let matrix = EMPTY_PIVOT let matrix = EMPTY_PIVOT
if (view === "pivot" && pivotRow !== pivotCol) { if (pivotView && pivotRow !== pivotCol) {
matrix = await getStatisticsPivot(backendUrl, { matrix = await getStatisticsPivot(backendUrl, {
...query, ...query,
row: pivotRow, row: pivotRow,
@@ -313,11 +328,11 @@ function StatisticsPageInner() {
return () => { return () => {
cancelled = true cancelled = true
} }
}, [backendUrl, isLive, prefsHydrated, range, slices, view, pivotRow, pivotCol, planes, requestKey, rangeError, paramsError]) }, [backendUrl, isLive, prefsHydrated, range, slices, pivotView, pivotRow, pivotCol, planes, requestKey, rangeError, paramsError])
const viewData = dataReady ? current.data : EMPTY const viewData = dataReady ? current.data : demo && !paramsError ? demo : EMPTY
const sliced = hasAnySlice(slices) const sliced = hasAnySlice(slices)
const emptyCube = !isLive || (!loading && viewData.kpis.bytes === 0 && viewData.interfaces.length === 0) const emptyCube = !loading && viewData.kpis.bytes === 0 && viewData.interfaces.length === 0
function handleRowClick(kind: StatisticsSliceKind, row: StatisticsBreakdownRow) { function handleRowClick(kind: StatisticsSliceKind, row: StatisticsBreakdownRow) {
if (kind === "users" && row.id === STATISTICS_UNBOUND_USER_ID) return if (kind === "users" && row.id === STATISTICS_UNBOUND_USER_ID) return
@@ -348,175 +363,194 @@ function StatisticsPageInner() {
: sliced : sliced
? `${STATISTICS_DIMS.filter((d) => !hiddenKinds(slices).has(d.id)).length} разрезов` ? `${STATISTICS_DIMS.filter((d) => !hiddenKinds(slices).has(d.id)).length} разрезов`
: `${rowsForKind(viewData, dim).length} строк` : `${rowsForKind(viewData, dim).length} строк`
const hasContext = STATISTICS_CONTEXT_KEYS.some((key) => searchParams.has(key))
const resetContext = () => updateParams(Object.fromEntries(STATISTICS_CONTEXT_KEYS.map((key) => [key, undefined])))
const scope = planes === "all" ? "Все плоскости" : "GRE/WG клиентов, без hops"
const bytesOf = (rows: StatisticsBreakdownRow[]) => rows.reduce((total, row) => total + row.bytes, 0)
const shareOf = (bytes: number) => (kpis.bytes > 0 ? Math.min(1, bytes / kpis.bytes) : 0)
const bytesItem = (id: string, title: string, caption: string, bytes: number, icon: ReactNode): CapacityItem => {
const [valueText, ...unit] = formatBytes(bytes).split(" ")
return { id, title, caption, value: bytes, total: kpis.bytes, ratio: shareOf(bytes), tone: shareOf(bytes) >= 0.999 ? "wn" : "ok", icon, valueText, unit: unit.join(" ") }
}
const planesControl = (
<SegmentedControl
value={planes}
onChange={(next) => updateParams({ planes: next === "all" ? "all" : undefined })}
options={[
{ value: "all", label: "Все плоскости" },
{ value: "unique", label: "GRE/WG клиентов" },
]}
/>
)
const cubeState = isLive && !dataReady ? (
<div role="status" className="p-6 text-sm text-muted-foreground">{loading ? "Загрузка статистики…" : rangeError || paramsError ? "Исправьте параметры отчёта для загрузки статистики." : "Статистика недоступна. Повторите загрузку."}</div>
) : emptyCube ? (
<EmptyState
title="Нет данных куба"
description="За выбранный период нет IPFIX-фактов. Куб заполняется с момента деплоя, без бэкфилла за год."
/>
) : null
const sliceChips = (
<SliceChips
chips={chips}
onRemove={(key) => {
const next = { ...slices }
delete next[key as keyof CubeSlices]
setSlices(next)
}}
/>
)
const filters = <StatisticsFilters key={JSON.stringify(slices)} slices={slices} onApply={setSlices} />
const tabTrigger = "h-auto flex-none px-3 py-2.5 after:bottom-[-1px]"
return ( return (
<div className="flex h-full flex-col"> <div className="flex h-full flex-col">
<PageHeader <PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Статистика" }]} />
crumbs={[{ label: "Обзор", href: "/dashboard" }, { label: "Статистика" }]}
actions={rangeError ? <Button type="button" variant="outline" onClick={() => setRange(rangeForPreset("7d"))}>Выбрать последние 7 дней</Button> : <PeriodSelector range={range} onChange={setRange} />}
/>
<div className="flex flex-1 flex-col gap-4 overflow-y-auto px-4 py-4 md:gap-6 md:px-6 md:py-5"> <div className="flex flex-1 flex-col gap-6 overflow-y-auto px-4 pt-5 pb-10 md:px-7 md:pt-6">
{!isLive ? ( <PageTitle
<Alert> icon={<ChartColumnIcon />}
<AlertTitle>Живые данные выключены</AlertTitle> title="Статистика"
<AlertDescription> description="Куб NetFlow: измерения, срезы и период · уникальный объём без дублей"
Куб статистики строится из IPFIX. Переключитесь на живой источник, чтобы увидеть отчёт. actions={
</AlertDescription> <>
</Alert> {rangeError ? <Button type="button" variant="outline" onClick={() => setRange(rangeForPreset("7d"))}>Выбрать последние 7 дней</Button> : <PeriodSelector range={range} onChange={setRange} />}
) : null} <Button type="button" variant="outline" onClick={resetContext} disabled={!hasContext}>Сбросить параметры отчёта</Button>
</>
}
/>
{error ? ( <div className="flex flex-col gap-5">
<Alert variant="destructive" role="alert"> {!isLive ? (
<AlertTitle>{rangeError ? "Некорректный период" : paramsError ? "Параметры отчёта требуют внимания" : "Ошибка загрузки"}</AlertTitle> <Alert variant="warning">
<AlertDescription>{error}{!rangeError && !paramsError && <Button type="button" variant="outline" size="sm" onClick={() => setRetry(n => n + 1)}>Повторить загрузку</Button>}{paramsError && <Button type="button" variant="outline" size="sm" onClick={() => updateParams(Object.fromEntries(STATISTICS_CONTEXT_KEYS.map(key => [key, undefined])))}>Сбросить параметры отчёта</Button>}</AlertDescription> <AlertTitle>Живые данные выключены</AlertTitle>
</Alert> <AlertDescription>
) : null} Показан демо-куб. Статистика строится из IPFIX — переключитесь на живой источник, чтобы увидеть свой отчёт.
</AlertDescription>
</Alert>
) : null}
{!slices.serverId && dataReady && !emptyCube ? ( {error ? (
<Alert> <Alert variant={paramsError ? "warning" : "destructive"} role="alert">
<AlertTitle>Уникальный объём</AlertTitle> <AlertTitle>{rangeError ? "Некорректный период" : paramsError ? "Параметры отчёта требуют внимания" : "Ошибка загрузки"}</AlertTitle>
<AlertDescription> <AlertDescription>{error}{!rangeError && !paramsError && <Button type="button" variant="outline" size="sm" onClick={() => setRetry(n => n + 1)}>Повторить загрузку</Button>}</AlertDescription>
Объём — трафик клиентов на GRE/WG, без повторного учёта JH↔EN и WAN. </Alert>
</AlertDescription> ) : null}
</Alert>
) : null}
{(dataReady || loading) && <KpiStatGrid {(dataReady || loading || (demo && !paramsError)) && <KpiStatGrid
aria-label="Сводка трафика" aria-label="Сводка трафика"
isLoading={loading} isLoading={loading}
skeletonCount={5} skeletonCount={4}
items={[ items={[
{ {
id: "bytes", id: "bytes",
label: "Объём", label: planes === "all" ? "Объём" : "Уникальный объём",
value: formatBytes(kpis.bytes), value: formatBytes(kpis.bytes),
hint: "GRE/WG клиентов, без hops", hint: slices.serverId ? (kpis.ifaces ? `${kpis.ifaces} iface` : undefined) : planes === "all" ? "WAN и дубли в списке" : "без WAN и overlay",
icon: <DatabaseIcon />, icon: <DatabaseIcon />,
iconClassName: "text-muted-foreground", iconClassName: planes === "all" ? "text-muted-foreground" : "text-success",
}, },
{ {
id: "packets", id: "packets",
label: "Пакеты", label: "Пакеты",
value: kpis.packets.toLocaleString("ru-RU"), value: kpis.packets.toLocaleString("ru-RU"),
hint: kpis.topService ? `топ: ${kpis.topService}` : undefined, hint: kpis.topService ? `топ: ${kpis.topService}` : undefined,
icon: <ActivityIcon />, icon: <ActivityIcon />,
iconClassName: "text-muted-foreground", iconClassName: "text-muted-foreground",
}, },
{ {
id: "bps", id: "bps",
label: "Средний bitrate", label: "Средний bitrate",
value: fmtBps(kpis.avgBps), value: fmtBps(kpis.avgBps),
icon: <GaugeIcon />, icon: <GaugeIcon />,
iconClassName: "text-muted-foreground", iconClassName: "text-muted-foreground",
}, },
{ {
id: "users", id: "users",
label: "Пользователи", label: "Пользователи",
value: String(kpis.users), value: String(kpis.users),
icon: <UsersIcon />, hint: `Серверы: ${kpis.servers}`,
iconClassName: "text-muted-foreground", icon: <UsersIcon />,
}, iconClassName: "text-muted-foreground",
{ },
id: "servers", ]}
label: "Серверы", />}
value: String(kpis.servers),
hint: slices.serverId
? (kpis.ifaces ? `${kpis.ifaces} iface` : undefined)
: planes === "all"
? "WAN и дубли в списке"
: "без WAN и overlay",
icon: <ServerIcon />,
iconClassName: "text-muted-foreground",
},
]}
/>}
{dataReady && <StatisticsVolumeChart series={viewData.series} grain={viewData.grain} />} <Tabs value={view} onValueChange={(next) => updateParams({ view: String(next) })} className="gap-5">
<TabsList variant="line" className="h-auto w-full justify-start gap-1 overflow-x-auto border-b p-0">
<TabsTrigger value="overview" className={tabTrigger}>Обзор</TabsTrigger>
<TabsTrigger value="pivot" className={tabTrigger}>Сводная (куб)</TabsTrigger>
<TabsTrigger value="explore" className={tabTrigger}>Срезы</TabsTrigger>
</TabsList>
<DataPageCard> <TabsContent value="overview" className="flex flex-col gap-5">
<DataPageToolbar {cubeState ?? (
leading={ <>
<div className="flex flex-wrap items-center gap-3"> <StatisticsVolumeChart series={viewData.series} grain={viewData.grain} scope={scope} actions={planesControl} />
<SegmentedControl <CapacityGrid
value={view} label="Доли объёма"
onChange={(next) => updateParams({ view: next === "pivot" ? "pivot" : "explore" })} items={[
options={[ bytesItem("users", "Пользователи", "GRE/WG клиентов, без hops", bytesOf(viewData.users), <UsersIcon />),
{ value: "explore", label: "Разрез" }, bytesItem("servers", "Серверы", planes === "all" ? "WAN и дубли в списке" : "без WAN и overlay", bytesOf(viewData.servers), <ServerIcon />),
{ value: "pivot", label: "Сводка" }, bytesItem("countries", "Страны", "Топ-10", bytesOf([...viewData.countries].sort((a, b) => b.bytes - a.bytes).slice(0, 10)), <GlobeIcon />),
]} ]}
/>
<SegmentedControl
value={planes}
onChange={(next) => updateParams({ planes: next === "all" ? "all" : undefined })}
options={[
{ value: "unique", label: "Уникальный" },
{ value: "all", label: "Все плоскости" },
]}
/>
{view === "explore" && !sliced ? (
<DimensionSelect
label="Критерий"
value={dim}
onChange={(next) => updateParams({ dim: next, tab: undefined })}
/> />
) : null} </>
{view === "pivot" ? ( )}
<> </TabsContent>
<PivotDimSelect
label="Строки" <TabsContent value="pivot">
value={pivotRow} <DataPageCard>
exclude={pivotCol} <DataPageToolbar
onChange={(next) => updateParams({ pivotRow: next })} leading={
/> <div className="flex flex-wrap items-center gap-3">
<PivotDimSelect {planesControl}
label="Колонки" <PivotDimSelect label="Строки" value={pivotRow} exclude={pivotCol} onChange={(next) => updateParams({ pivotRow: next })} />
value={pivotCol} <PivotDimSelect label="Колонки" value={pivotCol} exclude={pivotRow} onChange={(next) => updateParams({ pivotCol: next })} />
exclude={pivotRow} </div>
onChange={(next) => updateParams({ pivotCol: next })} }
/> filterControl={filters}
</> countLabel={dataReady ? countLabel : undefined}
) : null} />
</div> {sliceChips}
} {cubeState ?? <StatisticsPivotGrid data={pivot} onCellClick={handlePivotCell} isLoading={loading} />}
filterControl={<StatisticsFilters key={JSON.stringify(slices)} slices={slices} onApply={setSlices} />} </DataPageCard>
countLabel={dataReady ? countLabel : undefined} </TabsContent>
/>
<SliceChips <TabsContent value="explore">
chips={chips} <DataPageCard>
onRemove={(key) => { <DataPageToolbar
const next = { ...slices } leading={
delete next[key as keyof CubeSlices] <div className="flex flex-wrap items-center gap-3">
setSlices(next) {planesControl}
}} {!sliced ? <DimensionSelect label="Критерий" value={dim} onChange={(next) => updateParams({ dim: next, tab: undefined })} /> : null}
/> </div>
{isLive && !dataReady ? ( }
<div role="status" className="p-6 text-sm text-muted-foreground">{loading ? "Загрузка статистики…" : rangeError || paramsError ? "Исправьте параметры отчёта для загрузки статистики." : "Статистика недоступна. Повторите загрузку."}</div> filterControl={filters}
) : emptyCube ? ( countLabel={dataReady ? countLabel : undefined}
<EmptyState />
title="Нет данных куба" {sliceChips}
description="За выбранный период нет IPFIX-фактов. Куб заполняется с момента деплоя, без бэкфилла за год." {cubeState ?? (sliced ? (
/> <BreakdownDashboard
) : view === "pivot" ? ( data={viewData}
<StatisticsPivotGrid data={isLive ? pivot : EMPTY_PIVOT} onCellClick={handlePivotCell} isLoading={loading} /> hidden={hiddenKinds(slices)}
) : sliced ? ( selectedIdFor={(kind) => selectedIdForKind(kind, slices)}
<BreakdownDashboard onRowClick={handleRowClick}
data={viewData} isLoading={loading}
hidden={hiddenKinds(slices)} />
selectedIdFor={(kind) => selectedIdForKind(kind, slices)} ) : (
onRowClick={handleRowClick} <StatisticsBreakdownDataGrid
isLoading={loading} rows={rowsForKind(viewData, dim)}
/> kind={dim}
) : ( selectedId={selectedIdForKind(dim, slices)}
<StatisticsBreakdownDataGrid onRowClick={(row) => handleRowClick(dim, row)}
rows={rowsForKind(viewData, dim)} isLoading={loading}
kind={dim} />
selectedId={selectedIdForKind(dim, slices)} ))}
onRowClick={(row) => handleRowClick(dim, row)} </DataPageCard>
isLoading={loading} </TabsContent>
/> </Tabs>
)} </div>
</DataPageCard>
</div> </div>
</div> </div>
) )
+235 -179
View File
@@ -2,12 +2,14 @@
import { useState, useMemo, useEffect, type ReactNode } from "react" import { useState, useMemo, useEffect, type ReactNode } from "react"
import { Alert, AlertTitle, AlertDescription } from "@/components/reui/alert" import { Alert, AlertTitle, AlertDescription } from "@/components/reui/alert"
import { peakOfCombinedTraffic, projectTrafficObservations, type TrafficObservationMeta } from "@/lib/traffic-observations" import { peakOfCombinedTraffic, projectTrafficObservations, sumObservedTraffic, type TrafficObservationMeta } from "@/lib/traffic-observations"
import { projectTrafficBindingStatus } from "@/lib/traffic-binding-status" import { projectTrafficBindingStatus } from "@/lib/traffic-binding-status"
import { TrafficObservationStatus } from "@/components/traffic/traffic-observation-status" import { TrafficObservationStatus } from "@/components/traffic/traffic-observation-status"
import { TrafficDataTime } from "@/components/traffic/traffic-data-time" import { TrafficDataTime } from "@/components/traffic/traffic-data-time"
import { PageHeader } from "@/components/page-header" import { PageHeader } from "@/components/page-header"
import { Frame, FramePanel } from "@/components/reui/frame" import { PageTitle } from "@/components/page-title"
import { FramePanel } from "@/components/reui/frame"
import { SectionFrame, ToneBadge, type Tone } from "@/components/reui-kit/ops-blocks"
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid" import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
import { TrafficMiniChart } from "@/components/reui-kit/traffic-mini-chart" import { TrafficMiniChart } from "@/components/reui-kit/traffic-mini-chart"
import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart" import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart"
@@ -16,7 +18,7 @@ import { Sparkline } from "@/components/sparkline"
import { StatusDot } from "@/components/status-dot" import { StatusDot } from "@/components/status-dot"
import { Flag } from "@/components/flag" import { Flag } from "@/components/flag"
import { import {
RefreshCwIcon, TrendingUpIcon, TrendingDownIcon, RefreshCwIcon, TrendingUpIcon, ChartPieIcon,
ArrowUpIcon, ArrowDownIcon, ActivityIcon, UsersIcon, CableIcon, ServerIcon, SearchIcon, GitBranchIcon, PlusIcon, ArrowUpIcon, ArrowDownIcon, ActivityIcon, UsersIcon, CableIcon, ServerIcon, SearchIcon, GitBranchIcon, PlusIcon,
} from "lucide-react" } from "lucide-react"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
@@ -341,17 +343,6 @@ type SortDir = "asc" | "desc"
// ─── shared sub-components ──────────────────────────────────────────────────── // ─── shared sub-components ────────────────────────────────────────────────────
function StatChip({ icon, label, value }: { icon: ReactNode; label: string; value: string }) {
return (
<div className="flex items-center gap-2">
<div className="flex items-center justify-center size-7 rounded-md bg-muted shrink-0">{icon}</div>
<div className="leading-tight min-w-0 break-words">
<p className="text-xs text-muted-foreground">{label}</p>
<p className="text-sm font-semibold tabular-nums">{value}</p>
</div>
</div>
)
}
// ─── left-panel entity cards ────────────────────────────────────────────────── // ─── left-panel entity cards ──────────────────────────────────────────────────
@@ -368,22 +359,22 @@ function ServerCard({ s, selected, onClick }: { s: ServerTraffic; selected: bool
<StatusDot status={s.status} /> <StatusDot status={s.status} />
<span className="text-xs font-medium truncate">{s.name}</span> <span className="text-xs font-medium truncate">{s.name}</span>
</div> </div>
<span className="text-[10px] font-mono text-muted-foreground shrink-0 flex items-center gap-1"> <span className="text-xs font-mono text-muted-foreground shrink-0 flex items-center gap-1">
<Flag code={s.country} />{s.site} <Flag code={s.country} />{s.site}
</span> </span>
</div> </div>
<TrafficMiniChart rx={s.rxSeries} tx={s.txSeries} /> <TrafficMiniChart rx={s.rxSeries} tx={s.txSeries} />
<div className="flex justify-between mt-2 gap-2"> <div className="flex justify-between mt-2 gap-2">
<div className="flex items-center gap-1 text-[11px]"> <div className="flex items-center gap-1 text-xs">
<ArrowDownIcon className="size-3 text-emerald-500" /> <ArrowDownIcon className="size-3 text-emerald-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(s.rxNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(s.rxNow)}</span>
</div> </div>
<div className="flex items-center gap-1 text-[11px]"> <div className="flex items-center gap-1 text-xs">
<ArrowUpIcon className="size-3 text-blue-500" /> <ArrowUpIcon className="size-3 text-blue-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(s.txNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(s.txNow)}</span>
</div> </div>
{s.boundIfaces.length > 0 && ( {s.boundIfaces.length > 0 && (
<div className="flex items-center gap-0.5 text-[10px] text-muted-foreground"> <div className="flex items-center gap-0.5 text-xs text-muted-foreground">
<CableIcon className="size-3" />{s.boundIfaces.length} <CableIcon className="size-3" />{s.boundIfaces.length}
</div> </div>
)} )}
@@ -407,10 +398,10 @@ function UserCard({ u, selected, onClick }: { u: UserTraffic; selected: boolean;
</div> </div>
<div className="min-w-0"> <div className="min-w-0">
<p className="text-xs font-medium truncate">{u.login}</p> <p className="text-xs font-medium truncate">{u.login}</p>
<p className="text-[10px] text-muted-foreground truncate">{u.displayName}</p> <p className="text-xs text-muted-foreground truncate">{u.displayName}</p>
</div> </div>
</div> </div>
<div className="flex items-center gap-0.5 text-[10px] text-muted-foreground shrink-0"> <div className="flex items-center gap-0.5 text-xs text-muted-foreground shrink-0">
<CableIcon className="size-3" />{u.interfaces.length} <CableIcon className="size-3" />{u.interfaces.length}
</div> </div>
</div> </div>
@@ -418,18 +409,18 @@ function UserCard({ u, selected, onClick }: { u: UserTraffic; selected: boolean;
<> <>
<TrafficMiniChart rx={u.rxSeries} tx={u.txSeries} /> <TrafficMiniChart rx={u.rxSeries} tx={u.txSeries} />
<div className="flex justify-between mt-2 gap-2"> <div className="flex justify-between mt-2 gap-2">
<div className="flex items-center gap-1 text-[11px]"> <div className="flex items-center gap-1 text-xs">
<ArrowDownIcon className="size-3 text-emerald-500" /> <ArrowDownIcon className="size-3 text-emerald-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(u.rxNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(u.rxNow)}</span>
</div> </div>
<div className="flex items-center gap-1 text-[11px]"> <div className="flex items-center gap-1 text-xs">
<ArrowUpIcon className="size-3 text-blue-500" /> <ArrowUpIcon className="size-3 text-blue-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(u.txNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(u.txNow)}</span>
</div> </div>
</div> </div>
</> </>
) : ( ) : (
<p className="text-[10px] text-muted-foreground">Нет привязанных интерфейсов</p> <p className="text-xs text-muted-foreground">Нет привязанных интерфейсов</p>
)} )}
</button> </button>
) )
@@ -447,20 +438,20 @@ function IfaceCard({ c, selected, onClick }: { c: BoundIfaceTraffic; selected: b
<StatusDot status={c.status} /> <StatusDot status={c.status} />
<div className="min-w-0"> <div className="min-w-0">
<p className="text-xs font-mono font-medium truncate">{boundIfaceLabel(c)}</p> <p className="text-xs font-mono font-medium truncate">{boundIfaceLabel(c)}</p>
<p className="text-[10px] text-muted-foreground truncate">{c.userLogin}</p> <p className="text-xs text-muted-foreground truncate">{c.userLogin}</p>
</div> </div>
</div> </div>
<span className="text-[10px] font-mono text-muted-foreground shrink-0 flex items-center gap-1"> <span className="text-xs font-mono text-muted-foreground shrink-0 flex items-center gap-1">
<Flag code={c.serverCountry} />{c.serverSite} <Flag code={c.serverCountry} />{c.serverSite}
</span> </span>
</div> </div>
<TrafficMiniChart rx={c.rxSeries} tx={c.txSeries} /> <TrafficMiniChart rx={c.rxSeries} tx={c.txSeries} />
<div className="flex justify-between mt-2 gap-2"> <div className="flex justify-between mt-2 gap-2">
<div className="flex items-center gap-1 text-[11px]"> <div className="flex items-center gap-1 text-xs">
<ArrowDownIcon className="size-3 text-emerald-500" /> <ArrowDownIcon className="size-3 text-emerald-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(c.rxNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(c.rxNow)}</span>
</div> </div>
<div className="flex items-center gap-1 text-[11px]"> <div className="flex items-center gap-1 text-xs">
<ArrowUpIcon className="size-3 text-blue-500" /> <ArrowUpIcon className="size-3 text-blue-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(c.txNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(c.txNow)}</span>
</div> </div>
@@ -487,12 +478,12 @@ function IfaceRow({ c, showServer = false }: { c: BoundIfaceTraffic; showServer?
<span className="text-xs font-mono font-semibold break-all">{boundIfaceLabel(c)}</span> <span className="text-xs font-mono font-semibold break-all">{boundIfaceLabel(c)}</span>
<Badge variant={TYPE_VARIANT[c.interfaceType]} size="sm">{IFACE_TYPE_LABEL[c.interfaceType]}</Badge> <Badge variant={TYPE_VARIANT[c.interfaceType]} size="sm">{IFACE_TYPE_LABEL[c.interfaceType]}</Badge>
{showServer && ( {showServer && (
<span className="inline-flex items-center gap-1 text-[10px] font-mono text-muted-foreground bg-muted px-1.5 py-0.5 rounded"> <span className="inline-flex items-center gap-1 text-xs font-mono text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
<Flag code={c.serverCountry} />{c.serverSite} <Flag code={c.serverCountry} />{c.serverSite}
</span> </span>
)} )}
</div> </div>
<p className="text-[10px] text-muted-foreground truncate mt-0.5">{c.comment || c.userLogin}</p> <p className="text-xs text-muted-foreground truncate mt-0.5">{c.comment || c.userLogin}</p>
</div> </div>
<div className="shrink-0 text-right leading-tight"> <div className="shrink-0 text-right leading-tight">
<div className="flex items-center gap-1 justify-end text-xs font-mono font-medium text-emerald-600 dark:text-emerald-400"> <div className="flex items-center gap-1 justify-end text-xs font-mono font-medium text-emerald-600 dark:text-emerald-400">
@@ -502,12 +493,12 @@ function IfaceRow({ c, showServer = false }: { c: BoundIfaceTraffic; showServer?
<ArrowUpIcon className="size-3" />{fmtRate(c.txNow)} <ArrowUpIcon className="size-3" />{fmtRate(c.txNow)}
</div> </div>
</div> </div>
<div className="shrink-0 text-right leading-tight text-[10px] text-muted-foreground w-[72px]"> <div className="shrink-0 text-right leading-tight text-xs text-muted-foreground w-[72px]">
<p className="tabular-nums">{fmtGiB(c.rxTotal)}</p> <p className="tabular-nums">{fmtGiB(c.rxTotal)}</p>
<p className="tabular-nums">{fmtGiB(c.txTotal)}</p> <p className="tabular-nums">{fmtGiB(c.txTotal)}</p>
</div> </div>
<span className={cn( <span className={cn(
"shrink-0 text-[10px] px-1.5 py-0.5 rounded-full font-medium tabular-nums", "shrink-0 text-xs px-1.5 py-0.5 rounded-full font-medium tabular-nums",
c.status === "online" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground", c.status === "online" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground",
)}> )}>
{c.status === "online" ? "Работает" : c.status === "unknown" ? "Нет данных" : "Неактивен"} {c.status === "online" ? "Работает" : c.status === "unknown" ? "Нет данных" : "Неактивен"}
@@ -516,6 +507,61 @@ function IfaceRow({ c, showServer = false }: { c: BoundIfaceTraffic; showServer?
) )
} }
/** Интерфейсы выбранного сервера таблицей (блок «Интерфейсы сервера» макета v3). */
function ServerIfacesFrame({ server }: { server: ServerTraffic }) {
const cols = "grid-cols-[minmax(170px,1.6fr)_minmax(90px,1fr)_110px_100px_100px_150px]"
return (
<SectionFrame title="Интерфейсы сервера" description={`${server.name} · трафик по каждому интерфейсу`} icon={<CableIcon />} panelClassName="overflow-x-auto">
<div className="min-w-[740px]">
<div aria-hidden="true" className={cn("bg-muted/55 text-muted-foreground grid h-10 items-center gap-x-3 border-b px-3.5 text-xs font-medium", cols)}>
<span>Интерфейс</span><span>Сервер</span><span>Статус</span><span>RX</span><span>TX</span><span>Учтено</span>
</div>
{server.boundIfaces.map((c) => (
<div key={c.id} className={cn("grid min-h-[52px] items-center gap-x-3 border-b px-3.5 last:border-b-0", cols, c.status === "offline" && "opacity-55")}>
<span className="flex min-w-0 items-center gap-2 py-2">
<StatusDot status={c.status} />
<span className="min-w-0">
<span className="block truncate font-mono text-[13px] font-medium">{boundIfaceLabel(c)}</span>
<span className="text-muted-foreground block truncate font-mono text-xs">{IFACE_TYPE_LABEL[c.interfaceType]} · {c.comment || c.userLogin}</span>
</span>
</span>
<span className="truncate font-mono text-xs">{server.name}</span>
<span><ToneBadge tone={c.status === "online" ? "ok" : c.status === "unknown" ? "mu" : "er"}>{c.status === "online" ? "Работает" : c.status === "unknown" ? "Нет данных" : "Неактивен"}</ToneBadge></span>
<span className="font-mono text-xs tabular-nums">{fmtRate(c.rxNow)}</span>
<span className="font-mono text-xs tabular-nums">{fmtRate(c.txNow)}</span>
<span className="text-muted-foreground font-mono text-xs tabular-nums">{fmtGiB(c.rxTotal)} / {fmtGiB(c.txTotal)}</span>
</div>
))}
</div>
</SectionFrame>
)
}
/** Доля RX по серверам с данными (блок rbl макета v3). */
function RxShareFrame({ servers }: { servers: ServerTraffic[] }) {
const rows = servers.filter((s) => typeof s.rxNow === "number" && s.rxNow > 0).sort((a, b) => (b.rxNow ?? 0) - (a.rxNow ?? 0)).slice(0, 5)
const total = rows.reduce((sum, s) => sum + (s.rxNow ?? 0), 0)
if (!rows.length || total <= 0) return null
const max = rows[0].rxNow ?? 1
const colors = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--muted-foreground)"]
return (
<SectionFrame title="Доля RX" description="сейчас · по серверам с данными" icon={<ChartPieIcon />} panelClassName="flex flex-col gap-1.5 p-2.5">
{rows.map((s, i) => (
<div key={s.id} className="flex min-w-0 items-center gap-2">
<span className="bg-muted/70 relative h-7 min-w-0 flex-1 overflow-hidden rounded-full">
<i className="absolute inset-y-0 left-0 rounded-full opacity-40" style={{ width: `${Math.round(((s.rxNow ?? 0) / max) * 100)}%`, background: colors[i] }} />
<span className="relative flex h-full items-center gap-1.5 truncate px-2.5 text-xs font-medium">
<span aria-hidden="true" className="size-1.5 shrink-0 rounded-full" style={{ background: colors[i] }} />{s.name}
</span>
</span>
<span className="min-w-[72px] text-right font-mono text-xs">{fmtRate(s.rxNow)}</span>
<span className="text-muted-foreground min-w-11 text-right font-mono text-xs">{Math.round(((s.rxNow ?? 0) / total) * 100)}%</span>
</div>
))}
</SectionFrame>
)
}
function BoundIfacesList({ clients, showServer = false }: { clients: BoundIfaceTraffic[]; showServer?: boolean }) { function BoundIfacesList({ clients, showServer = false }: { clients: BoundIfaceTraffic[]; showServer?: boolean }) {
if (clients.length === 0) if (clients.length === 0)
return <p className="text-xs text-muted-foreground py-1">Нет привязанных интерфейсов</p> return <p className="text-xs text-muted-foreground py-1">Нет привязанных интерфейсов</p>
@@ -528,24 +574,46 @@ function BoundIfacesList({ clients, showServer = false }: { clients: BoundIfaceT
// ─── detail panel helpers ───────────────────────────────────────────────────── // ─── detail panel helpers ─────────────────────────────────────────────────────
function DetailHeader({ range, setRange, children }: { function DetailHeader({ range, setRange, children, status }: {
range: Range; setRange: (r: Range) => void; children: ReactNode range: Range; setRange: (r: Range) => void; children: ReactNode; status?: ReactNode
}) { }) {
return ( return (
<div className="flex flex-wrap items-start justify-between mb-3 gap-3"> <div className="mb-3 flex flex-wrap items-center gap-3">
<div className="flex items-center gap-2 flex-wrap min-w-0">{children}</div> <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">{children}</div>
<div className="flex flex-wrap gap-1"> {status}
<div className="bg-muted inline-flex h-9 items-center gap-0.5 rounded-lg p-[3px]">
{TRAFFIC_RANGE_KEYS.map((r) => ( {TRAFFIC_RANGE_KEYS.map((r) => (
<Button key={r} type="button" aria-pressed={range === r} size="sm" variant={r === range ? "default" : "ghost"} <button key={r} type="button" aria-pressed={range === r} onClick={() => setRange(r)}
className="h-7 px-2 text-xs" onClick={() => setRange(r)}> className={cn("text-muted-foreground hover:text-foreground h-[30px] rounded-md px-2.5 text-[13px] font-medium transition-colors", range === r && "bg-background text-foreground shadow-sm")}>
{TRAFFIC_RANGE_LABELS[r]} {TRAFFIC_RANGE_LABELS[r]}
</Button> </button>
))} ))}
</div> </div>
</div> </div>
) )
} }
const SERVER_STATUS: Record<ServerTraffic["status"], { tone: Tone; label: string }> = {
online: { tone: "ok", label: "Онлайн" },
degraded: { tone: "wn", label: "Ухудшение" },
offline: { tone: "er", label: "Оффлайн" },
}
/** Текущие и пиковые скорости двумя колонками (блок kv макета v3). */
function KvStats({ label, items }: { label: string; items: Array<{ id: string; label: string; value: string; hint?: string }> }) {
return (
<div role="group" aria-label={label} className="mt-3 grid grid-cols-2 gap-x-3.5 gap-y-3 border-t pt-3.5">
{items.map((item) => (
<div key={item.id} className="min-w-0">
<small className="text-muted-foreground block text-xs">{item.label}</small>
<b className="font-mono text-[13px] font-medium tabular-nums">{item.value}</b>
{item.hint ? <span className="text-muted-foreground ml-2 text-xs">{item.hint}</span> : null}
</div>
))}
</div>
)
}
function OfflinePlaceholder({ text = "Нет данных — объект недоступен" }: { text?: string }) { function OfflinePlaceholder({ text = "Нет данных — объект недоступен" }: { text?: string }) {
return ( return (
<div className="flex items-center justify-center h-[220px] text-muted-foreground/40"> <div className="flex items-center justify-center h-[220px] text-muted-foreground/40">
@@ -596,63 +664,24 @@ function ServerDetail({
const txNow = liveTx ?? sel.txNow const txNow = liveTx ?? sel.txNow
return ( return (
<> <>
<DetailHeader range={range} setRange={setRange}> <DetailHeader range={range} setRange={setRange} status={<ToneBadge tone={SERVER_STATUS[sel.status].tone} size="lg">{SERVER_STATUS[sel.status].label}</ToneBadge>}>
<StatusDot status={sel.status} /> <div className="min-w-0">
<h2 className="text-base font-semibold break-all">{sel.name}</h2> <h2 className="text-sm font-semibold break-all">{sel.name}</h2>
<span className="text-xs font-mono bg-muted px-1.5 py-0.5 rounded flex items-center gap-1"> <p className="text-muted-foreground flex items-center gap-1 text-[0.78rem]"><Flag code={sel.country} />{sel.site}</p>
<Flag code={sel.country} />{sel.site} </div>
</span>
</DetailHeader> </DetailHeader>
<TrafficObservationStatus observations={sel.observations} unknown={sel.rxNow == null || sel.txNow == null} /> <TrafficObservationStatus observations={sel.observations} unknown={sel.rxNow == null || sel.txNow == null} />
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} /> <TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
<div className="mt-4 pt-4 border-t"> <KvStats
<KpiStatGrid label="Скорость выбранного сервера"
aria-label="Скорость выбранного сервера" items={[
items={[ { id: "rx-now", label: "RX сейчас", value: fmtRate(rxNow), hint: liveHint },
{ { id: "tx-now", label: "TX сейчас", value: fmtRate(txNow), hint: liveHint },
id: "rx-now", { id: "rx-peak", label: "Пик RX", value: fmtRate(sel.rxPeak) },
label: "RX", { id: "tx-peak", label: "Пик TX", value: fmtRate(sel.txPeak) },
value: fmtRate(rxNow), ]}
hint: liveHint, />
icon: <ArrowDownIcon className="size-4" />,
iconClassName: "text-success",
},
{
id: "tx-now",
label: "TX",
value: fmtRate(txNow),
hint: liveHint,
icon: <ArrowUpIcon className="size-4" />,
iconClassName: "text-info",
},
{
id: "rx-peak",
label: "Пик RX",
value: fmtRate(sel.rxPeak),
icon: <TrendingUpIcon className="size-4" />,
iconClassName: "text-warning",
},
{
id: "tx-peak",
label: "Пик TX",
value: fmtRate(sel.txPeak),
icon: <TrendingDownIcon className="size-4" />,
iconClassName: "text-warning",
},
]}
/>
</div>
<TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} /> <TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} />
{sel.boundIfaces.length > 0 && (
<div className="mt-4 pt-4 border-t">
<h3 className="text-sm font-semibold mb-2 flex items-center gap-2">
<CableIcon className="size-4 text-muted-foreground" />
Привязанные интерфейсы
<span className="text-xs text-muted-foreground font-normal">({sel.boundIfaces.length})</span>
</h3>
<BoundIfacesList clients={sel.boundIfaces} />
</div>
)}
</> </>
) )
} }
@@ -666,7 +695,7 @@ function UserDetail({ sel, range, setRange }: { sel: UserTraffic; range: Range;
<UsersIcon className="size-4 text-muted-foreground" /> <UsersIcon className="size-4 text-muted-foreground" />
</div> </div>
<div className="leading-tight"> <div className="leading-tight">
<h2 className="text-base font-semibold break-all">{sel.login}</h2> <h2 className="text-sm font-semibold break-all">{sel.login}</h2>
<p className="text-xs text-muted-foreground break-all">{sel.displayName} · {sel.role}</p> <p className="text-xs text-muted-foreground break-all">{sel.displayName} · {sel.role}</p>
</div> </div>
</DetailHeader> </DetailHeader>
@@ -675,12 +704,15 @@ function UserDetail({ sel, range, setRange }: { sel: UserTraffic; range: Range;
) : ( ) : (
<> <>
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} /> <TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-4 pt-4 border-t"> <KvStats
<StatChip icon={<ArrowDownIcon className="size-3.5 text-emerald-500" />} label="RX" value={fmtRate(sel.rxNow)} /> label="Скорость выбранного клиента"
<StatChip icon={<ArrowUpIcon className="size-3.5 text-blue-500" />} label="TX" value={fmtRate(sel.txNow)} /> items={[
<StatChip icon={<TrendingUpIcon className="size-3.5 text-amber-500" />} label="Пик RX" value={fmtRate(sel.rxPeak)} /> { id: "rx", label: "RX сейчас", value: fmtRate(sel.rxNow) },
<StatChip icon={<CableIcon className="size-3.5 text-purple-500" />} label="Интерфейсы" value={`${sel.interfaces.length}`} /> { id: "tx", label: "TX сейчас", value: fmtRate(sel.txNow) },
</div> { id: "rx-peak", label: "Пик RX", value: fmtRate(sel.rxPeak) },
{ id: "ifaces", label: "Интерфейсы", value: String(sel.interfaces.length) },
]}
/>
<TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} /> <TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} />
<div className="mt-4 pt-4 border-t"> <div className="mt-4 pt-4 border-t">
<h3 className="text-sm font-semibold mb-2 flex items-center gap-2"> <h3 className="text-sm font-semibold mb-2 flex items-center gap-2">
@@ -702,7 +734,7 @@ function IfaceDetail({ sel, range, setRange }: { sel: BoundIfaceTraffic; range:
<DetailHeader range={range} setRange={setRange}> <DetailHeader range={range} setRange={setRange}>
<StatusDot status={sel.status} /> <StatusDot status={sel.status} />
<div className="leading-tight min-w-0"> <div className="leading-tight min-w-0">
<h2 className="text-base font-mono font-semibold break-all">{boundIfaceLabel(sel)}</h2> <h2 className="text-sm font-mono font-semibold break-all">{boundIfaceLabel(sel)}</h2>
<p className="text-xs text-muted-foreground truncate">{sel.comment || sel.userLogin}</p> <p className="text-xs text-muted-foreground truncate">{sel.comment || sel.userLogin}</p>
</div> </div>
<Badge variant={TYPE_VARIANT[sel.interfaceType]} size="sm">{IFACE_TYPE_LABEL[sel.interfaceType]}</Badge> <Badge variant={TYPE_VARIANT[sel.interfaceType]} size="sm">{IFACE_TYPE_LABEL[sel.interfaceType]}</Badge>
@@ -711,12 +743,15 @@ function IfaceDetail({ sel, range, setRange }: { sel: BoundIfaceTraffic; range:
</span> </span>
</DetailHeader> </DetailHeader>
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} /> <TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-4 pt-4 border-t"> <KvStats
<StatChip icon={<ArrowDownIcon className="size-3.5 text-emerald-500" />} label="RX" value={fmtRate(sel.rxNow)} /> label="Скорость выбранного интерфейса"
<StatChip icon={<ArrowUpIcon className="size-3.5 text-blue-500" />} label="TX" value={fmtRate(sel.txNow)} /> items={[
<StatChip icon={<TrendingUpIcon className="size-3.5 text-amber-500" />} label="Пик RX" value={fmtRate(sel.rxPeak)} /> { id: "rx", label: "RX сейчас", value: fmtRate(sel.rxNow) },
<StatChip icon={<TrendingUpIcon className="size-3.5 text-amber-500" />} label="Пик TX" value={fmtRate(sel.txPeak)} /> { id: "tx", label: "TX сейчас", value: fmtRate(sel.txNow) },
</div> { id: "rx-peak", label: "Пик RX", value: fmtRate(sel.rxPeak) },
{ id: "tx-peak", label: "Пик TX", value: fmtRate(sel.txPeak) },
]}
/>
<TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} /> <TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} />
<div className="mt-4 pt-4 border-t grid grid-cols-2 sm:grid-cols-3 gap-4"> <div className="mt-4 pt-4 border-t grid grid-cols-2 sm:grid-cols-3 gap-4">
<div> <div>
@@ -1143,11 +1178,17 @@ export default function TrafficPage() {
: effectiveMode === "ifaces" : effectiveMode === "ifaces"
? activeBoundIfaces ? activeBoundIfaces
: activeServerTraffic : activeServerTraffic
const totalRx = kpiSource.length && kpiSource.every(s => s.rxNow !== null) ? kpiSource.reduce((a, s) => a + (s.rxNow ?? 0), 0) : null const allowPartialKpi = effectiveMode === "ifaces"
const totalTx = kpiSource.length && kpiSource.every(s => s.txNow !== null) ? kpiSource.reduce((a, s) => a + (s.txNow ?? 0), 0) : null const totalRx = sumObservedTraffic(kpiSource.map(s => s.rxNow))
const totalTx = sumObservedTraffic(kpiSource.map(s => s.txNow))
const exactPeaks = effectiveMode === "servers" && trafficReady ? trafficState?.peaks : undefined const exactPeaks = effectiveMode === "servers" && trafficReady ? trafficState?.peaks : undefined
const peakRx = exactPeaks ? exactPeaks.rx : peakOfCombinedTraffic(kpiSource.map(s => s.rxSeries)) const peakRx = exactPeaks ? { value: exactPeaks.rx, observed: kpiSource.length } : peakOfCombinedTraffic(kpiSource.map(s => s.rxSeries), allowPartialKpi)
const peakTx = exactPeaks ? exactPeaks.tx : peakOfCombinedTraffic(kpiSource.map(s => s.txSeries)) const peakTx = exactPeaks ? { value: exactPeaks.tx, observed: kpiSource.length } : peakOfCombinedTraffic(kpiSource.map(s => s.txSeries), allowPartialKpi)
const coverageHint = (observed: number) => allowPartialKpi && observed > 0 && observed < kpiSource.length
? `${observed} из ${kpiSource.length} интерф.`
: undefined
const totalHint = effectiveMode === "servers" ? "Интерфейсы и туннели" : undefined
const peakHint = exactPeaks ? "По общим замерам" : "По интервалам графика"
const visibleSortFields = SORT_FIELDS.filter(s => !s.modesOnly || s.modesOnly.includes(effectiveMode)) const visibleSortFields = SORT_FIELDS.filter(s => !s.modesOnly || s.modesOnly.includes(effectiveMode))
const ingestLine = flowIngestLine(collectorStatus) const ingestLine = flowIngestLine(collectorStatus)
@@ -1192,77 +1233,88 @@ export default function TrafficPage() {
{ {
id: "rx", id: "rx",
label: "Сумма RX", label: "Сумма RX",
value: fmtRate(totalRx), value: fmtRate(allowPartialKpi || totalRx.observed === kpiSource.length ? totalRx.value : null),
hint: effectiveMode === "servers" ? "Интерфейсы и туннели" : undefined, hint: coverageHint(totalRx.observed) ?? totalHint,
icon: <ArrowDownIcon className="size-4" />, icon: <ArrowDownIcon className="size-4" />,
iconClassName: "text-success", iconClassName: "text-success",
}, },
{ {
id: "tx", id: "tx",
label: "Сумма TX", label: "Сумма TX",
value: fmtRate(totalTx), value: fmtRate(allowPartialKpi || totalTx.observed === kpiSource.length ? totalTx.value : null),
hint: effectiveMode === "servers" ? "Интерфейсы и туннели" : undefined, hint: coverageHint(totalTx.observed) ?? totalHint,
icon: <ArrowUpIcon className="size-4" />, icon: <ArrowUpIcon className="size-4" />,
iconClassName: "text-info", iconClassName: "text-info",
}, },
{ {
id: "peak-rx", id: "peak-rx",
label: "Пик суммы RX", label: "Пик суммы RX",
value: fmtRate(peakRx), value: fmtRate(peakRx.value),
hint: exactPeaks ? "По общим замерам" : "По интервалам графика", hint: coverageHint(peakRx.observed) ?? peakHint,
icon: <TrendingUpIcon className="size-4" />, icon: <TrendingUpIcon className="size-4" />,
iconClassName: "text-warning", iconClassName: "text-warning",
}, },
{ {
id: "peak-tx", id: "peak-tx",
label: "Пик суммы TX", label: "Пик суммы TX",
value: fmtRate(peakTx), value: fmtRate(peakTx.value),
hint: exactPeaks ? "По общим замерам" : "По интервалам графика", hint: coverageHint(peakTx.observed) ?? peakHint,
icon: <TrendingUpIcon className="size-4" />, icon: <TrendingUpIcon className="size-4" />,
iconClassName: "text-warning", iconClassName: "text-warning",
}, },
] ]
const modeCount: Record<GroupMode, number | null> = {
servers: activeServerTraffic.length,
users: (isLive ? liveUsers : userTraffic).length,
ifaces: (isLive ? liveBoundIfaces : boundIfaces).length,
flows: null,
}
const refreshBusy = isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)
const listTitle = effectiveMode === "servers" ? "Серверы" : effectiveMode === "users" ? "Клиенты" : "Интерфейсы"
const listShown = effectiveMode === "servers" ? sortedServers.length : effectiveMode === "users" ? sortedUsers.length : sortedIfaces.length
return ( return (
<div className="flex flex-col h-full"> <div className="flex flex-col h-full">
<PageHeader <PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Трафик" }]} />
crumbs={[{ label: "Обзор" }, { label: "Трафик" }]}
actions={
<>
<Button
variant="outline"
size="sm"
onClick={() => {
if (effectiveMode === "flows") setFlowRetry(value => value + 1)
else setTrafficRetry(value => value + 1)
}}
disabled={isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)}
>
<RefreshCwIcon className={cn("size-4", isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading) && "animate-spin")} />Обновить
</Button>
</>
}
/>
{/* ── mode tab bar ── */} <div className="flex-1 min-w-0 overflow-y-auto px-4 pt-5 pb-10 md:px-7 md:pt-6">
<div className="border-b bg-background shrink-0"> <div className="flex flex-col gap-6">
<div role="group" aria-label="Разделы трафика" className="flex items-center overflow-x-auto px-3 sm:px-6"> <PageTitle
{GROUP_MODES.map(({ mode, icon, label }) => ( icon={<ActivityIcon />}
<button type="button" aria-pressed={effectiveMode === mode} key={mode} onClick={() => handleModeChange(mode)} title="Трафик"
className={cn( description="Счётчики интерфейсов и потоки IPFIX по серверам, клиентам и интерфейсам"
"flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors -mb-px", actions={
effectiveMode === mode <>
? "border-primary text-foreground" <Button type="button" variant="outline" onClick={() => { handleModeChange("flows"); setRange("30d") }}>Месячный отчёт</Button>
: "border-transparent text-muted-foreground hover:text-foreground hover:border-border", <Button
)}> type="button"
{icon}{label} onClick={() => {
</button> if (effectiveMode === "flows") setFlowRetry(value => value + 1)
))} else setTrafficRetry(value => value + 1)
</div> }}
</div> disabled={refreshBusy}
>
<div className="flex-1 min-w-0 overflow-y-auto p-3 sm:p-6"> <RefreshCwIcon className={cn("size-4", refreshBusy && "animate-spin")} />Обновить
</Button>
</>
}
/>
<div className="flex flex-col gap-5"> <div className="flex flex-col gap-5">
<div role="group" aria-label="Разделы трафика" className="flex items-center gap-1 overflow-x-auto border-b">
{GROUP_MODES.map(({ mode, label }) => (
<button type="button" aria-pressed={effectiveMode === mode} key={mode} onClick={() => handleModeChange(mode)}
className={cn(
"text-muted-foreground hover:text-foreground -mb-px inline-flex items-center gap-1.5 border-b-2 border-transparent px-3 py-2.5 text-sm font-medium whitespace-nowrap transition-colors",
effectiveMode === mode && "border-foreground text-foreground",
)}>
{label}
{modeCount[mode] != null ? (
<em aria-hidden="true" className={cn("bg-muted text-muted-foreground inline-flex h-5 min-w-5 items-center justify-center rounded-md px-1.5 font-mono text-xs not-italic", effectiveMode === mode && "bg-foreground/12 text-foreground")}>{modeCount[mode]}</em>
) : null}
</button>
))}
</div>
{!(effectiveMode === "flows" && range === "30d") && (!isLive || !(effectiveMode === "flows" ? liveError : trafficError)) && <KpiStatGrid {!(effectiveMode === "flows" && range === "30d") && (!isLive || !(effectiveMode === "flows" ? liveError : trafficError)) && <KpiStatGrid
isLoading={isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)} isLoading={isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)}
aria-label="Сводка трафика" aria-label="Сводка трафика"
@@ -1291,15 +1343,15 @@ export default function TrafficPage() {
{flowError} {flowError}
</div> </div>
)} )}
<div className="grid min-w-0 grid-cols-1 xl:grid-cols-[300px_minmax(0,1fr)] gap-5 items-start"> <div className="grid min-w-0 grid-cols-1 xl:grid-cols-[300px_minmax(0,1fr)] gap-4 items-start">
<div className="flex flex-col gap-3"> <SectionFrame title={flowScope === "users" ? "Клиенты" : "Экспортёры"} description="Потоки IPFIX · сортировка и поиск" panelClassName="flex flex-col gap-3 p-2.5">
<div role="group" aria-label="Источник потоков" className="flex gap-1"> <div role="group" aria-label="Источник потоков" className="flex gap-1">
<button <button
type="button" type="button"
aria-pressed={flowScope === "servers"} aria-pressed={flowScope === "servers"}
onClick={() => { setFlowScope("servers"); setFlowIface("__all__") }} onClick={() => { setFlowScope("servers"); setFlowIface("__all__") }}
className={cn( className={cn(
"text-[10px] px-2 py-0.5 rounded border transition-colors", "text-xs px-2 py-0.5 rounded border transition-colors",
flowScope === "servers" flowScope === "servers"
? "border-primary bg-primary/10 text-primary font-medium" ? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground", : "border-border text-muted-foreground hover:text-foreground",
@@ -1312,7 +1364,7 @@ export default function TrafficPage() {
aria-pressed={flowScope === "users"} aria-pressed={flowScope === "users"}
onClick={() => { setFlowScope("users"); setFlowIface("__all__"); if (range === "30d") setRange("1h") }} onClick={() => { setFlowScope("users"); setFlowIface("__all__"); if (range === "30d") setRange("1h") }}
className={cn( className={cn(
"text-[10px] px-2 py-0.5 rounded border transition-colors", "text-xs px-2 py-0.5 rounded border transition-colors",
flowScope === "users" flowScope === "users"
? "border-primary bg-primary/10 text-primary font-medium" ? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground", : "border-border text-muted-foreground hover:text-foreground",
@@ -1332,14 +1384,14 @@ export default function TrafficPage() {
/> />
</div> </div>
<div className={cn("flex gap-1 flex-wrap", range === "30d" && "hidden")}> <div className={cn("flex gap-1 flex-wrap", range === "30d" && "hidden")}>
<span className="text-[10px] text-muted-foreground self-center mr-0.5">Сортировка:</span> <span className="text-xs text-muted-foreground self-center mr-0.5">Сортировка:</span>
{visibleSortFields.map(({ field, label }) => ( {visibleSortFields.map(({ field, label }) => (
<button <button
key={field} key={field}
type="button" type="button"
onClick={() => toggleSort(field)} onClick={() => toggleSort(field)}
className={cn( className={cn(
"text-[10px] px-2 py-0.5 rounded border transition-colors", "text-xs px-2 py-0.5 rounded border transition-colors",
sortField === field sortField === field
? "border-primary bg-primary/10 text-primary font-medium" ? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground", : "border-border text-muted-foreground hover:text-foreground",
@@ -1365,8 +1417,8 @@ export default function TrafficPage() {
</p> </p>
) : null} ) : null}
</div> </div>
</div> </SectionFrame>
<Frame dense className="w-full min-w-0 flex flex-col"> <SectionFrame bare className="w-full min-w-0">
<FramePanel className="flex-1 min-w-0 p-3 sm:p-5"> <FramePanel className="flex-1 min-w-0 p-3 sm:p-5">
{analyticsLoading && <p role="status">Загрузка аналитики…</p>} {analyticsLoading && <p role="status">Загрузка аналитики…</p>}
{currentAnalytics?.error && <Alert variant="destructive" role="alert"><AlertTitle>Аналитика недоступна</AlertTitle><AlertDescription>{currentAnalytics.error}<Button size="sm" variant="outline" onClick={() => setAnalyticsRetry(value => value + 1)}>Повторить аналитику</Button></AlertDescription></Alert>} {currentAnalytics?.error && <Alert variant="destructive" role="alert"><AlertTitle>Аналитика недоступна</AlertTitle><AlertDescription>{currentAnalytics.error}<Button size="sm" variant="outline" onClick={() => setAnalyticsRetry(value => value + 1)}>Повторить аналитику</Button></AlertDescription></Alert>}
@@ -1393,7 +1445,7 @@ export default function TrafficPage() {
emptyHint={analyticsLoading ? "Загрузка аналитики…" : currentAnalytics?.error ? "Не удалось получить данные выбранного среза" : flowEmptyHint(collectorStatus)} emptyHint={analyticsLoading ? "Загрузка аналитики…" : currentAnalytics?.error ? "Не удалось получить данные выбранного среза" : flowEmptyHint(collectorStatus)}
/> />
</FramePanel> </FramePanel>
</Frame> </SectionFrame>
</div> </div>
<FlowOverlaySheet <FlowOverlaySheet
open={overlayOpen} open={overlayOpen}
@@ -1404,9 +1456,10 @@ export default function TrafficPage() {
/> />
</div> </div>
) : ( ) : (
<div className="grid min-w-0 grid-cols-1 xl:grid-cols-[300px_minmax(0,1fr)] gap-5 items-start"> <div className="grid min-w-0 grid-cols-1 xl:grid-cols-[300px_minmax(0,1fr)] gap-4 items-start">
{/* ── left panel ── */} {/* ── left panel ── */}
<div className="flex flex-col gap-3"> <div className="flex min-w-0 flex-col gap-4">
<SectionFrame title={listTitle} description={`${listShown} из ${modeCount[effectiveMode] ?? listShown} · сортировка и поиск`} panelClassName="flex flex-col gap-3 p-2.5">
{/* search */} {/* search */}
<div className="relative"> <div className="relative">
@@ -1416,20 +1469,17 @@ export default function TrafficPage() {
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
aria-label="Поиск трафика" placeholder="Поиск…" aria-label="Поиск трафика" placeholder="Поиск…"
className="w-full pl-8 pr-3 h-8 text-xs bg-muted/50 border border-border rounded-md outline-none focus:border-primary transition-colors" className="border-input bg-input/30 focus:border-ring h-8 w-full rounded-lg border pr-3 pl-8 text-[13px] outline-none transition-colors"
/> />
</div> </div>
{/* sort controls */} {/* sort controls */}
<div className="flex gap-1 flex-wrap"> <div role="group" aria-label="Сортировка" className="bg-muted inline-flex h-9 w-fit items-center gap-0.5 rounded-lg p-[3px]">
<span className="text-[10px] text-muted-foreground self-center mr-0.5">Сортировка:</span>
{visibleSortFields.map(({ field, label }) => ( {visibleSortFields.map(({ field, label }) => (
<button type="button" aria-pressed={sortField === field} key={field} onClick={() => toggleSort(field)} <button type="button" aria-pressed={sortField === field} key={field} onClick={() => toggleSort(field)}
className={cn( className={cn(
"text-[10px] px-2 py-0.5 rounded border transition-colors", "text-muted-foreground hover:text-foreground h-[30px] rounded-md px-2.5 text-[13px] font-medium transition-colors",
sortField === field sortField === field && "bg-background text-foreground shadow-sm",
? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground",
)}> )}>
{label}{sortField === field ? (sortDir === "desc" ? " ↓" : " ↑") : ""} {label}{sortField === field ? (sortDir === "desc" ? " ↓" : " ↑") : ""}
</button> </button>
@@ -1455,20 +1505,23 @@ export default function TrafficPage() {
<IfaceCard key={c.id} c={c} selected={c.id === selectedId} onClick={() => setSelectedId(c.id)} /> <IfaceCard key={c.id} c={c} selected={c.id === selectedId} onClick={() => setSelectedId(c.id)} />
))} ))}
</div> </div>
</SectionFrame>
{effectiveMode === "servers" ? <RxShareFrame servers={activeServerTraffic} /> : null}
</div> </div>
{/* ── detail panel ── */} {/* ── detail panel ── */}
<Frame dense className="w-full min-w-0 flex flex-col"> <div className="flex min-w-0 flex-col gap-4">
<SectionFrame bare className="w-full min-w-0">
<FramePanel className="flex-1 min-w-0 p-3 sm:p-5"> <FramePanel className="flex-1 min-w-0 p-3 sm:p-5">
{isLive && effectiveMode === "servers" && ( {isLive && effectiveMode === "servers" && (
<div className="mb-3 pb-3 border-b"> <div className="mb-3 pb-3 border-b">
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2 flex-wrap">
<span className="text-[11px] text-muted-foreground mr-1">Интерфейс:</span> <span className="text-xs text-muted-foreground mr-1">Интерфейс:</span>
<button <button
type="button" aria-pressed={hideDisabledIfaces} type="button" aria-pressed={hideDisabledIfaces}
onClick={() => setHideDisabledIfaces((v) => !v)} onClick={() => setHideDisabledIfaces((v) => !v)}
className={cn( className={cn(
"inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-medium transition-all", "inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium transition-all",
hideDisabledIfaces hideDisabledIfaces
? "bg-muted text-foreground border-border" ? "bg-muted text-foreground border-border"
: "text-muted-foreground border-border hover:text-foreground hover:border-foreground/40", : "text-muted-foreground border-border hover:text-foreground hover:border-foreground/40",
@@ -1480,7 +1533,7 @@ export default function TrafficPage() {
type="button" aria-pressed={selectedIface === "__all__"} type="button" aria-pressed={selectedIface === "__all__"}
onClick={() => setSelectedIface("__all__")} onClick={() => setSelectedIface("__all__")}
className={cn( className={cn(
"inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-[10px] font-medium transition-all", "inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-medium transition-all",
selectedIface === "__all__" selectedIface === "__all__"
? "bg-foreground text-background border-foreground" ? "bg-foreground text-background border-foreground"
: "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40", : "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40",
@@ -1496,7 +1549,7 @@ export default function TrafficPage() {
type="button" aria-pressed={active} type="button" aria-pressed={active}
onClick={() => setSelectedIface(iface.name)} onClick={() => setSelectedIface(iface.name)}
className={cn( className={cn(
"inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[10px] font-medium transition-all", "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-xs font-medium transition-all",
active active
? "bg-foreground text-background border-foreground" ? "bg-foreground text-background border-foreground"
: "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40", : "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40",
@@ -1508,7 +1561,7 @@ export default function TrafficPage() {
</button> </button>
) )
})} })}
{detailBusy && <span className="text-[10px] text-muted-foreground ml-2">Загрузка...</span>} {detailBusy && <span className="text-xs text-muted-foreground ml-2">Загрузка...</span>}
</div> </div>
</div> </div>
)} )}
@@ -1544,11 +1597,14 @@ export default function TrafficPage() {
{effectiveMode === "users" && selUser && <UserDetail sel={selUser} range={range} setRange={setRange} />} {effectiveMode === "users" && selUser && <UserDetail sel={selUser} range={range} setRange={setRange} />}
{effectiveMode === "ifaces" && selIface && <IfaceDetail sel={selIface} range={range} setRange={setRange} />} {effectiveMode === "ifaces" && selIface && <IfaceDetail sel={selIface} range={range} setRange={setRange} />}
</FramePanel> </FramePanel>
</Frame> </SectionFrame>
{effectiveMode === "servers" && detailServer && detailServer.boundIfaces.length > 0 ? <ServerIfacesFrame server={detailServer} /> : null}
</div>
</div> </div>
)} )}
</div> </div>
</div>
</div> </div>
</div> </div>
) )
+5 -4
View File
@@ -235,7 +235,7 @@ function probeGroupActionKey(srvId: string, group: { name: string; target: strin
// ── shared components ────────────────────────────────────────────────────────── // ── shared components ──────────────────────────────────────────────────────────
function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" }) { function TypeChip({ type }: { type: import("@mmapp/contracts/servers").ServerType }) {
return ( return (
<span className={cn( <span className={cn(
"inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-bold border shrink-0", "inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-bold border shrink-0",
@@ -245,7 +245,7 @@ function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" })
? "bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20" ? "bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20"
: "bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20", : "bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20",
)}> )}>
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : "EN"} {type === "jump-host" ? "JH" : type === "home-router" ? "HR" : type === "ix-node" ? "IX" : "EN"}
</span> </span>
) )
} }
@@ -666,7 +666,7 @@ interface BackendServer {
id: number id: number
name: string name: string
host: string host: string
type: "jump-host" | "exit-node" | "home-router" type: import("@mmapp/contracts/servers").ServerType
site: string site: string
country: string country: string
enabled: boolean enabled: boolean
@@ -843,7 +843,7 @@ const INIT_RESOURCES: ServerResource[] = mockServers.map(s => {
// ── ResourcesTab ────────────────────────────────────────────────────────────── // ── ResourcesTab ──────────────────────────────────────────────────────────────
type ResTypeFilter = "all" | "jump-host" | "exit-node" | "home-router" type ResTypeFilter = "all" | import("@mmapp/contracts/servers").ServerType
function ResourceWarnings({ rows }: { rows: UptimeResourceRow[] }) { function ResourceWarnings({ rows }: { rows: UptimeResourceRow[] }) {
const [expanded, setExpanded] = useState(false) const [expanded, setExpanded] = useState(false)
@@ -941,6 +941,7 @@ function ResourcesTab({ resources, serversList, liveApi }: { resources: ServerRe
{ value: "jump-host", label: "JumpHost" }, { value: "jump-host", label: "JumpHost" },
{ value: "exit-node", label: "Exit Node" }, { value: "exit-node", label: "Exit Node" },
{ value: "home-router", label: "Home Router" }, { value: "home-router", label: "Home Router" },
{ value: "ix-node", label: "IX Node" },
] ]
return ( return (
@@ -0,0 +1,34 @@
BEGIN;
ALTER TABLE public.servers DROP CONSTRAINT servers_type_check;
ALTER TABLE public.servers ADD CONSTRAINT servers_type_check
CHECK (type IN ('jump-host', 'exit-node', 'home-router', 'ix-node'));
CREATE TABLE public.ix_segments (
id uuid PRIMARY KEY,
name text NOT NULL UNIQUE,
revision integer NOT NULL CHECK (revision > 0),
configuration jsonb NOT NULL CHECK (jsonb_typeof(configuration) = 'object'),
applied_revision integer CHECK (applied_revision > 0 AND applied_revision <= revision),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE public.ix_segment_devices (
segment_id uuid NOT NULL REFERENCES public.ix_segments(id) ON DELETE CASCADE,
server_id bigint NOT NULL REFERENCES public.servers(id) ON DELETE RESTRICT,
PRIMARY KEY (segment_id, server_id)
);
CREATE INDEX ix_segment_devices_server_idx ON public.ix_segment_devices(server_id);
CREATE TABLE public.ix_segment_revisions (
segment_id uuid NOT NULL REFERENCES public.ix_segments(id) ON DELETE CASCADE,
revision integer NOT NULL CHECK (revision > 0),
configuration jsonb NOT NULL CHECK (jsonb_typeof(configuration) = 'object'),
actor_id text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (segment_id, revision)
);
INSERT INTO public.schema_migrations (id) VALUES ('0058_internet_exchange') ON CONFLICT (id) DO NOTHING;
COMMIT;
@@ -0,0 +1,97 @@
BEGIN;
ALTER TABLE public.server_poll_storage_usage
DROP CONSTRAINT server_poll_storage_usage_check2,
DROP CONSTRAINT server_poll_storage_usage_admissions_check,
DROP CONSTRAINT server_poll_storage_rows_charge,
DROP CONSTRAINT server_poll_storage_bytes_charge,
ADD CONSTRAINT server_poll_storage_usage_admissions_check CHECK (admissions >= 0),
ADD CONSTRAINT server_poll_storage_rows_charge CHECK (reserved_rows = admissions * 4019 + compacted_admissions * 2),
ADD CONSTRAINT server_poll_storage_bytes_charge CHECK (reserved_bytes = admissions * 8421376 + compacted_admissions * 32768 + archive_bytes);
CREATE OR REPLACE FUNCTION server_poll_storage_admission_guard() RETURNS trigger LANGUAGE plpgsql SET TimeZone='UTC' SET search_path=pg_catalog,public AS $$
DECLARE retention integer; charged integer; r public.server_poll_archives%ROWTYPE;
BEGIN
PERFORM pg_advisory_xact_lock(hashtextextended('server-poll-storage-v1',0));
IF TG_OP='DELETE' THEN
IF NOT public.server_poll_storage_gc_allowed(OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_executions WHERE receipt_id=OLD.receipt_id)
OR EXISTS(SELECT 1 FROM public.server_poll_intents WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_acks WHERE receipt_id=OLD.receipt_id)
OR EXISTS(SELECT 1 FROM public.server_poll_receipts WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_quarantines WHERE receipt_id=OLD.receipt_id)
OR EXISTS(SELECT 1 FROM public.server_poll_archives WHERE receipt_id=OLD.receipt_id) THEN RAISE EXCEPTION 'poll lifetime or children prevent admission deletion'; END IF;
UPDATE public.server_poll_storage_usage SET admissions=admissions-CASE WHEN OLD.storage_state='full' THEN 1 ELSE 0 END,
compacted_admissions=compacted_admissions-CASE WHEN OLD.storage_state='compacted' THEN 1 ELSE 0 END,
archive_bytes=archive_bytes-COALESCE(OLD.archive_bytes,0),
reserved_rows=reserved_rows-CASE WHEN OLD.storage_state='full' THEN 4019 ELSE 2 END,
reserved_bytes=reserved_bytes-CASE WHEN OLD.storage_state='full' THEN 8421376 ELSE 32768+OLD.archive_bytes END
WHERE scope IN('global','owner:'||OLD.owner_id);
GET DIAGNOSTICS charged=ROW_COUNT; IF charged<>2 THEN RAISE EXCEPTION 'poll quota refund mismatch'; END IF; RETURN OLD;
END IF;
IF TG_OP='UPDATE' THEN
IF OLD.storage_state='compacted' AND NEW.storage_state='compacted'
AND current_setting('mm.poll_retire_receipt',true)=OLD.receipt_id::text
AND (to_jsonb(OLD)-'archive_bytes')=(to_jsonb(NEW)-'archive_bytes') THEN
SELECT * INTO r FROM public.server_poll_archives WHERE receipt_id=OLD.receipt_id AND version=2;
IF NOT FOUND OR r.ciphertext_bytes<>NEW.archive_bytes OR NEW.archive_bytes>OLD.archive_bytes
OR r.execution_id<>OLD.execution_id OR r.connection_id<>OLD.connection_id OR r.owner_id<>OLD.owner_id
THEN RAISE EXCEPTION 'retired poll charge source mismatch'; END IF;
UPDATE public.server_poll_storage_usage
SET archive_bytes=archive_bytes-OLD.archive_bytes+NEW.archive_bytes,
reserved_bytes=reserved_bytes-OLD.archive_bytes+NEW.archive_bytes
WHERE scope IN ('global','owner:'||OLD.owner_id) AND compacted_admissions>=1 AND archive_bytes>=OLD.archive_bytes;
GET DIAGNOSTICS charged=ROW_COUNT;
IF charged<>2 THEN RAISE EXCEPTION 'retired poll charge adjustment mismatch'; END IF;
RETURN NEW;
END IF;
-- This durable one-shot marker is written and ACKed in its OWN transaction
-- before archive construction. A committed/unknown claim never resets and
-- the worker never retries destructive work against an already claimed full
-- source. Claim time is maintenance metadata, not renewed execution activity.
IF OLD.storage_state='full' AND NEW.storage_state='full' AND OLD.compaction_claim IS NULL AND OLD.compaction_claimed_at IS NULL AND OLD.compaction_claim_xid IS NULL
AND NEW.compaction_claim IS NOT NULL AND NEW.compaction_claim_xid IS NULL
AND(to_jsonb(OLD)-ARRAY['compaction_claim','compaction_claimed_at','compaction_claim_xid'])=(to_jsonb(NEW)-ARRAY['compaction_claim','compaction_claimed_at','compaction_claim_xid'])
AND public.server_poll_storage_compact_allowed(OLD.receipt_id)
THEN NEW.compaction_claimed_at:=clock_timestamp(); NEW.compaction_claim_xid:=pg_current_xact_id(); RETURN NEW; END IF;
IF(to_jsonb(OLD)-ARRAY['claim_token','claim_attempted_at','used_rows','used_bytes','storage_state','compact_at','archive_bytes','original_activity_at']) IS DISTINCT FROM
(to_jsonb(NEW)-ARRAY['claim_token','claim_attempted_at','used_rows','used_bytes','storage_state','compact_at','archive_bytes','original_activity_at']) THEN RAISE EXCEPTION 'poll admission identity is immutable'; END IF;
IF OLD.storage_state<>'full' THEN RAISE EXCEPTION 'compacted poll identity cannot reopen or change'; END IF;
IF NEW.storage_state='compacted' THEN
SELECT * INTO r FROM public.server_poll_archives WHERE receipt_id=OLD.receipt_id AND compaction_xid=pg_current_xact_id();
IF NOT FOUND OR NEW.used_rows<>OLD.used_rows OR NEW.used_bytes<>OLD.used_bytes OR NEW.claim_token IS DISTINCT FROM OLD.claim_token
OR NEW.claim_attempted_at IS DISTINCT FROM OLD.claim_attempted_at OR NEW.archive_bytes<>r.ciphertext_bytes OR NEW.original_activity_at<>r.original_activity_at
OR EXISTS(SELECT 1 FROM public.server_poll_executions WHERE receipt_id=OLD.receipt_id)
OR EXISTS(SELECT 1 FROM public.server_poll_intents WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_acks WHERE receipt_id=OLD.receipt_id)
OR EXISTS(SELECT 1 FROM public.server_poll_receipts WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_quarantines WHERE receipt_id=OLD.receipt_id)
THEN RAISE EXCEPTION 'poll compaction requires the complete current-transaction archive'; END IF;
NEW.compact_at:=r.created_at;
UPDATE public.server_poll_storage_usage SET admissions=admissions-1,compacted_admissions=compacted_admissions+1,
archive_bytes=archive_bytes+r.ciphertext_bytes,reserved_rows=reserved_rows-4019+2,reserved_bytes=reserved_bytes-8421376+32768+r.ciphertext_bytes
WHERE scope IN('global','owner:'||OLD.owner_id) AND admissions>=1;
GET DIAGNOSTICS charged=ROW_COUNT; IF charged<>2 THEN RAISE EXCEPTION 'poll compaction charge mismatch'; END IF;
RETURN NEW;
END IF;
IF NEW.compact_at IS NOT NULL OR NEW.archive_bytes IS NOT NULL OR NEW.original_activity_at IS NOT NULL THEN RAISE EXCEPTION 'full poll cannot carry archive metadata'; END IF;
IF OLD.claim_token IS NOT NULL AND NEW.claim_token IS NULL AND OLD.claim_attempted_at IS NULL AND NEW.claim_attempted_at IS NOT NULL
AND NEW.used_rows=OLD.used_rows AND NEW.used_bytes=OLD.used_bytes AND OLD.authority_expires_at>clock_timestamp()
THEN NEW.claim_attempted_at:=clock_timestamp(); RETURN NEW; END IF;
IF OLD.claim_token IS NOT DISTINCT FROM NEW.claim_token AND OLD.claim_attempted_at IS NOT DISTINCT FROM NEW.claim_attempted_at
AND NEW.used_rows=OLD.used_rows+1 AND NEW.used_bytes>OLD.used_bytes THEN RETURN NEW; END IF;
RAISE EXCEPTION 'poll admission cannot refresh, reopen or refund itself';
END IF;
IF NEW.storage_state<>'full' OR NEW.compact_at IS NOT NULL OR NEW.archive_bytes IS NOT NULL OR NEW.original_activity_at IS NOT NULL
OR NEW.compaction_claim IS NOT NULL OR NEW.compaction_claimed_at IS NOT NULL OR NEW.compaction_claim_xid IS NOT NULL
OR NOT public.server_poll_storage_accounting_valid() THEN RAISE EXCEPTION 'new poll requires full reservation and exact ledger'; END IF;
SELECT requests_retention_days INTO retention FROM public.mcp_settings WHERE id=1;
IF retention IS NULL OR retention NOT BETWEEN 1 AND 365 OR NEW.authority_issued_at>clock_timestamp() OR NEW.authority_expires_at<=clock_timestamp()
OR NEW.claim_token IS NULL OR NEW.claim_attempted_at IS NOT NULL OR NEW.used_rows<>0 OR NEW.used_bytes<>0 THEN RAISE EXCEPTION 'new poll admission needs original live authority'; END IF;
IF EXISTS(SELECT 1 FROM public.server_poll_storage_admissions WHERE receipt_id=NEW.receipt_id OR(identity_kind=NEW.identity_kind AND execution_id=NEW.execution_id)) THEN RAISE EXCEPTION 'poll identity already spent'; END IF;
NEW.created_at:=clock_timestamp(); NEW.retention_days:=retention; NEW.safety_ms:=60000;
NEW.gc_not_before:=NEW.authority_expires_at+make_interval(days=>retention)+interval '60 seconds';
INSERT INTO public.server_poll_storage_usage(scope) VALUES('owner:'||NEW.owner_id) ON CONFLICT DO NOTHING;
UPDATE public.server_poll_storage_usage SET admissions=admissions+1,reserved_rows=reserved_rows+4019,reserved_bytes=reserved_bytes+8421376 WHERE scope IN('global','owner:'||NEW.owner_id);
GET DIAGNOSTICS charged=ROW_COUNT; IF charged<>2 THEN RAISE EXCEPTION 'poll admission counters unavailable'; END IF;
RETURN NEW;
END $$;
INSERT INTO public.schema_migrations (id) VALUES ('0059_server_poll_journal_limits') ON CONFLICT (id) DO NOTHING;
COMMIT;
+169 -1
View File
@@ -464,6 +464,69 @@
], ],
"reason": "Общий listRevisions с REST: только метаданные, максимум 50 записей; серверная область и права проверяются до SQL, payload ревизии не выдаётся." "reason": "Общий listRevisions с REST: только метаданные, максимум 50 записей; серверная область и права проверяются до SQL, payload ревизии не выдаётся."
}, },
{
"method": "POST",
"path": "/api/ix/import",
"status": "excluded",
"operations": [],
"reason": "Одноразовый импорт Linux-клиента: выдаёт конфигурацию только по коду, созданному оператором IX."
},
{
"method": "GET",
"path": "/api/ix/linux-bonds",
"status": "excluded",
"operations": [],
"reason": "Каталог для формы выбора туннелей одного VPS в WebUI. Оператор сопоставляет подключения разных площадок со своими локальными интерфейсами."
},
{
"method": "GET",
"path": "/api/ix/nodes",
"status": "excluded",
"operations": [],
"reason": "Служебная проекция для выбора площадок в интерфейсе. В MCP доступ к серверам определяется областью подключения."
},
{
"method": "GET",
"path": "/api/ix/nodes/:serverId/inventory",
"status": "mediated",
"operations": ["network.ix.inventory"],
"reason": "Общее чтение интерфейсов, шлюзов и кандидата Router ID. MCP проверяет серверную область, а контекст редактируемого сегмента используется в WebUI."
},
{
"method": "GET",
"path": "/api/ix/segments",
"status": "mediated",
"operations": ["network.ix.list"],
"reason": "Общий сервис списка сегментов. MCP ограничивает выборку областью серверов и возвращает метаданные ревизий."
},
{
"method": "GET",
"path": "/api/ix/segments/:id/linux",
"status": "excluded",
"operations": [],
"reason": "Шаблон подключения Linux оператор получает в интерфейсе для локальной настройки клиента."
},
{
"method": "GET",
"path": "/api/ix/segments/:id/linux/path",
"status": "mediated",
"operations": ["network.ix.linux-path"],
"reason": "Общее чтение маршрутов Linux-клиента из применённой ревизии. MCP проверяет доступ к узлу клиента."
},
{
"method": "GET",
"path": "/api/ix/segments/:id/status",
"status": "mediated",
"operations": ["network.ix.read"],
"reason": "Общий опрос маршрутов и BGP-сессий применённой ревизии. MCP проверяет доступ ко всем узлам сегмента."
},
{
"method": "GET",
"path": "/api/ix/topology",
"status": "excluded",
"operations": [],
"reason": "Проекция применённых связей для сетевой карты. MCP читает конфигурацию и состояние отдельных сегментов."
},
{ {
"method": "GET", "method": "GET",
"path": "/api/logs", "path": "/api/logs",
@@ -1071,7 +1134,7 @@
"operations": [ "operations": [
"traffic.live.read" "traffic.live.read"
], ],
"reason": "Общий readTrafficLiveSample; MCP возвращает ограниченную серию до трёх срезов вместо бесконечного SSE. Полнота суммы, направление RX/TX, отзыв доступа и смена источника проверяются перед каждым новым native-запросом." "reason": "Общий readTrafficLiveSample для разового чтения интерфейса, SSE и ограниченной MCP-серии. Источник проверяется перед каждым новым native-запросом."
}, },
{ {
"method": "GET", "method": "GET",
@@ -1562,6 +1625,97 @@
], ],
"reason": "Общий REST/MCP executor существующего сертификата: оба selector и все роли, явный private/CA intent, human MCP plan, actor/key no-replay, exact owned file/read/cleanup, encrypted owner-only artifact/TTL; синтетическая SQL/HTTP/portal и browser приёмка. Native CHR отдельно." "reason": "Общий REST/MCP executor существующего сертификата: оба selector и все роли, явный private/CA intent, human MCP plan, actor/key no-replay, exact owned file/read/cleanup, encrypted owner-only artifact/TTL; синтетическая SQL/HTTP/portal и browser приёмка. Native CHR отдельно."
}, },
{
"method": "POST",
"path": "/api/ix/preview",
"status": "excluded",
"operations": [],
"reason": "Локальный предпросмотр объектов из компилятора. План MCP дополнительно фиксирует состояние площадок и требует подтверждения."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/linux-bonds",
"status": "excluded",
"operations": [],
"reason": "WebUI сохраняет выбранные оператором интерфейсы и порядок путей для последующего импорта и подтверждения в локальном ix-client."
},
{
"method": "DELETE",
"path": "/api/ix/segments/:id/linux-bonds/:bondId",
"status": "excluded",
"operations": [],
"reason": "Оператор удаляет сохранённое описание группы из WebUI. Снятие политики на самом VPS подтверждается отдельно в ix-client."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/linux-bonds/:bondId/export",
"status": "excluded",
"operations": [],
"reason": "Оператор скачивает JSON группы из WebUI и локально сопоставляет его с интерфейсами VPS в ix-client."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/plan",
"status": "mediated",
"operations": ["network.ix.configure"],
"reason": "Предпросмотр сохранённой ревизии для оператора. MCP строит отдельный план через общий сервис IX."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/apply",
"status": "mediated",
"operations": ["network.ix.configure"],
"reason": "Пользователь WebUI подтверждает просмотренную ревизию. MCP применяет свой подтверждённый план через общий исполнитель IX."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/linux",
"status": "excluded",
"operations": [],
"reason": "WebUI сохраняет одной ревизией клиента Linux и выбранный транзит. Записи на RouterOS идут после подтверждения изменений."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/linux/credential",
"status": "excluded",
"operations": [],
"reason": "WebUI выдаёт действующий PSK или ключ WireGuard оператору с правом изменения сети и записью в журнале. Для WireGuard MCP возвращает защищённую ссылку через network.wireguard.export."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/linux/revoke",
"status": "excluded",
"operations": [],
"reason": "WebUI сохраняет черновик отзыва клиента. Удаление конфигурации RouterOS выполняется отдельным подтверждённым планом."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/removal-plan",
"status": "mediated",
"operations": ["network.ix.delete"],
"reason": "Предпросмотр управляемых объектов перед явным подтверждением удаления сегмента."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/transit",
"status": "excluded",
"operations": [],
"reason": "Мастер WebUI собирает черновик связи и выхода по инвентарю двух узлов. Применение к обоим маршрутизаторам требует отдельного подтверждения."
},
{
"method": "DELETE",
"path": "/api/ix/segments/:id",
"status": "mediated",
"operations": ["network.ix.delete"],
"reason": "Общий исполнитель удаления проверяет ревизию и очищает управляемые объекты IX."
},
{
"method": "POST",
"path": "/api/ix/segments",
"status": "excluded",
"operations": [],
"reason": "Сохранение черновика из интерфейса. Для изменения конфигурации через MCP используется план с подтверждением."
},
{ {
"method": "POST", "method": "POST",
"path": "/api/mcp/connections", "path": "/api/mcp/connections",
@@ -1632,6 +1786,20 @@
"operations": ["network.bridge-vlan.configure"], "operations": ["network.bridge-vlan.configure"],
"reason": "Подготовка связанного плана bridge/VLAN через тот же MCP-инструмент; выполнение требует человеческого подтверждения." "reason": "Подготовка связанного плана bridge/VLAN через тот же MCP-инструмент; выполнение требует человеческого подтверждения."
}, },
{
"method": "POST",
"path": "/api/mcp/ix/plan",
"status": "mediated",
"operations": ["network.ix.configure"],
"reason": "Интерфейс владельца вызывает тот же инструмент MCP подготовки плана IX. Применение проходит отдельно после подтверждения."
},
{
"method": "POST",
"path": "/api/mcp/ix/restore",
"status": "mediated",
"operations": ["network.ix.restore"],
"reason": "Интерфейс владельца вызывает тот же инструмент MCP подготовки восстановления сохранённой ревизии IX."
},
{ {
"method": "POST", "method": "POST",
"path": "/api/mcp/management-channels", "path": "/api/mcp/management-channels",
+2 -1
View File
@@ -60,6 +60,7 @@
"test:ipsec": "tsx src/services/ipsec-config.test.ts && tsx src/services/ipsec-state.test.ts && tsx src/routes/ipsec-history.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-operation.test.ts && tsx src/routes/ipsec-mutation.test.ts && tsx src/routes/ipsec-nat.test.ts && tsx src/routes/ipsec-group.test.ts && tsx src/services/ipsec-peer-delete.test.ts && tsx src/modules/mcp/ipsec-peer-delete-actions.test.ts && tsx src/services/ipsec-user-delete.test.ts && tsx src/modules/mcp/ipsec-user-delete-actions.test.ts && tsx src/services/ipsec-certificate-delete.test.ts && tsx src/modules/mcp/ipsec-certificate-delete-actions.test.ts && tsx src/services/ipsec-peer-update.test.ts && tsx src/modules/mcp/ipsec-peer-update-actions.test.ts && tsx src/services/ipsec-user-update-model.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/services/ipsec-server-delete-model.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/ipsec-user-create-model.test.ts", "test:ipsec": "tsx src/services/ipsec-config.test.ts && tsx src/services/ipsec-state.test.ts && tsx src/routes/ipsec-history.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-operation.test.ts && tsx src/routes/ipsec-mutation.test.ts && tsx src/routes/ipsec-nat.test.ts && tsx src/routes/ipsec-group.test.ts && tsx src/services/ipsec-peer-delete.test.ts && tsx src/modules/mcp/ipsec-peer-delete-actions.test.ts && tsx src/services/ipsec-user-delete.test.ts && tsx src/modules/mcp/ipsec-user-delete-actions.test.ts && tsx src/services/ipsec-certificate-delete.test.ts && tsx src/modules/mcp/ipsec-certificate-delete-actions.test.ts && tsx src/services/ipsec-peer-update.test.ts && tsx src/modules/mcp/ipsec-peer-update-actions.test.ts && tsx src/services/ipsec-user-update-model.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/services/ipsec-server-delete-model.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/ipsec-user-create-model.test.ts",
"test:live-maps": "tsx src/services/gre-revision-restore.test.ts && tsx src/services/gre-native-mutation.test.ts && tsx src/services/gre-mutation.test.ts && tsx src/services/filter-rules-observed.test.ts && tsx src/services/firewall-revision-restore.test.ts && tsx src/services/firewall-address-write.test.ts && tsx src/services/firewall-rule-write.test.ts && tsx src/services/gre-observed-read.test.ts && tsx src/services/network-observed-read.test.ts && tsx src/services/firewall-rule-move.test.ts && tsx src/services/ospf-state-read.test.ts && tsx src/modules/mcp/readiness-http.test.ts && tsx src/services/probe-interface-model.test.ts && tsx src/services/wan-runtime-model.test.ts && tsx src/services/gre-keepalive.test.ts && tsx src/services/gre-read.test.ts && tsx src/services/ospf-route-parse.test.ts && tsx src/services/vxlan-live.test.ts && tsx src/routes/vxlan.test.ts && tsx src/services/containers-live.test.ts && tsx src/services/firewall-poll.test.ts && tsx src/services/gre-catalog-poll.test.ts && tsx src/routes/filters-gre-catalog.test.ts && tsx src/routes/bgp-catalog.test.ts && tsx src/services/bgp-catalog-parse.test.ts && tsx src/routes/ospf-catalog.test.ts && tsx src/services/ospf-observed-values.test.ts && tsx src/routes/ospf-legacy.test.ts", "test:live-maps": "tsx src/services/gre-revision-restore.test.ts && tsx src/services/gre-native-mutation.test.ts && tsx src/services/gre-mutation.test.ts && tsx src/services/filter-rules-observed.test.ts && tsx src/services/firewall-revision-restore.test.ts && tsx src/services/firewall-address-write.test.ts && tsx src/services/firewall-rule-write.test.ts && tsx src/services/gre-observed-read.test.ts && tsx src/services/network-observed-read.test.ts && tsx src/services/firewall-rule-move.test.ts && tsx src/services/ospf-state-read.test.ts && tsx src/modules/mcp/readiness-http.test.ts && tsx src/services/probe-interface-model.test.ts && tsx src/services/wan-runtime-model.test.ts && tsx src/services/gre-keepalive.test.ts && tsx src/services/gre-read.test.ts && tsx src/services/ospf-route-parse.test.ts && tsx src/services/vxlan-live.test.ts && tsx src/routes/vxlan.test.ts && tsx src/services/containers-live.test.ts && tsx src/services/firewall-poll.test.ts && tsx src/services/gre-catalog-poll.test.ts && tsx src/routes/filters-gre-catalog.test.ts && tsx src/routes/bgp-catalog.test.ts && tsx src/services/bgp-catalog-parse.test.ts && tsx src/routes/ospf-catalog.test.ts && tsx src/services/ospf-observed-values.test.ts && tsx src/routes/ospf-legacy.test.ts",
"test": "node scripts/test.mjs", "test": "node scripts/test.mjs",
"test:ix": "tsx --test src/services/internet-exchange-plan.test.ts src/services/internet-exchange-execution.test.ts src/services/internet-exchange-bonds.test.ts src/services/ix-bond-transport.test.ts src/services/ix-import-links.test.ts",
"test:evolution": "tsx src/services/evobgp-catalog.test.ts && tsx src/services/evobgp-client.test.ts && tsx src/routes/evobgp-catalog.test.ts && tsx src/routes/evobgp-settings.test.ts && tsx src/plugins/auth.evolution-settings.test.ts", "test:evolution": "tsx src/services/evobgp-catalog.test.ts && tsx src/services/evobgp-client.test.ts && tsx src/routes/evobgp-catalog.test.ts && tsx src/routes/evobgp-settings.test.ts && tsx src/plugins/auth.evolution-settings.test.ts",
"test:netflow-purge": "tsx src/db/operation-lock.test.ts && tsx src/services/traffic-flow-purge-execution.test.ts && tsx src/services/flow-purge-partitions.test.ts && tsx --test src/services/traffic-flow-worker-lifecycle.test.ts && tsx src/routes/traffic-flow-purge.test.ts", "test:netflow-purge": "tsx src/db/operation-lock.test.ts && tsx src/services/traffic-flow-purge-execution.test.ts && tsx src/services/flow-purge-partitions.test.ts && tsx --test src/services/traffic-flow-worker-lifecycle.test.ts && tsx src/routes/traffic-flow-purge.test.ts",
"test:netflow-settings": "tsx src/services/traffic-flow-host-file-builders.test.ts && tsx src/services/traffic-flow-key-execution.test.ts && tsx src/routes/traffic-flow-settings.test.ts && tsx src/plugins/auth.netflow-settings.test.ts && tsx src/services/traffic-flow-agent-install.test.ts && tsx src/services/traffic-flow-agent-client.test.ts && tsx src/services/traffic-flow-operation-queue.test.ts && tsx src/routes/traffic-flow-host.test.ts && tsx src/services/traffic-flow-settings-execution.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/traffic-flow-lifecycle-fence.test.ts && tsx src/services/traffic-flow-settings-store.test.ts && tsx src/services/traffic-flow-settings-service.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts", "test:netflow-settings": "tsx src/services/traffic-flow-host-file-builders.test.ts && tsx src/services/traffic-flow-key-execution.test.ts && tsx src/routes/traffic-flow-settings.test.ts && tsx src/plugins/auth.netflow-settings.test.ts && tsx src/services/traffic-flow-agent-install.test.ts && tsx src/services/traffic-flow-agent-client.test.ts && tsx src/services/traffic-flow-operation-queue.test.ts && tsx src/routes/traffic-flow-host.test.ts && tsx src/services/traffic-flow-settings-execution.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/traffic-flow-lifecycle-fence.test.ts && tsx src/services/traffic-flow-settings-store.test.ts && tsx src/services/traffic-flow-settings-service.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts",
@@ -68,7 +69,7 @@
"test:containers": "tsx src/services/containers-live.test.ts && tsx src/services/containers-state.test.ts && tsx src/services/container-removal.test.ts && tsx src/routes/containers-state.test.ts", "test:containers": "tsx src/services/containers-live.test.ts && tsx src/services/containers-state.test.ts && tsx src/services/container-removal.test.ts && tsx src/routes/containers-state.test.ts",
"test:certificates": "tsx src/services/certificate-installation.test.ts && tsx src/services/certificate-renew-collector.test.ts && tsx src/services/certificate-issue-execution.test.ts && tsx src/services/certificate-issue-request.test.ts && tsx src/routes/certificates-issue.test.ts && tsx src/services/certificate-issue-dto.test.ts && tsx src/services/certificate-parse.test.ts && tsx src/services/certificates-state.test.ts && tsx src/routes/certificates-state.test.ts && tsx src/services/acme-settings-test.test.ts && tsx src/services/acme-settings-update-model.test.ts && tsx src/modules/mcp/acme-settings-actions.test.ts", "test:certificates": "tsx src/services/certificate-installation.test.ts && tsx src/services/certificate-renew-collector.test.ts && tsx src/services/certificate-issue-execution.test.ts && tsx src/services/certificate-issue-request.test.ts && tsx src/routes/certificates-issue.test.ts && tsx src/services/certificate-issue-dto.test.ts && tsx src/services/certificate-parse.test.ts && tsx src/services/certificates-state.test.ts && tsx src/routes/certificates-state.test.ts && tsx src/services/acme-settings-test.test.ts && tsx src/services/acme-settings-update-model.test.ts && tsx src/modules/mcp/acme-settings-actions.test.ts",
"test:system-database": "tsx src/services/bounded-database-dump.test.ts && tsx src/services/database-dump-connection.test.ts && tsx src/services/system-database-partition-restore.test.ts && tsx src/services/system-database-cache.test.ts && tsx src/services/database-background-work.test.ts && tsx src/services/database-request-gate.test.ts && tsx --test src/services/detached-database-admission.test.ts && tsx src/services/traffic-flow-worker-shutdown.test.ts && tsx src/services/system-database-restore-execution.test.ts && tsx src/services/system-database-operation.test.ts && tsx src/services/system-database-schema-readiness.test.ts && tsx --test src/routes/mcp-oauth-database-admission.test.ts && tsx src/routes/system-database.test.ts && tsx src/plugins/auth.system-database.test.ts && tsx src/services/database-control-archive-boundary.test.ts && tsx src/db/database-schema-control-model.test.ts && tsx src/db/database-schema-control.test.ts && tsx src/db/controlled-migrations.test.ts && tsx src/db/controlled-schema-verification.test.ts && tsx --test src/db/migration-data-inventory.test.ts && tsx --test src/services/database-maintenance-startup.test.ts && tsx --test src/services/database-restore-audit.test.ts && tsx --test src/services/database-maintenance-resolution.test.ts && tsx --test scripts/database-maintenance-resolution.test.mts && tsx src/db/database-runtime-schema.test.ts", "test:system-database": "tsx src/services/bounded-database-dump.test.ts && tsx src/services/database-dump-connection.test.ts && tsx src/services/system-database-partition-restore.test.ts && tsx src/services/system-database-cache.test.ts && tsx src/services/database-background-work.test.ts && tsx src/services/database-request-gate.test.ts && tsx --test src/services/detached-database-admission.test.ts && tsx src/services/traffic-flow-worker-shutdown.test.ts && tsx src/services/system-database-restore-execution.test.ts && tsx src/services/system-database-operation.test.ts && tsx src/services/system-database-schema-readiness.test.ts && tsx --test src/routes/mcp-oauth-database-admission.test.ts && tsx src/routes/system-database.test.ts && tsx src/plugins/auth.system-database.test.ts && tsx src/services/database-control-archive-boundary.test.ts && tsx src/db/database-schema-control-model.test.ts && tsx src/db/database-schema-control.test.ts && tsx src/db/controlled-migrations.test.ts && tsx src/db/controlled-schema-verification.test.ts && tsx --test src/db/migration-data-inventory.test.ts && tsx --test src/services/database-maintenance-startup.test.ts && tsx --test src/services/database-restore-audit.test.ts && tsx --test src/services/database-maintenance-resolution.test.ts && tsx --test scripts/database-maintenance-resolution.test.mts && tsx src/db/database-runtime-schema.test.ts",
"test:all": "npm run test:logs && npm run test:probes && npm run test:exec && npm run test:alert-engine && npm run test:alerts-telegram && npm run test:auth && npm run test:wireguard && npm run test:ipsec && npm run test:traffic-rate && npm run test:traffic-flow && npm run test:users && npm run test:pg && npm run test:sidebar-counts && npm run test:backups && npm run test:scheduler && npm run test:live-maps && npm run test:ospf-optimizer && npm run test:recursive-routes && npm run test:config-sync && npm run test:ros-file && npm run test:containers && npm run test:certificates && npm run test:netflow-settings && npm run test:netflow-purge && npm run test:evolution && npm run test:system-database && npm run test:server-privacy && npm run test:mcp:module-completion && npm run test:mcp:loopback-agent && npm run test:server-probe-management && npm run test:server-poll-management && npm run test:mcp:routing-authority && npm run test:mcp:native-readers && npm run test:mcp:chr-acquisition && npm run test:mcp:shared-context && npm run test:mcp:telemetry-configuration", "test:all": "npm run test:ix && npm run test:logs && npm run test:probes && npm run test:exec && npm run test:alert-engine && npm run test:alerts-telegram && npm run test:auth && npm run test:wireguard && npm run test:ipsec && npm run test:traffic-rate && npm run test:traffic-flow && npm run test:users && npm run test:pg && npm run test:sidebar-counts && npm run test:backups && npm run test:scheduler && npm run test:live-maps && npm run test:ospf-optimizer && npm run test:recursive-routes && npm run test:config-sync && npm run test:ros-file && npm run test:containers && npm run test:certificates && npm run test:netflow-settings && npm run test:netflow-purge && npm run test:evolution && npm run test:system-database && npm run test:server-privacy && npm run test:mcp:module-completion && npm run test:mcp:loopback-agent && npm run test:server-probe-management && npm run test:server-poll-management && npm run test:mcp:routing-authority && npm run test:mcp:native-readers && npm run test:mcp:chr-acquisition && npm run test:mcp:shared-context && npm run test:mcp:telemetry-configuration",
"test:server-privacy": "tsx ../packages/contracts/src/servers.test.ts && tsx src/routes/server-secrets-sql.test.ts && tsx --test src/services/server-connection-test.test.ts", "test:server-privacy": "tsx ../packages/contracts/src/servers.test.ts && tsx src/routes/server-secrets-sql.test.ts && tsx --test src/services/server-connection-test.test.ts",
"test:mcp:flow-rebuild:pg": "node scripts/test-mcp-postgres.mjs --flow-rebuild-mcp", "test:mcp:flow-rebuild:pg": "node scripts/test-mcp-postgres.mjs --flow-rebuild-mcp",
"test:mcp:flow-host-keys:pg": "node scripts/test-mcp-postgres.mjs --flow-host-keys", "test:mcp:flow-host-keys:pg": "node scripts/test-mcp-postgres.mjs --flow-host-keys",
+41
View File
@@ -0,0 +1,41 @@
import { execFileSync } from "node:child_process"
import { isIPv4 } from "node:net"
import { homedir } from "node:os"
import { join } from "node:path"
const targets = process.env.MMAPP_IX_CHR_HOSTS?.split(",").map(value => value.trim()) ?? []
if (targets.length !== 2 || new Set(targets).size !== 2 || !targets.every(isIPv4)) {
throw new Error("MMAPP_IX_CHR_HOSTS must identify two distinct, isolated CHR IPv4 addresses")
}
export const hosts = [targets[0], targets[1]] as const
const key = join(homedir(), ".ssh", "chr_claude")
const known = process.env.MMAPP_IX_TEST_KNOWN_HOSTS ?? join(homedir(), ".ssh", "known_hosts")
export const quote = (value: string) => '"' + value.replace(/[\\"$]/g, "\\$&").replace(/\n/g, "\\n") + '"'
export const sshOptions = ["-F", process.platform === "win32" ? "NUL" : "/dev/null", "-i", key,
"-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", "-o", "UserKnownHostsFile=" + known,
"-o", "ConnectTimeout=12", "-o", "LogLevel=ERROR"]
export function cli(side: number, expression: string, stage?: string) {
const args = [...sshOptions, "claude@" + hosts[side],
`:onerror err in={ ${expression.replace(/\r?\n\s*/g, " ")}; :put "IX_OK" } do={ :put ("IX_ERROR:" . $err) }`]
const run = () => execFileSync("ssh", args, { encoding: "utf8", timeout: 35000, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }).trim()
let stdout: string
try {
for (let attempt = 0;; attempt++) {
try { stdout = run(); break } catch (error) {
// Retry only when the command could not have reached the router.
const failure = error as { status?: number; stderr?: string; stdout?: string }
if (attempt >= 2 || failure.status !== 255 || failure.stdout || !/^ssh: connect to host .* port 22: Connection timed out\s*$/i.test(failure.stderr ?? "")) throw error
}
}
} catch (error) {
if (stage) throw Error(`CHR ${side + 1}: SSH failed during ${stage}`)
throw error
}
if (!stdout.split(/\r?\n/).includes("IX_OK") || stdout.includes("IX_ERROR") || /syntax error|expected end|expected closing/.test(stdout)) {
const diagnostic = stdout.replace(/[a-f0-9]{36,}/gi, "[redacted]").slice(0, 420)
throw Error(`CHR ${side + 1} rejected ${stage ?? expression.slice(0, 360)} · ${diagnostic}`)
}
return stdout.replace(/\r?\n?IX_OK$/, "").trim()
}
+264
View File
@@ -0,0 +1,264 @@
import assert from "node:assert/strict"
import { randomBytes, randomUUID, X509Certificate } from "node:crypto"
import { mkdtemp } from "node:fs/promises"
import { createServer, isIPv4 } from "node:net"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { setTimeout as delay } from "node:timers/promises"
import { getCACertificates, setDefaultCACertificates } from "node:tls"
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"
import EmbeddedPostgres from "embedded-postgres"
import { SignJWT } from "jose"
import { ixNamespace } from "../../src/services/internet-exchange-plan.js"
import { cli, hosts, quote } from "./ix-chr-ssh.mjs"
assert.deepEqual(process.argv.slice(2), ["--owned-test-pair"])
for (const name of Object.keys(process.env)) {
if (/^(DATABASE_|MCP_|AUTH_|PG|MMAPP_)/.test(name)) delete process.env[name]
}
process.env.DOTENV_CONFIG_PATH = join(tmpdir(), "mmapp-ix-no-env-" + randomUUID())
const id = randomUUID(), ns = ixNamespace(id), short = ns.slice(0, 12)
const segment = short + "-gre", gre = short + "-gre", pin = (side: number) => "10.245.0." + (1 + side)
const psk = randomBytes(32).toString("hex"), password = randomBytes(24).toString("hex")
const roots = getCACertificates("default")
const certificates: string[] = []
const entered = new Map<number, string>()
const result: Record<string, unknown> = {}
let appliedNamespace: string | undefined
const ipsecPaths = ["/ip/ipsec/policy", "/ip/ipsec/identity", "/ip/ipsec/peer", "/ip/ipsec/proposal", "/ip/ipsec/profile"]
const ixPaths = ["/ip/route", "/ip/address", "/ip/firewall/filter", "/ipv6/firewall/filter", "/ip/vrf", "/interface/bridge"]
const sides = [0, 1]
function baseline(side: number) {
return cli(side, `:put [/system resource get version]; :put [/system resource get board-name];
:put [/ip/service/print as-value proplist=disabled,port,certificate,address where name=www-ssl and dynamic=no];
:put [:len [/interface/gre/find]]; :put [:len [/ip/vrf/find]];
:put [:len [/ip/ipsec/peer/find]]; :put [:len [/ip/ipsec/installed-sa/find]];
:put [:len [/ip/firewall/filter/find]]; :put [:len [/ipv6/firewall/filter/find]];
:put [:len [/ip/address/find where address~${quote("^" + hosts[side] + "/")}]]`)
}
async function port() {
const socket = createServer()
await new Promise<void>((ok, fail) => socket.listen(0, "127.0.0.1", ok).on("error", fail))
const value = (socket.address() as { port: number }).port
await new Promise<void>((ok, fail) => socket.close(error => error ? fail(error) : ok()))
return value
}
async function until<T>(label: string, check: () => T | Promise<T>, timeout = 45000) {
const end = Date.now() + timeout
do {
const value = await check()
if (value) return value
await delay(900)
} while (Date.now() < end)
throw Error(label + " timed out")
}
function prepareGre(side: number) {
const local = hosts[side], remote = hosts[1 - side]
const p = quote(short)
cli(side, `:put "profile"; /ip/ipsec/profile/add name=${p} enc-algorithm=aes-256 hash-algorithm=sha256 dh-group=modp2048;
:put "proposal"; /ip/ipsec/proposal/add name=${p} enc-algorithms=aes-256-cbc auth-algorithms=sha256 pfs-group=modp2048;
:put "peer"; /ip/ipsec/peer/add name=${p} address=${remote}/32 local-address=${local} profile=${p} exchange-mode=ike2 passive=${side ? "yes" : "no"};
:put "identity"; /ip/ipsec/identity/add peer=${p} auth-method=pre-shared-key secret=${quote(psk)} comment=${p};
:put "policy"; /ip/ipsec/policy/add peer=${p} src-address=${local}/32 dst-address=${remote}/32 protocol=gre action=encrypt level=require tunnel=no proposal=${p} comment=${p};
:put "GRE"; /interface/gre/add name=${quote(gre)} local-address=${local} remote-address=${remote} allow-fast-path=no comment=${quote("IX:" + segment)};
/ip/address/add address=${pin(side)}/30 interface=${quote(gre)} comment=${quote(ns + ":lab:gre")}`, "isolated IKEv2/GRE setup")
}
async function openRest(side: number) {
const sessions = cli(side, ':put [/user/active/print as-value proplist=address where name=claude and via=ssh]')
const sources = [...new Set([...sessions.matchAll(/address=([\d.]+)/g)].map(match => match[1]))]
assert(sources.length === 1 && isIPv4(sources[0]), "Cannot pin HTTPS to a single observed management address")
const source = sources[0] + "/32", host = hosts[side], ca = short + "-ca", leaf = short + "-tls"
cli(side, `/certificate/add name=${quote(ca)} common-name=${quote(ca)} key-usage=key-cert-sign,crl-sign days-valid=1;
/certificate/sign [find where name=${quote(ca)}];
/certificate/add name=${quote(leaf)} common-name=${quote(host)} subject-alt-name=IP:${host} key-usage=tls-server days-valid=1;
/certificate/sign [find where name=${quote(leaf)}] ca=${quote(ca)};
/certificate/export-certificate [find where name=${quote(ca)}] file-name=${quote(ca)}`)
const certificate = cli(side, `:put [/file/get [find where name=${quote(ca + ".crt")}] contents]`)
assert.equal(new X509Certificate(certificate).ca, true)
certificates.push(certificate)
setDefaultCACertificates([...roots, ...certificates])
cli(side, `/ip/firewall/filter/add chain=input action=drop protocol=tcp dst-port=443 dst-address=${host}/32 src-address=!${source} comment=${quote(ns + ":lab:tls")};
/user/group/add name=${quote(short)} policy=read,write,api,rest-api;
/user/add name=${quote(short)} address=${source} group=${quote(short)} password=${quote(password)};
/ip/service/set [find where name=www-ssl and dynamic=no] address=${source} certificate=${quote(leaf)} disabled=no`, "restricted HTTPS REST setup")
let lastError = ""
await until("router REST on verified HTTPS", async () => {
const response = await fetch(`https://${host}/rest/system/resource`, {
headers: { authorization: "Basic " + Buffer.from(short + ":" + password).toString("base64") }, signal: AbortSignal.timeout(5000),
}).catch(error => { lastError = String(error.cause ?? error); return undefined })
if (!response) return false
assert.equal(response.status, 200, "REST test user was refused")
assert.equal((await response.json()).version, "7.24.5 (stable)")
return true
}, 18000).catch(error => { throw Error(`CHR ${side + 1}: ${error.message} · ${lastError}`) })
}
function clean(side: number, before: string) {
const own = `where comment~${quote(appliedNamespace ? `^(${ns}|${appliedNamespace}):` : "^" + ns + ":")}`
const checks = ixPaths.map(path => `[:len [${path}/find ${own}]]`)
cli(side, `/ip/service/set [find where name=www-ssl and dynamic=no] disabled=yes address="" certificate=none;
/user/remove [/user/find where name=${quote(short)}]; /user/group/remove [/user/group/find where name=${quote(short)}];
/file/remove [/file/find where name=${quote(short + "-ca.crt")}];
/certificate/remove [/certificate/find where name=${quote(short + "-tls")}];
/certificate/remove [/certificate/find where name=${quote(short + "-ca")}];
${ixPaths.map(path => `${path}/remove [${path}/find ${own}]`).join("; ")};
/interface/gre/remove [/interface/gre/find where name=${quote(gre)} and comment=${quote("IX:" + segment)}];
${ipsecPaths.map((path, i) => `${path}/remove [${path}/find where ${i < 2 ? "comment" : "name"}=${quote(short)}]`).join("; ")}`)
checks.push(...ipsecPaths.map((path, i) => `[:len [${path}/find where ${i < 2 ? "comment" : "name"}=${quote(short)}]]`),
`[:len [/user/find where name=${quote(short)}]]`, `[:len [/user/group/find where name=${quote(short)}]]`,
`[:len [/certificate/find where name~${quote("^" + short + "-(ca|tls)$")}]]`, `[:len [/file/find where name=${quote(short + "-ca.crt")}]]`)
assert.equal(cli(side, ":put (" + checks.join("+") + ")"), "0")
assert.equal(baseline(side), before)
}
async function useManager() {
const root = await mkdtemp(join(tmpdir(), "mmapp-ix-mcp-"))
process.chdir(root)
const pgPort = await port(), httpPort = await port()
const origin = `http://127.0.0.1:${httpPort}`, endpoint = new URL("/mcp", origin)
const pgPassword = randomBytes(24).toString("hex"), jwtSecret = randomBytes(32).toString("hex")
Object.assign(process.env, { DATABASE_URL: `postgresql://ixlab:${pgPassword}@127.0.0.1:${pgPort}/postgres`,
NODE_ENV: "test", AUTH_REQUIRED: "true", AUTH_JWT_SECRET: jwtSecret, AUTH_ISSUER: origin,
AUTH_PORTAL_URL: origin, MCP_STATE_DIR: join(root, "state"), MCP_PUBLIC_URL: endpoint.href, MCP_UI_URL: origin, CORS_ORIGIN: origin })
const pg = new EmbeddedPostgres({ databaseDir: join(root, "db"), user: "ixlab", password: pgPassword, port: pgPort,
persistent: false, createPostgresUser: false, initdbFlags: ["--encoding=UTF8", "--no-locale"], postgresFlags: ["-h", "127.0.0.1"],
onLog: () => {}, onError: () => {} })
await pg.initialise()
await pg.start()
const { pool, closePool } = await import("../../src/db/index.js")
const { applySqlMigrations } = await import("../../src/db/migrate.js")
const { buildApp } = await import("../../src/index.js")
const { updateMcpSettings } = await import("../../src/modules/mcp/store.js")
let app: Awaited<ReturnType<typeof buildApp>> | undefined
const client = new Client({ name: "owned-ix-gre", version: "1.0.0" })
try {
await applySqlMigrations(pool)
const serverIds: number[] = []
for (const [side, host] of hosts.entries()) {
const { rows } = await pool.query(`INSERT INTO servers(name,host,port,username,password,use_ssl,verify_ssl,enabled,type)
VALUES($1,$2,443,$3,$4,true,true,true,'ix-node') RETURNING id`, [`ix-chr-${side + 1}`, host, short, password])
serverIds.push(Number(rows[0].id))
}
const permissions = ["mm:network:read", "mm:network:write", "mm:mcp:admin", "mm:mcp:approve"]
const actor = { id: "ix-fixture", email: "[email protected]", name: "IX fixture", apps: ["mm"], permissions,
expiresAt: Date.now() + 1800000, issuedAt: Date.now() }
await updateMcpSettings({ enabled: true }, actor)
app = await buildApp({ startScheduler: false, logger: false })
await app.listen({ port: httpPort, host: "127.0.0.1" })
const jwt = await new SignJWT({ sub: actor.id, apps: actor.apps, permissions }).setProtectedHeader({ alg: "HS256" })
.setIssuer(origin).setIssuedAt().setExpirationTime("15m").sign(new TextEncoder().encode(jwtSecret))
async function rest(path: string, data?: object) {
const response = await fetch(origin + "/api" + path, { method: data ? "POST" : "GET",
headers: { authorization: "Bearer " + jwt, "content-type": "application/json" },
...(data ? { body: JSON.stringify(data) } : {}), signal: AbortSignal.timeout(15000) })
const body = await response.json()
assert(response.ok, `${path}: ${response.status} ${JSON.stringify(body).slice(0, 600)}`)
return body
}
const configuration = { name: segment, sites: serverIds.map((serverId, side) => ({
serverId, routerId: pin(side), autonomousSystem: 64512 + side,
interfaces: [{ name: gre, kind: "gre-ipsec", localEndpoint: hosts[side], endpoint: hosts[1 - side], peerServerId: serverIds[1 - side] }],
})) }
const draft = await rest("/ix/segments", { revision: 0, configuration })
const segmentId: string = draft.segment.id
assert.match(segmentId, /^[0-9a-f-]{36}$/)
appliedNamespace = ixNamespace(segmentId)
assert.equal(draft.segment.revision, 1)
assert.equal(draft.segment.appliedRevision, null)
result.managerRestDraft = true
const { token } = await rest("/mcp/connections", { name: "Owned IX approval", mode: "approval", permissions: ["mm:network:read", "mm:network:write"],
limits: { mutationsPerHour: 40, callsPerMinute: 120 },
expiresAt: new Date(Date.now() + 600000).toISOString(), scope: { serverIds, allowGlobal: false,
operationIds: ["network.ix.configure", "network.ix.read", "changes.apply", "operations.read"] } })
await client.connect(new StreamableHTTPClientTransport(endpoint, {
requestInit: { headers: { authorization: "Bearer " + token } },
}), { timeout: 10000 })
async function call(name: string, args: object, expectedError = false) {
const reply = await client.callTool({ name, arguments: args }, undefined, { timeout: 120000 })
assert.equal(Boolean(reply.isError), expectedError, name + " " + JSON.stringify(reply.structuredContent ?? reply.content).slice(0, 1200))
return (reply.structuredContent as { result: any })?.result
}
const plan = await call("mm_ix_change_plan", { change: { id: segmentId, revision: 1, configuration } })
assert.equal(plan.state, "awaiting-approval")
const apply = { planId: plan.planId, idempotencyKey: randomUUID() }
await call("mm_change_apply", apply, true)
await rest("/mcp/plans/" + plan.planId + "/decision", { approve: true })
const op = await call("mm_change_apply", apply)
const terminal = await until("MCP terminal operation", async () => {
const value = await call("mm_operation_get", { operationId: op.id })
return !["pending", "running"].includes(value.state) && value
}, 90000)
assert.equal(terminal.state, "applied", JSON.stringify({ state: terminal.state, error: terminal.error_code }))
assert.equal(terminal.verification, "passed")
assert.equal((await call("mm_change_apply", apply)).id, op.id)
const verified = await call("mm_ix_segment_get", { id: segmentId })
assert.equal(verified.segment.appliedRevision, 2)
const status = await rest("/ix/segments/" + segmentId + "/status")
assert.deepEqual(status.sites.map(({ serverId, available }: { serverId: number; available: boolean }) => [serverId, available]),
serverIds.map(serverId => [serverId, true]))
result.mcpAppliedAndVerified = true
result.routerRestSites = status.sites.length
} finally {
await client.close()
await app?.close()
await closePool()
await pg.stop()
}
}
function packets(side: number) {
assert(appliedNamespace)
return Number(cli(side, `:put [/ping address=${pin(1 - side)} src-address=${pin(side)} vrf=${appliedNamespace} count=3 interval=250ms]`).split(/\r?\n/).at(-1))
}
let failure: unknown
try {
const original = sides.map(baseline)
for (const value of original) {
const [version, board, ...expected] = value.split(/\r?\n/)
assert.equal(version, "7.24.5 (stable)")
assert.match(board, /^CHR/)
const [https, ...inventory] = expected
assert.match(https, /(?:^|;)certificate=none;disabled=true;port=443$/)
assert.deepEqual(inventory, ["0", "1", "0", "0", "0", "0", "1"])
}
for (const side of sides) {
entered.set(side, original[side])
prepareGre(side)
}
for (const side of sides) await openRest(side)
console.log("Both RouterOS REST endpoints authenticated with temporary trusted HTTPS certificates")
await useManager()
console.log("MCP applied the reviewed configuration to both routers")
await until("encrypted GRE forwarding", () => packets(0) === 3 && packets(1) === 3)
const sas = sides.map(side => Number(cli(side, ":put [:len [/ip/ipsec/installed-sa/find where state=mature]]")))
assert(sas.every(count => count === 2))
result.greReplies = [3, 3]
result.matureIpsecSAs = sas
// Turn off both matching policies during the plaintext negative test.
for (const side of sides) cli(side, `/ip/ipsec/policy/disable [/ip/ipsec/policy/find where comment=${quote(short)}]`)
for (const side of sides) assert.equal(packets(side), 0)
result.plaintextGreBlocked = true
for (const side of sides) cli(side, `/ip/ipsec/policy/enable [/ip/ipsec/policy/find where comment=${quote(short)}]`)
await until("GRE recovery with required IPsec", () => packets(0) === 3 && packets(1) === 3)
result.greRecovered = true
} catch (error) {
failure = error
}
setDefaultCACertificates(roots)
let testStandRestored = true
for (const [side, original] of entered) {
try { clean(side, original) } catch (error) {
console.error(`Cleanup unconfirmed on CHR ${side + 1} · ${ns} ${appliedNamespace ?? ""}`)
testStandRestored = false
failure ??= error
}
}
console.log(JSON.stringify({ ...result, testStandRestored }))
if (failure) throw failure
+198
View File
@@ -0,0 +1,198 @@
import assert from "node:assert/strict"
import { randomInt, randomUUID } from "node:crypto"
import { setTimeout as delay } from "node:timers/promises"
import { ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
import { compileIxConfiguration, ixDiscardInterface, ixNamespace } from "../../src/services/internet-exchange-plan.js"
import { cli, hosts, quote } from "./ix-chr-ssh.mjs"
assert.equal(process.argv[2], "--owned-test-pair")
assert(process.argv.length === 3 || (process.argv.length === 4 && process.argv[3] === "--ipv6"))
const ipv6 = process.argv[3] === "--ipv6"
const id = randomUUID(), ns = ixNamespace(id), short = ns.slice(0, 10)
const discard = ixDiscardInterface(id)
const marker = ns + ":lab", primary = short + "-p", backup = short + "-b"
const port = randomInt(45000, 55000)
const net = "10.247." + randomInt(32, 224)
const [aP, bP, aB, bB] = ipv6 ? ["fd00:247:1::1", "fd00:247:1::2", "fd00:247:2::1", "fd00:247:2::2"] : [1, 2, 5, 6].map(n => net + "." + n)
const [target, pProbe, bProbe, trafficSource] = ipv6 ? ["2001:db8:3::200", "2001:db8:3::201", "2001:db8:3::202", "2001:db8:3::203"] : ["192.0.2.200", "192.0.2.201", "192.0.2.202", "192.0.2.203"]
const afi = ipv6 ? "ipv6" : "ip", length = ipv6 ? "/128" : "/32", gateway = ipv6 ? "fd00:198:18::101" : "198.18.0.101"
const addressPath = "/" + afi + "/address", routePath = "/" + afi + "/route", filterPath = "/" + afi + "/firewall/filter", listPath = "/" + afi + "/firewall/address-list"
const advertise: Record<string, string> = ipv6 ? { advertise: "no" } : {}
const community = "65000:120"
const entered = new Set<number>()
const results: Record<string, unknown> = {}
const pending: string[][] = [[], []]
const fields = (values: Record<string, string>) => Object.entries(values).map(([name, value]) => name === "blackhole" && value === "yes" ? name : name + "=" + quote(value)).join(" ")
function add(side: number, path: string, values: Record<string, string>, beforeMain = false) {
pending[side].push(path + " add " + fields(values) + (beforeMain ? " place-before=[/ip/vrf/find where name=main]" : ""))
}
function flush(side: number) {
while (pending[side].length) {
const commands = pending[side].splice(0, 10)
cli(side, commands.map((command, index) => `:put "IX_STAGE_${index}"; ${command}`).join("; "))
}
}
function owned(side: number, path: string, values: Record<string, string>, tag: string) {
add(side, path, { ...values, comment: marker + ":" + tag })
}
function preflight(side: number) {
const data = cli(side, `:put [/system resource get version]; :put [/system resource get board-name];
:put ([:len [/ip/vrf/find]]=1 && [:len [/interface/wireguard/find]]=0 && [:len [/routing/bgp/connection/find]]=0 && [:len [/ip/firewall/filter/find]]=0 && [:len [/ipv6/firewall/filter/find]]=0);
:put [:len [/ip/address/find where address~${quote("^" + hosts[side] + "/")}]]`)
const [version, board, empty, address] = data.split(/\r?\n/)
assert.equal(version, "7.24.5 (stable)")
assert.match(board, /^CHR/)
assert.equal(empty, "true", "Stand changed, refusing a modified baseline")
assert.equal(address, "1", "Expected test WAN address missing")
}
const config = ixSegmentConfigurationSchema.parse({
name: "ix-acceptance",
sites: [
{ serverId: 501, autonomousSystem: 64512, routerId: net + ".5",
interfaces: [{ name: primary, kind: "wireguard", peerServerId: 502 }, { name: backup, kind: "wireguard", peerServerId: 502 }],
groups: [{ id: "far", gateway, primary: { interface: primary, nextHop: bP, probe: pProbe },
backup: { interface: backup, nextHop: bB, probe: bProbe } }],
neighbors: [{ id: "feed", type: "public-feed", address: bB, localAddress: aB, remoteAs: 64513, binding: backup, rules: [{ community, group: "far" }] }],
},
{ serverId: 502, autonomousSystem: 64513, routerId: net + ".6",
interfaces: [{ name: primary, kind: "wireguard", peerServerId: 501 }, { name: backup, kind: "wireguard", peerServerId: 501 }] },
],
})
const compiled = compileIxConfiguration(id, config)
const deferred = new Set([routePath, "/routing/bgp/instance", "/routing/filter/rule", "/routing/bgp/connection"])
const cleanupPaths = [...deferred].reverse().concat(listPath,
"/interface/wireguard/peers", addressPath, "/ip/firewall/filter", "/ipv6/firewall/filter", "/ip/vrf", "/interface/bridge", "/interface/wireguard")
function clean(side: number) {
const where = `where comment~${quote("^" + ns + ":")}`
cli(side, cleanupPaths.map(path => `${path} remove [${path}/find ${where}]`).join("; "))
assert.equal(cli(side, `:put (${cleanupPaths.map(path => `[:len [${path}/find ${where}]]`).join("+")})`), "0")
preflight(side)
}
function observe() {
return cli(0, `:put [/routing/route/print as-value where dst-address=${quote(target + length)} and routing-table=${quote(ns)}]`)
}
async function until(label: string, check: () => boolean, timeout = 75000) {
const start = Date.now()
while (!check()) {
if (Date.now() - start > timeout) throw new Error(label + " timeout: " + observe())
await delay(900)
}
return Date.now() - start
}
function hasPath(name: string) {
const fields = observe().split(";")
return fields.includes("bgp=true") && fields.includes("active=true") && fields.some(field => field.startsWith("immediate-gw=") && field.endsWith("%" + name))
}
function establishedSession() {
const session = cli(0, `:put [/routing/bgp/session/print as-value where name~${quote(ns + "-feed")}]`).split(";")
assert.ok(session.includes("established=true"))
assert.ok(session.includes("prefix-count=1"))
const started = session.find(field => field.startsWith("last-started="))
assert.ok(started)
return started
}
function packetProbe(destination: string, source?: string, side = 0, routingTable = ns) {
return Number(cli(side, `:put [/ping address=${destination} vrf=${routingTable} count=3 interval=250ms${source ? " src-address=" + source : ""}]`).split(/\r?\n/).at(-1))
}
async function run() {
preflight(0); preflight(1)
for (let side = 0; side < 2; side++) {
entered.add(side)
for (const [index, name] of [primary, backup].entries()) owned(side, "/interface/wireguard", { name, "listen-port": String(port + index), vrf: "main" }, "wg" + index)
for (const object of compiled.filter(object => object.serverId === 501 + side && !deferred.has(object.path))) {
add(side, object.path, object.fields, object.path === "/ip/vrf")
if (object.path === "/ip/vrf") {
flush(side)
await until("VRF interface", () => cli(side, `:put [:len [/interface/find where name=${quote(ns)}]]`) === "1", 9000)
}
}
for (const [index, name] of [primary, backup].entries()) {
owned(side, "/ip/firewall/filter", { chain: "input", action: "accept", protocol: "udp", "src-address": hosts[1 - side] + "/32", "dst-port": String(port + index) }, "allow-wg" + index)
const inner = (side ? [bP, bB] : [aP, aB])[index]
owned(side, addressPath, { address: inner + (ipv6 ? "/64" : "/30"), interface: name, ...advertise }, "address" + index)
}
flush(side)
}
for (const [index, name] of [primary, backup].entries()) {
const keys = [0, 1].map(side => cli(side, `:put [/interface/wireguard/get [/interface/wireguard/find where name=${quote(name)}] public-key]`))
keys.forEach(value => assert.match(value, /^[A-Za-z0-9+/]{43}=$/))
for (const side of [0, 1]) owned(side, "/interface/wireguard/peers", { interface: name, "public-key": keys[1 - side], "endpoint-address": hosts[1 - side],
"endpoint-port": String(port + index), "allowed-address": (side
? [index ? aB : aP, trafficSource]
: [index ? bB : bP, target, index ? bProbe : pProbe]).map(address => address + length).join(","),
"persistent-keepalive": "5" }, "peer" + index)
}
for (const [index, address] of [target, pProbe, bProbe].entries()) {
owned(1, addressPath, { address: address + length, interface: discard, ...advertise }, "destination" + index)
}
owned(0, addressPath, { address: trafficSource + length, interface: discard, ...advertise }, "source")
// Keep the same source and return path across both forward paths.
owned(1, routePath, { "dst-address": trafficSource + length, "routing-table": ns,
gateway: aB + "%" + backup + "@" + ns, "target-scope": "10" }, "return")
const control = { chain: "input", "in-interface": ns, protocol: "tcp", "src-address": aB + length, action: "accept" }
const beforeDeny = " place-before=[" + filterPath + "/find where comment=" + quote(ns + ":deny-input-" + (ipv6 ? "6" : "4")) + "]"
cli(1, [fields({ ...control, "dst-port": "179", comment: marker + ":bgp-accept" }),
fields({ ...control, "src-port": "179", "connection-state": "established", comment: marker + ":bgp-reply" })]
.map(rule => filterPath + " add " + rule + beforeDeny).join("; "))
owned(1, listPath, { list: short + "-net", address: target + length }, "network")
owned(1, "/routing/bgp/instance", { name: ns, as: "64513", "router-id": net + ".6", vrf: ns, "routing-table": ns }, "instance")
owned(1, "/routing/filter/rule", { chain: short + "-out", rule: `if (dst == ${target}${length}) { set bgp-communities ${community}; accept; } reject;` }, "export")
owned(1, "/routing/bgp/connection", { name: short + "-export", instance: ns, afi, "local.role": "ebgp", "local.address": bB,
"remote.address": aB + length, "remote.as": "64512", vrf: ns, "routing-table": ns, "output.network": short + "-net", "output.filter-chain": short + "-out" }, "connection")
for (const object of compiled.filter(object => object.serverId === 501 && deferred.has(object.path))) add(0, object.path, object.fields)
flush(1); flush(0)
await until("primary WireGuard transport", () => packetProbe(bP, aP) === 3, 40000)
await until("backup WireGuard transport", () => packetProbe(bB, aB) === 3, 40000)
await until("BGP primary route", () => hasPath(primary))
const session = establishedSession()
results.bgpEstablished = true
results.primaryRoute = observe()
results.primaryReplies = packetProbe(target, trafficSource)
assert.equal(results.primaryReplies, 3)
assert.equal(cli(0, `:put [:len [/routing/route/find where dst-address=${quote(target + length)} and routing-table=main]]`), "0", "BGP prefix must not leak to main")
results.mainIsolated = true
// Drop only A's test UDP flow on the remote end. Interfaces remain enabled,
// so this exercises probe-driven failover rather than administrative down.
cli(1, "/ip/firewall/filter add " + fields({ chain: "input", action: "drop", protocol: "udp", "src-address": hosts[0] + "/32",
"dst-port": String(port), comment: marker + ":cut" }) + " place-before=[/ip/firewall/filter/find where comment=" + quote(marker + ":allow-wg0") + "]")
results.failoverMs = await until("primary underlay loss", () => hasPath(backup))
results.backupRoute = observe()
results.backupReplies = packetProbe(target, trafficSource)
assert.equal(results.backupReplies, 3)
assert.equal(establishedSession(), session)
cli(1, "/ip/firewall/filter remove [/ip/firewall/filter/find where comment=" + quote(marker + ":cut") + "]")
results.failbackMs = await until("primary recovery", () => hasPath(primary))
results.recoveredReplies = packetProbe(target, trafficSource)
assert.equal(results.recoveredReplies, 3)
assert.equal(establishedSession(), session)
results.bgpSessionKept = true
}
let failure: unknown
try { await run() } catch (error) {
failure = error
for (const side of entered) try {
console.error(`Test CHR ${side + 1} · ${cli(side, `:put [/routing/bgp/session/print as-value];
:put [/interface/wireguard/peers/print as-value proplist=interface,rx,tx,last-handshake,current-endpoint-address where comment~${quote("^" + ns + ":")}];
${filterPath}/print stats where comment~${quote("^" + ns + ":")};
:put [${addressPath}/print as-value proplist=address,interface,invalid where comment~${quote("^" + ns + ":")}];
:put [/routing/route/print as-value where routing-table=${quote(ns)}]; :put [/routing/nexthop/print as-value where address~${quote(gateway)}]`).slice(0, 8500)}`)
} catch { /* Preserve the original failure and continue cleanup. */ }
}
for (const side of entered) {
try { clean(side) } catch (error) {
console.error(`Cleanup unconfirmed on test CHR ${side + 1} for ${ns}: ${error}`)
failure ??= error
}
}
if (failure) {
console.error(JSON.stringify(results))
throw failure
}
console.log(JSON.stringify({ ...results, testStandRestored: true }))
+570
View File
@@ -0,0 +1,570 @@
import assert from "node:assert/strict"
import { createPrivateKey, createPublicKey, randomBytes, randomUUID } from "node:crypto"
import { mkdtemp, writeFile } from "node:fs/promises"
import { createServer, type RequestListener } from "node:http"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { setTimeout as delay } from "node:timers/promises"
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"
import EmbeddedPostgres from "embedded-postgres"
const dir = await mkdtemp(join(tmpdir(), "mm-ix-web-"))
const socket = createServer()
await new Promise<void>(resolve => socket.listen(0, "127.0.0.1", resolve))
const pgPort = (socket.address() as { port: number }).port
await new Promise<void>(resolve => socket.close(() => resolve()))
const password = randomBytes(24).toString("hex")
const pg = new EmbeddedPostgres({ databaseDir: join(dir, "pg"), user: "ixlab", password,
port: pgPort, persistent: false, initdbFlags: ["--encoding=UTF8", "--no-locale"], onLog() {} })
Object.assign(process.env, {
NODE_ENV: "test", DATABASE_URL: `postgres://ixlab:${password}@127.0.0.1:${pgPort}/postgres`,
MCP_STATE_DIR: join(dir, "state"), AUTH_REQUIRED: "true", AUTH_JWT_SECRET: randomBytes(32).toString("hex"),
DATABASE_PATH: join(dir, "no-legacy.sqlite"),
})
await pg.initialise()
await pg.start()
type RouterRows = Record<string, Record<string, string>[]>
const rows: RouterRows = {
"/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }],
"/interface": [{ ".id": "*A0", name: "gre-client", type: "gre", comment: "IX:ix-web-fixture" }],
"/interface/gre": [{ ".id": "*A0", name: "gre-client", "local-address": "192.0.2.20", "remote-address": "192.0.2.21", "allow-fast-path": "false" }],
"/ip/ipsec/policy": [{ ".id": "*A1", "src-address": "192.0.2.20/32", "dst-address": "192.0.2.21/32",
protocol: "gre", action: "encrypt", level: "require", tunnel: "false", disabled: "false" }],
}
let writes = 0
let deletes = 0
let failPutAt = -1
let failDeleteAt = -1
const fixtureHubPublicKey = Buffer.alloc(32, 11).toString("base64")
const serveRouter = (rows: RouterRows): RequestListener => async (request, response) => {
try {
const path = new URL(request.url!, "http://127.0.0.1").pathname.replace(/^\/rest/, "")
let result: unknown
if (request.method === "GET") result = rows[path] ?? []
else if (request.method === "POST" && path === "/interface/print") {
let raw = ""
for await (const chunk of request) raw += chunk
const body = JSON.parse(raw)
assert.equal(body.stats, "")
result = (rows["/interface"] ?? []).map(row => {
const gre = rows["/interface/gre"]?.some(item => item.name === row.name)
return { name: row.name, "rx-byte": gre ? "1536" : "9000", "tx-byte": gre ? "2048" : "8000" }
})
}
else if (request.method === "PUT") {
if (writes === failPutAt) throw Error("Synthetic RouterOS apply failure")
let raw = ""
for await (const chunk of request) raw += chunk
const { "place-before": place, ...fields } = JSON.parse(raw)
const row = { ...fields, ...(path === "/interface/wireguard" && { "public-key": fixtureHubPublicKey }),
".id": "*" + (++writes + 1).toString(16).toUpperCase() }
const list = rows[path] ??= []
const index = list.findIndex(entry => entry[".id"] === place)
list.splice(index < 0 ? list.length : index, 0, row)
if (["/ip/vrf", "/interface/wireguard", "/interface/bridge", "/interface/gre"].includes(path)) {
rows["/interface"].push({ ".id": row[".id"], name: row.name,
type: path === "/interface/wireguard" ? "wg" : path.split("/").at(-1)!, comment: row.comment })
}
result = row
} else if (request.method === "PATCH") {
const parent = path.slice(0, path.lastIndexOf("/"))
const id = decodeURIComponent(path.slice(path.lastIndexOf("/") + 1))
const row = rows[parent]?.find(entry => entry[".id"] === id)
assert(row)
let raw = ""
for await (const chunk of request) raw += chunk
Object.assign(row, JSON.parse(raw))
writes++
result = row
} else if (request.method === "DELETE") {
if (deletes === failDeleteAt) throw Error("Synthetic RouterOS deletion failure")
const parent = path.slice(0, path.lastIndexOf("/"))
const id = decodeURIComponent(path.slice(path.lastIndexOf("/") + 1))
const index = (rows[parent] ?? []).findIndex(row => row[".id"] === id)
assert(index >= 0)
const [deleted] = rows[parent].splice(index, 1)
rows["/interface"] = rows["/interface"].filter(row => row.name !== deleted.name || row[".id"] !== id)
deletes++
response.statusCode = 204
response.end()
return
} else throw Error("Unexpected native verb: " + request.method)
response.setHeader("content-type", "application/json")
response.end(JSON.stringify(result))
} catch (error) {
response.statusCode = 500
response.end(JSON.stringify({ error: String(error) }))
}
}
const router = createServer(serveRouter(rows))
const backupRows: RouterRows = {
"/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }],
"/interface": [{ ".id": "*2", name: "ether1", type: "ether", running: "true" }],
"/ip/address": [{ ".id": "*3", interface: "ether1", address: "198.51.100.20/24" }],
"/ip/route": [{ ".id": "*4", "routing-table": "main", "dst-address": "0.0.0.0/0",
gateway: "198.51.100.1%ether1", "immediate-gw": "198.51.100.1%ether1", active: "true" }],
}
const backupRouter = createServer(serveRouter(backupRows))
const { initDatabase } = await import("../../src/db/bootstrap.js")
const { pool } = await import("../../src/db/index.js")
let app: Awaited<ReturnType<typeof import("../../src/index.js").buildApp>> | undefined
let mcp: Client | undefined
try {
await initDatabase()
assert.equal((await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled, false)
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
const port = (router.address() as { port: number }).port
const { rows: [server] } = await pool.query(`INSERT INTO servers
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
VALUES('owned-ix','127.0.0.1',$1,true,'ix-node','synthetic','synthetic',false,true) RETURNING id`, [port])
const { buildApp } = await import("../../src/index.js")
const { env } = await import("../../src/config.js")
app = await buildApp({ logger: false, startScheduler: false })
const origin = await app.listen({ host: "127.0.0.1", port: 0 })
const token = (owner: string, permission: string) => app!.jwt.sign({ iss: env.authIssuer, sub: owner,
apps: ["mm"], permissions: [permission], iat: Math.floor(Date.now() / 1000) - 1, exp: Math.floor(Date.now() / 1000) + 600 })
const writer = token("ix-web-owner", "mm:network:write")
const reader = token("ix-web-reader", "mm:network:read")
const otherWriter = token("ix-web-other-owner", "mm:network:write")
async function post(path: string, payload: object, status: number, jwt = writer, method = "POST") {
const reply = await fetch(origin + "/api/ix/segments" + path, { method,
headers: { "content-type": "application/json", ...(jwt ? { authorization: "Bearer " + jwt } : {}) },
body: JSON.stringify(payload), signal: AbortSignal.timeout(30_000) })
const data = reply.status === 204 ? undefined : await reply.json()
assert.equal(reply.status, status, JSON.stringify(data))
return data
}
const configuration = { name: "ix-web-fixture", sites: [{ serverId: Number(server.id),
autonomousSystem: 64512, routerId: "192.0.2.5", interfaces: [{ name: "wg-ix-web", kind: "wireguard",
prefixes: ["2001:db8:12::/48"], provisionWireguard: { peerPublicKey: "A".repeat(43) + "=",
listenPort: 51820, localAddress: "10.20.30.1/30", peerAddress: "10.20.30.2", hubEndpoint: "192.0.2.20" } },
{ name: "gre-client", kind: "gre-ipsec", localEndpoint: "192.0.2.20", endpoint: "192.0.2.21" }] }] }
const { segment } = await post("", { revision: 0, configuration }, 200)
assert.equal(segment.revision, 1)
assert.equal(segment.appliedRevision, null)
const path = "/" + segment.id
const linux = async (name?: string, status = 200) => {
const query = name ? "?" + new URLSearchParams({ serverId: String(server.id), interfaceName: name }) : ""
const response = await fetch(origin + "/api/ix/segments" + path + "/linux" + query, { headers: { authorization: "Bearer " + reader } })
const body = await response.json()
assert.equal(response.status, status, JSON.stringify(body))
return body
}
assert.deepEqual(await linux(), { revision: null, items: [] })
const { digest, changes } = await post(path + "/plan", { revision: 1 }, 200)
assert(changes.some((step: { path: string }) => step.path === "/interface/wireguard/peers"))
await post(path + "/apply", { revision: 1, digest }, 401, "")
await post(path + "/apply", { revision: 1, digest }, 403, reader)
await post(path + "/apply", { revision: 1, digest }, 409, otherWriter)
await post(path + "/apply", { revision: 1, digest: "0".repeat(64) }, 409)
rows["/interface"].push({ ".id": "*F0", name: "test-drift", type: "ether" })
await post(path + "/apply", { revision: 1, digest }, 409)
assert.equal(writes, 0)
const fresh = await post(path + "/plan", { revision: 1 }, 200)
await post(path + "/plan", { revision: 1, resume: true }, 409)
const protectionId = randomUUID()
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES ($1,$2,'ix-web-owner')",
[protectionId, { kind: "server", id: String(server.id), protection: "deny" }])
await post(path + "/apply", { revision: 1, digest: fresh.digest }, 409)
assert.equal(writes, 0)
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protectionId])
failPutAt = 1
await post(path + "/apply", { revision: 1, digest: fresh.digest }, 503)
assert.equal(writes, 1)
await post(path + "/plan", { revision: 1 }, 409)
failPutAt = -1
const resume = await post(path + "/plan", { revision: 1, resume: true }, 200)
assert.equal(resume.changes.length, changes.length - 1)
const applied = await post(path + "/apply", { revision: 1, digest: resume.digest, resume: true }, 200)
assert.equal(applied.segment.appliedRevision, 2)
assert.equal(applied.result.configurationVerified, true)
assert.equal(applied.result.forwardingVerified, false)
const resultWrites = writes
assert.equal(resultWrites, changes.length)
const clients = await linux()
assert.equal(clients.revision, 2)
assert.deepEqual(clients.items.map((item: { kind: string }) => item.kind), ["wireguard", "gre-ipsec"])
const wg = await linux("wg-ix-web")
assert.match(wg.template, /Endpoint = 192\.0\.2\.20:51820/)
assert.match(wg.template, /Table = off/)
assert(!wg.template.includes("A".repeat(43)))
await post(path + "/linux/credential", { serverId: Number(server.id), interfaceName: "wg-ix-web" }, 404)
const gre = await linux("gre-client")
assert.match(gre.template, /local_ts = 192\.0\.2\.21\/32\[47\]/)
assert.match(gre.template, /remote_ts = 192\.0\.2\.20\/32\[47\]/)
assert.match(gre.template, /mode = transport/)
assert.match(gre.setup, /mode gre local 192\.0\.2\.21 remote 192\.0\.2\.20/)
rows["/ip/ipsec/policy"][0].disabled = "true"
await linux("gre-client", 409)
rows["/ip/ipsec/policy"][0].disabled = "false"
rows["/interface/wireguard/peers"][0].disabled = "true"
await linux("wg-ix-web", 409)
delete rows["/interface/wireguard/peers"][0].disabled
await post(path + "/apply", { revision: 1, digest: fresh.digest }, 409)
assert.equal(writes, resultWrites)
const next = await post("", { id: segment.id, revision: 2, configuration: { ...configuration,
sites: [{ ...configuration.sites[0], discardNetworks: ["2001:db8:ff::/48"] }] } }, 200)
assert.equal(next.segment.appliedRevision, 2)
assert.equal((await linux("wg-ix-web")).revision, 2)
const members = rows["/interface/list/member"]
members.push({ ".id": "*FE", list: rows["/interface/list"][0].name, interface: "test-drift" })
const foreign = await post(path + "/plan", { revision: 3 }, 409)
assert.match(foreign.error, /посторонний интерфейс/)
members.pop()
const nextPlan = await post(path + "/plan", { revision: 3 }, 200)
await post(path + "/apply", { revision: 3, digest: nextPlan.digest }, 200)
assert(rows["/ipv6/route"].some(row => row["dst-address"] === "2001:db8:ff::/48"))
const { rows: [audit] } = await pool.query(`SELECT count(*)::int AS n FROM mcp_audit
WHERE actor_id='ix-web-owner' AND action='configuration.acknowledged' AND connection_id IS NULL`)
assert.equal(audit.n, writes)
const { rows: [connections] } = await pool.query("SELECT count(*)::int AS n FROM mcp_connections")
assert.equal(connections.n, 0)
const draftConfig = { ...configuration, name: "ix-web-draft" }
const draft = (await post("", { revision: 0, configuration: draftConfig }, 200)).segment
const draftPath = "/" + draft.id
const draftRemoval = await post(draftPath + "/removal-plan", { revision: 1 }, 200)
assert.deepEqual(draftRemoval.changes, [])
const deleteDraft = { revision: 1, digest: draftRemoval.digest }
await post(draftPath, deleteDraft, 403, reader, "DELETE")
await post(draftPath, deleteDraft, 409, otherWriter, "DELETE")
await post(draftPath, deleteDraft, 204, writer, "DELETE")
assert.equal(deletes, 0)
await post(draftPath, deleteDraft, 404, writer, "DELETE")
const recreated = (await post("", { revision: 0, configuration: draftConfig }, 200)).segment
const removalInput = { revision: 4 }
const blocked = await post(path + "/removal-plan", removalInput, 409)
assert.match(blocked.error, /Отключите интерфейс.*gre-client/)
rows["/interface"].find(row => row.name === "gre-client")!.disabled = "true"
rows["/ip/address"].push({ ".id": "*FE", interface: "wg-ix-web", address: "192.0.2.1/32" })
assert.match((await post(path + "/removal-plan", removalInput, 409)).error, /нет в применённой ревизии/)
rows["/ip/address"].pop()
const removal = await post(path + "/removal-plan", removalInput, 200)
assert.equal(removal.changes.length, writes)
assert(removal.changes.every((change: { action: string }) => change.action === "delete"))
failDeleteAt = 1
await post(path, { ...removalInput, digest: removal.digest }, 503, writer, "DELETE")
assert.equal(deletes, 1)
assert.equal((await pool.query("SELECT configuration->>'deleted' AS deleted FROM ix_segments WHERE id=$1", [segment.id])).rows[0].deleted, null)
await post(path, { ...removalInput, digest: removal.digest }, 409, writer, "DELETE")
failDeleteAt = -1
const remaining = await post(path + "/removal-plan", removalInput, 200)
assert.equal(remaining.changes.length, removal.changes.length - 1)
await post(path, { ...removalInput, digest: remaining.digest }, 204, writer, "DELETE")
assert.equal(deletes, writes)
assert.equal(rows["/ip/ipsec/policy"].length, 1)
assert.deepEqual(rows["/interface"].map(row => row.name), ["gre-client", "test-drift"])
const { rows: [archive] } = await pool.query(`SELECT s.configuration->>'deleted' AS deleted,
(SELECT count(*)::int FROM ix_segment_revisions WHERE segment_id=s.id) AS revisions,
(SELECT count(*)::int FROM ix_segment_devices WHERE segment_id=s.id) AS devices
FROM ix_segments s WHERE id=$1`, [segment.id])
assert.deepEqual(archive, { deleted: "true", revisions: 4, devices: 0 })
const listReply = await fetch(origin + "/api/ix/segments", { headers: { authorization: "Bearer " + reader } })
assert.equal(listReply.status, 200)
assert.deepEqual((await listReply.json()).items.map((item: { configuration: { name: string } }) => item.configuration.name), [draftConfig.name])
process.env.MCP_PUBLIC_URL = origin + "/mcp"
const ownerPermissions = ["mm:network:write", "mm:network:read", "mm:mcp:admin", "mm:mcp:approve"]
const issuedAt = Math.floor(Date.now() / 1000) - 1
const ownerId = "ix-mcp-owner"
const mcpJwt = app.jwt.sign({ iss: env.authIssuer, sub: ownerId, apps: ["mm"], permissions: ownerPermissions, iat: issuedAt, exp: issuedAt + 600 })
const { updateMcpSettings } = await import("../../src/modules/mcp/store.js")
await updateMcpSettings({ enabled: true }, { id: ownerId, email: "[email protected]", name: "IX acceptance", apps: ["mm"],
permissions: ownerPermissions, issuedAt: issuedAt * 1000, expiresAt: (issuedAt + 600) * 1000 })
async function mcpPost(path: string, body: object) {
const reply = await fetch(origin + "/api/mcp/" + path, { method: "POST",
headers: { authorization: "Bearer " + mcpJwt, "content-type": "application/json" }, body: JSON.stringify(body) })
const data = await reply.json()
assert(reply.ok, JSON.stringify(data))
return data
}
const { token: mcpToken } = await mcpPost("connections", { name: "IX removal acceptance", mode: "approval",
permissions: ["mm:network:write", "mm:network:read"], expiresAt: new Date(Date.now() + 300_000).toISOString(),
scope: { allowGlobal: false, serverIds: [Number(server.id)], operationIds: ["network.ix.delete", "network.wireguard.export", "changes.apply", "operations.read"] } })
mcp = new Client({ name: "ix-removal-acceptance", version: "1.0.0" })
await mcp.connect(new StreamableHTTPClientTransport(new URL(origin + "/mcp"),
{ requestInit: { headers: { authorization: "Bearer " + mcpToken } } }))
async function call<T>(name: string, args: object, error = false) {
const reply = await mcp!.callTool({ name, arguments: args })
assert.equal(Boolean(reply.isError), error, JSON.stringify(reply.structuredContent ?? reply.content))
return (reply.structuredContent as { result: T } | undefined)?.result as T
}
const mcpPlan = await call<{ planId: string; state: string }>(
"mm_ix_delete_plan", { id: recreated.id, revision: 1 })
assert.equal(mcpPlan.state, "awaiting-approval")
const mcpApply = { planId: mcpPlan.planId, idempotencyKey: randomUUID() }
await call("mm_change_apply", mcpApply, true)
await mcpPost("plans/" + mcpPlan.planId + "/decision", { approve: true })
type Operation = { id: string; state: string; verification: string }
const operation = await call<Operation>("mm_change_apply", mcpApply)
let terminal = operation
for (let attempts = 0; attempts < 30 && ["pending", "running"].includes(terminal.state); attempts++) {
await delay(200)
terminal = await call<Operation>("mm_operation_get", { operationId: operation.id })
}
assert.equal(terminal.state, "applied", JSON.stringify(terminal))
assert.equal(terminal.verification, "passed")
assert.equal(deletes, writes)
const managed = (await post("", { revision: 0, configuration: { name: "ix-web-managed", sites: [
{ serverId: Number(server.id), autonomousSystem: 64512, routerId: "192.0.2.6" },
] } }, 200)).segment
const managedPath = "/" + managed.id
rows["/interface"].push({ ".id": "*FA", name: "ether1", type: "ether", running: "true" })
;(rows["/ip/address"] ??= []).push(
{ ".id": "*FB", interface: "ether1", address: "192.0.2.20/24" },
{ ".id": "*FC", interface: "ether1", address: "192.0.2.30/24" },
)
;(rows["/ip/route"] ??= []).push({ ".id": "*FD", "routing-table": "main", "dst-address": "0.0.0.0/0",
gateway: "192.0.2.1%ether1", "immediate-gw": "192.0.2.1%ether1", active: "true" })
const clientInput = { serverId: Number(server.id), name: "linux-auto", kind: "wireguard", hubEndpoint: "192.0.2.20",
peerEndpoint: "192.0.2.40", exit: "local-wan", prefixes: [], destinations: ["203.0.113.0/24"], enabled: true }
const staged = await post(managedPath + "/linux", { ...clientInput, revision: managed.revision }, 200)
assert.match(staged.interfaceName, /^il-wg-[a-z0-9-]+-[0-9a-f]{12}$/)
assert.ok(staged.segment.configuration.sites[0].interfaces[0].linux.clientId)
const clientKey = { serverId: clientInput.serverId, interfaceName: staged.interfaceName }
await post(managedPath + "/linux/credential", clientKey, 409)
await post(managedPath + "/linux/credential", clientKey, 403, reader)
const edited = await post(managedPath + "/linux", { ...clientInput, ...clientKey, revision: staged.segment.revision, name: "linux-renamed" }, 200)
const provision = edited.segment.configuration.sites[0].interfaces[0].provisionWireguard
assert.deepEqual(provision, staged.segment.configuration.sites[0].interfaces[0].provisionWireguard)
const plan = await post(managedPath + "/plan", { revision: edited.segment.revision }, 200)
await post(managedPath + "/apply", { revision: edited.segment.revision, digest: plan.digest }, 200)
const credential = await post(managedPath + "/linux/credential", clientKey, 200)
const privateKey = credential.template.match(/^PrivateKey = ([A-Za-z0-9+/]{43}=)$/m)?.[1]
assert.ok(privateKey)
const scalar = Buffer.from(privateKey, "base64")
const key = createPrivateKey({ key: Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar]),
format: "der", type: "pkcs8" })
const publicKey = createPublicKey(key).export({ format: "der", type: "spki" }).subarray(-32).toString("base64")
assert.equal(publicKey, provision.peerPublicKey)
assert.equal(rows["/interface/wireguard/peers"].find(row => row.interface === clientKey.interfaceName)?.["public-key"], publicKey)
assert(!JSON.stringify([edited, plan, rows]).includes(privateKey))
const templateResponse = await fetch(origin + "/api/ix/segments" + managedPath + "/linux?" + new URLSearchParams({
serverId: String(clientKey.serverId), interfaceName: clientKey.interfaceName,
}), { headers: { authorization: "Bearer " + reader } })
assert.equal(templateResponse.status, 200)
assert.match((await templateResponse.json()).template, /PrivateKey = <локальный_приватный_ключ>/)
const exportPlan = await call<{ planId: string; state: string }>("mm_wireguard_export_plan",
{ ...clientKey, ixSegmentId: managed.id, format: "peer-conf" })
assert.equal(exportPlan.state, "awaiting-approval")
assert(!JSON.stringify(exportPlan).includes(privateKey))
await mcpPost("plans/" + exportPlan.planId + "/decision", { approve: true })
const exportOperation = await call<Operation>("mm_change_apply", { planId: exportPlan.planId, idempotencyKey: randomUUID() })
let exported = exportOperation
for (let attempts = 0; attempts < 50 && ["pending", "running"].includes(exported.state); attempts++) {
await delay(200)
exported = await call<Operation>("mm_operation_get", { operationId: exportOperation.id })
}
assert.equal(exported.state, "applied", JSON.stringify(exported))
assert(!JSON.stringify(exported).includes(privateKey))
const { rows: [{ result: receipt }] } = await pool.query("SELECT result FROM mcp_operation_steps WHERE operation_id=$1", [exported.id])
assert.equal(receipt.humanDownloadOnly, true)
const secretRecords = await pool.query(`SELECT to_jsonb(s) AS record FROM mcp_operation_steps s WHERE operation_id=$1
UNION ALL SELECT to_jsonb(p) FROM mcp_plans p WHERE id=$2
UNION ALL SELECT to_jsonb(a) FROM mcp_artifacts a WHERE id=$3
UNION ALL SELECT to_jsonb(a) FROM mcp_audit a WHERE actor_id IN ('ix-web-owner','ix-mcp-owner')`,
[exported.id, exportPlan.planId, receipt.artifactId])
assert(!JSON.stringify(secretRecords.rows).includes(privateKey))
const download = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + mcpJwt } })
assert.equal(download.status, 200)
assert.equal(await download.text(), credential.template)
assert.equal(download.headers.get("cache-control"), "private, no-store")
const denied = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + otherWriter } })
assert.equal(denied.status, 403)
const appliedPeer = rows["/interface/wireguard/peers"].find(row => row.interface === clientKey.interfaceName)!
appliedPeer.disabled = "true"
const inactive = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + mcpJwt } })
assert.equal(inactive.status, 409)
delete appliedPeer.disabled
const companionInput = { ...clientInput, kind: "gre-ipsec", companionOf: clientKey.interfaceName }
const canceled = await post(managedPath + "/linux", { ...companionInput, revision: credential.revision }, 200)
const canceledKey = { serverId: clientKey.serverId, interfaceName: canceled.interfaceName }
const reverted = await post(managedPath + "/linux/revoke", { ...canceledKey, revision: canceled.segment.revision }, 200)
const noChanges = await post(managedPath + "/plan", { revision: reverted.segment.revision }, 200)
assert.deepEqual(noChanges.changes, [])
const resumed = await post(managedPath + "/apply", { revision: reverted.segment.revision, digest: noChanges.digest }, 200)
const paired = await post(managedPath + "/linux", { ...companionInput, revision: resumed.segment.revision }, 200)
const bindings = paired.segment.configuration.sites[0].interfaces
const [wireguard, greBinding] = bindings
assert.match(greBinding.name, /^il-gre-[a-z0-9-]+-[0-9a-f]{12}$/)
assert.ok(wireguard.linux.clientId)
const original = resumed.segment.configuration.sites[0].interfaces[0]
assert.deepEqual(wireguard, { ...original, linux: { ...original.linux, clientId: wireguard.linux.clientId } })
assert.equal(wireguard.linux.clientId, greBinding.linux.clientId)
assert.notEqual(wireguard.provisionWireguard.peerAddress, greBinding.provisionGre.peerAddress)
const foreignRoute = { ".id": "*FE", "routing-table": "main", "dst-address": "198.51.100.0/24",
gateway: "10.254.0.2%" + clientKey.interfaceName }
rows["/ip/route"].push(foreignRoute)
const blockedForeign = await post(managedPath + "/plan", { revision: paired.segment.revision }, 409)
assert.match(blockedForeign.error, /другой маршрутизацией/)
assert.equal(rows["/ip/route"].pop(), foreignRoute)
const pairPlan = await post(managedPath + "/plan", { revision: paired.segment.revision }, 200)
assert(!pairPlan.changes.some(change => change.path.startsWith("/interface/wireguard")))
const pairedApplied = await post(managedPath + "/apply", { revision: paired.segment.revision, digest: pairPlan.digest }, 200)
const countersResponse = await fetch(origin + "/api/ix/segments" + managedPath + "/linux", { headers: { authorization: "Bearer " + reader } })
assert.equal(countersResponse.status, 200)
const observedGre = (await countersResponse.json()).items.find(item => item.interfaceName === greBinding.name)
assert.equal(observedGre.connection.rx, "1536")
assert.equal(observedGre.connection.tx, "2048")
const pairVrf = rows["/ip/vrf"].find(row => row.interfaces?.includes(wireguard.name))!
assert(pairVrf.interfaces.split(",").includes(greBinding.name))
const greCredential = await post(managedPath + "/linux/credential",
{ serverId: clientKey.serverId, interfaceName: paired.interfaceName }, 200)
assert.match(greCredential.template, /secret = "[a-f0-9]{64}"/)
assert.match(greCredential.setup, /install -m 0600 "\$conf" \/etc\/swanctl\/conf\.d\//)
assert.match(greCredential.setup, /ip -4 rule add pref \d+ from 192\.0\.2\.40\/32 lookup main/)
assert.match(greCredential.setup, /ip -4 route replace default dev ixg\w+ src \S+ table \d+/)
assert(greCredential.setup.indexOf(" lookup main\n") < greCredential.setup.indexOf("swanctl --initiate"))
assert.equal((await post(managedPath + "/linux/credential", clientKey, 200)).template, credential.template)
const bondPath = managedPath + "/linux-bonds"
const bondInput = { revision: 0, name: "mixed", mode: "weighted", directCidrs: ["192.0.2.0/24"],
members: [wireguard, greBinding].map((binding, i) => ({ segmentId: managed.id, serverId: clientKey.serverId,
interfaceName: binding.name, weight: i ? 1 : 3, appliedRevision: pairedApplied.segment.revision })) }
await post(bondPath, bondInput, 403, reader)
const bond = await post(bondPath, bondInput, 200)
assert.equal(bond.clientId, wireguard.linux.clientId)
await post(bondPath, bondInput, 409)
const bundlePath = bondPath + "/" + bond.id + "/export"
const bundle = await post(bundlePath, { revision: 1 }, 200)
assert.deepEqual(bundle.members.map(member => [member.kind, member.weight]), [["wireguard", 3], ["gre-ipsec", 1]])
assert.equal(bundle.members[0].peerPublicKey, fixtureHubPublicKey)
assert.deepEqual(bundle.destinations, ["0.0.0.0/0"])
assert(!JSON.stringify(bundle).includes(privateKey))
if (process.env.IX_BOND_TEST_EXPORT) {
await writeFile(process.env.IX_BOND_TEST_EXPORT, JSON.stringify(bundle, null, 2) + "\n", { flag: "wx" })
}
await post(bundlePath, { revision: 1 }, 403, reader)
await post(managedPath + "/removal-plan", { revision: pairedApplied.segment.revision }, 409)
const { rows: [exit] } = await pool.query(`INSERT INTO servers
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
VALUES('owned-exit','127.0.0.1',$1,true,'exit-node','synthetic','synthetic',false,true) RETURNING id`, [port])
const transit = { targetServerId: Number(exit.id), localEndpoint: "192.0.2.20", remoteEndpoint: "192.0.2.30", family: 4, name: "remote-exit" }
const appliedRevision = pairedApplied.segment.revision
const remoteClient = { ...clientInput, name: "linux-remote", revision: appliedRevision, exit: undefined, transit }
const beforeStage = writes
await post(managedPath + "/linux", { ...remoteClient, localAddress: "10.254.21.1/30" }, 400)
const stagedRemote = await post(managedPath + "/linux", remoteClient, 200)
assert(!Object.hasOwn(stagedRemote.segment.configuration, "linuxBonds"))
assert.deepEqual(await post(bundlePath, { revision: 1 }, 200), bundle)
const racing = await Promise.all(["equal", "failover"].map(mode => fetch(origin + "/api/ix/segments" + bondPath, {
method: "POST", headers: { authorization: "Bearer " + writer, "content-type": "application/json" },
body: JSON.stringify({ ...bondInput, id: bond.id, revision: 1, mode }),
})))
assert.deepEqual(racing.map(r => r.status).sort(), [200, 409])
const revised = await racing.find(r => r.ok)!.json()
assert.equal(revised.revision, 2)
await post(bundlePath, { revision: 1 }, 409)
await post(bondPath + "/" + bond.id, { revision: 2 }, 204, writer, "DELETE")
await post(bundlePath, { revision: 2 }, 409)
assert.equal(writes, beforeStage)
assert.equal(stagedRemote.segment.revision, appliedRevision + 1)
assert.equal(stagedRemote.segment.appliedRevision, appliedRevision)
const remoteSite = stagedRemote.segment.configuration.sites[0]
assert.equal(remoteSite.interfaces.find(row => row.name === stagedRemote.interfaceName).linux.exit, transit.name)
const transitBinding = remoteSite.interfaces.find(row => row.name === remoteSite.groups.find(group => group.id === transit.name).primary.interface)
assert.equal(transitBinding.peerServerId, Number(exit.id))
const { ixReservedTunnelBindings } = await import("../../src/services/internet-exchange-store.js")
assert((await ixReservedTunnelBindings(Number(exit.id))).some(binding => binding.name === transitBinding.name))
const remotePlan = await post(managedPath + "/plan", { revision: stagedRemote.segment.revision }, 200)
assert(remotePlan.changes.some(change => change.serverId === Number(exit.id) &&
change.path === "/ip/firewall/nat" && change.fields["out-interface"] === "ether1"))
assert(remotePlan.changes.some(change => change.serverId === Number(server.id) && change.path === "/interface/wireguard"))
assert.equal(writes, beforeStage)
const both = await post(managedPath + "/linux", { ...clientInput, name: "both", peerEndpoint: "192.0.2.41",
revision: stagedRemote.segment.revision, additionalGre: true }, 200)
const added = both.segment.configuration.sites[0].interfaces.filter(binding => binding.linux?.name === "both")
assert.deepEqual(added.map(binding => binding.kind), ["wireguard", "gre-ipsec"])
assert.ok(added[0].linux.clientId)
assert.equal(added[0].linux.clientId, added[1].linux.clientId)
await new Promise<void>(resolve => backupRouter.listen(0, "127.0.0.1", resolve))
const { rows: [secondIx] } = await pool.query(`INSERT INTO servers
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
VALUES('owned-bond-peer','127.0.0.1',$1,true,'ix-node','synthetic','synthetic',false,true) RETURNING id`,
[(backupRouter.address() as { port: number }).port])
const secondSegment = (await post("", { revision: 0, configuration: { name: "ix-web-bond-peer", sites: [
{ serverId: Number(secondIx.id), autonomousSystem: 64513, routerId: "192.0.2.8" },
] } }, 200)).segment
const secondPath = "/" + secondSegment.id
const secondInput = { ...clientInput, hubEndpoint: "198.51.100.20", serverId: Number(secondIx.id), revision: secondSegment.revision }
await post(secondPath + "/linux", { ...secondInput, vpsClientId: randomUUID() }, 409)
const existingPair = await post(secondPath + "/linux", { ...secondInput, additionalGre: true }, 200)
const initialPairPlan = await post(secondPath + "/plan", { revision: existingPair.segment.revision }, 200)
const appliedPair = (await post(secondPath + "/apply", { revision: existingPair.segment.revision, digest: initialPairPlan.digest }, 200)).segment
const [oldWg, oldGre] = appliedPair.configuration.sites[0].interfaces
assert.notEqual(oldWg.linux.clientId, bond.clientId)
const changeIdentity = { ...secondInput, interfaceName: oldWg.name, vpsClientId: bond.clientId, revision: appliedPair.revision }
const secondWg = await post(secondPath + "/linux", changeIdentity, 200)
const newTunnel = secondWg.segment.configuration.sites[0].interfaces[0]
assert.deepEqual(newTunnel, { ...oldWg, linux: { ...oldWg.linux, clientId: bond.clientId } })
assert.deepEqual(secondWg.segment.configuration.sites[0].interfaces[1], oldGre)
assert.notEqual(newTunnel.provisionWireguard.peerAddress, wireguard.provisionWireguard.peerAddress)
const secondaryPlan = await post(secondPath + "/plan", { revision: secondWg.segment.revision }, 200)
assert.deepEqual(secondaryPlan.changes, [])
const secondaryApplied = (await post(secondPath + "/apply", { revision: secondWg.segment.revision, digest: secondaryPlan.digest }, 200)).segment
const cross = await post(bondPath, { ...bondInput, members: [bondInput.members[0], {
segmentId: secondSegment.id, appliedRevision: secondaryApplied.revision, serverId: secondInput.serverId, interfaceName: secondWg.interfaceName, weight: 1,
}] }, 200)
await post(secondPath + "/removal-plan", { revision: secondaryApplied.revision }, 409)
const groupedChange = await post(secondPath + "/linux", { ...changeIdentity, vpsClientId: oldGre.linux.clientId, revision: secondaryApplied.revision }, 409)
assert.match(groupedChange.error, /исключите подключение/)
const crossBundle = await post(bondPath + "/" + cross.id + "/export", { revision: 1 }, 200)
assert.equal(crossBundle.members[1].address, newTunnel.provisionWireguard.peerAddress)
await post(bondPath + "/" + cross.id, { revision: 1 }, 204, writer, "DELETE")
const ownPublicKey = Buffer.alloc(32, 29).toString("base64")
const manualVrf = backupRows["/ip/vrf"]
const manualGrePolicy = { "src-address": "198.51.100.20/32", "dst-address": "192.0.2.22/32", protocol: "gre", action: "encrypt", level: "require", tunnel: "false" }
backupRows["/interface/wireguard"].push({ name: "pre-wg", "public-key": fixtureHubPublicKey })
backupRows["/interface/wireguard/peers"].push({ interface: "pre-wg", "public-key": ownPublicKey, "allowed-address": "10.7.0.2/32" })
backupRows["/interface/gre"].push({ name: "pre-gre", "local-address": "198.51.100.20", "remote-address": "192.0.2.22", "allow-fast-path": "false" })
backupRows["/ip/ipsec/policy"].push(manualGrePolicy)
backupRows["/ip/address"].push({ interface: "pre-wg", address: "10.7.0.1/30" }, { interface: "pre-gre", address: "10.8.0.1/30" })
const refs = ["pre-wg", "pre-gre"].map((interfaceName, i) => ({ interfaceName, segmentId: secondSegment.id, serverId: secondInput.serverId,
appliedRevision: secondaryApplied.revision, weight: 1, existing: { linuxInterface: i ? "gre-manual" : "wg0", address: "10." + (7 + i) + ".0.2",
probe: "10." + (7 + i) + ".0.1", endpoint: "198.51.100.20", destinations: ["10.250.0.0/24"],
...(i ? { kind: "gre-ipsec", remoteEndpoint: "192.0.2.22" } : { kind: "wireguard", clientPublicKey: ownPublicKey }) } }))
const manualPath = secondPath + "/linux-bonds"
const manualInput = { ...bondInput, name: "existing", members: refs }
const beforeManual = JSON.stringify(backupRows)
const writesBeforeManual = writes
await post(manualPath, manualInput, 403, reader)
await post(manualPath, { ...manualInput, members: [{ ...refs[0], existing: { ...refs[0].existing, clientPublicKey: fixtureHubPublicKey } }, refs[1]] }, 409)
manualVrf.unshift({ name: "another-vrf", interfaces: "pre-wg" })
await post(manualPath, manualInput, 409)
manualVrf.shift()
const manual = await post(manualPath, manualInput, 200)
const manualExport = manualPath + "/" + manual.id + "/export"
const result = await post(manualExport, { revision: 1 }, 200)
assert.deepEqual(result.members.map(p => p.interfaceName), ["wg0", "gre-manual"])
assert.equal(result.members[0].peerPublicKey, fixtureHubPublicKey)
manualGrePolicy.level = "use"
await post(manualExport, { revision: 1 }, 409)
manualGrePolicy.level = "require"
await post(manualPath + "/" + manual.id, { revision: 1 }, 204, writer, "DELETE")
assert.equal(writes, writesBeforeManual)
assert.equal(JSON.stringify(backupRows), beforeManual)
await post(secondPath + "/removal-plan", { revision: secondaryApplied.revision }, 200)
console.log(JSON.stringify({ appliedRevisions: [2, 4], writes, audit: audit.n, mcpConnections: connections.n,
unauthenticated: 401, readOnly: 403, ownerMismatch: 409, drift: 409, replay: 409, protected: 409, linuxClients: clients.items.length,
deletedDraft: true, removedNativeObjects: deletes, revisionsRetained: archive.revisions,
mcpRemovalVerified: true, managedWireguardVerified: true, clientWithTransitStagedAtomically: true, bothProtocolsInOneVrf: true,
mixedBondExport: true, crossSegmentBond: true, concurrentBondEdits: true, existingRouterOsTunnels: true }))
} finally {
await mcp?.close()
await app?.close()
await new Promise<void>(resolve => router.close(() => resolve()))
if (backupRouter.listening) await new Promise<void>(resolve => backupRouter.close(() => resolve()))
await pool.end()
await pg.stop()
}
// As in the MCP integration suite, close the standalone runner after teardown and log flushing.
process.stderr.write("", () => process.stdout.write("", () => process.exit()))
@@ -0,0 +1,97 @@
import assert from "node:assert/strict"
import { mkdtemp, readdir, readFile } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join, resolve } from "node:path"
import { createServer } from "node:net"
import { randomBytes } from "node:crypto"
import EmbeddedPostgres from "embedded-postgres"
import { FIXED59_IX_DELTA } from "../writer-profile/fixed59-ix-delta.js"
import { canonical } from "../writer-profile/application-writer-profile-canonical.js"
import { ixWriterProfileEnrollmentSql } from "../../src/db/internet-exchange-writer-profile.js"
import { FIXED44_CATALOGUE_BUILD_SQL } from "../writer-profile/fixed44-build-sql.js"
import { CatalogueValueStream } from "../writer-profile/application-writer-profile-catalogue-values.js"
import { projectCatalogueData, GROUPS, sorted, type Inventory, type Row } from "../writer-profile/catalogue-projection.js"
const root = await mkdtemp(join(tmpdir(), "mmapp-ix-profile-"))
assert.equal(resolve(root, ".."), resolve(tmpdir()))
const listener = createServer()
await new Promise<void>((done, reject) => listener.listen(0, "127.0.0.1", done).on("error", reject))
const port = (listener.address() as { port: number }).port
await new Promise<void>((done, reject) => listener.close(error => error ? reject(error) : done()))
const app = new EmbeddedPostgres({ databaseDir: root, user: "ixlab", password: randomBytes(24).toString("hex"),
port, persistent: false, createPostgresUser: false, initdbFlags: ["--encoding=UTF8", "--no-locale"],
postgresFlags: ["-h", "127.0.0.1", "-c", "jit=off"], onLog: () => {}, onError: () => {} })
const roles = ["ix_operator", "ix_runtime", "ix_capture", "ix_publisher", "ix_control"]
const tables = ["ix_segments", "ix_segment_devices", "ix_segment_revisions"]
console.log("Initialising disposable PostgreSQL")
await app.initialise()
console.log("Starting disposable PostgreSQL")
await app.start()
const db = app.getPgClient("postgres", "127.0.0.1")
try {
await db.connect()
console.log("Applying pinned migrations in the fixture")
await db.query("CREATE TABLE schema_migrations(id text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())")
const directory = resolve("backend/drizzle")
for (const name of (await readdir(directory)).filter(name => name.endsWith(".sql")).sort()) {
await db.query(await readFile(join(directory, name), "utf8"))
await db.query("INSERT INTO schema_migrations(id) VALUES ($1) ON CONFLICT DO NOTHING", [name.slice(0,-4)])
}
for (const role of roles) await db.query("CREATE ROLE " + role)
await db.query("CREATE SCHEMA IF NOT EXISTS mmapp_control; CREATE FUNCTION mmapp_control.candidate_truncate_preadmitted() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RETURN NULL; END; $$")
for (const name of tables) await db.query("ALTER TABLE public." + name + " OWNER TO ix_operator")
await db.query("GRANT USAGE ON SCHEMA mmapp_control TO ix_operator; GRANT EXECUTE ON FUNCTION mmapp_control.candidate_truncate_preadmitted() TO ix_operator")
await db.query("BEGIN; SET LOCAL ROLE ix_operator")
await db.query(ixWriterProfileEnrollmentSql("ix_runtime", "ix_capture"))
await db.query("COMMIT")
const insert = "INSERT INTO ix_segments(id,name,revision,configuration) VALUES ('8dd5d978-83ac-4343-8cff-16655a0a77a7','fixture',1,'{}')"
const maintenance = app.getPgClient("postgres", "127.0.0.1")
await maintenance.connect()
try {
await maintenance.query("SELECT pg_advisory_lock(8723110::bigint)")
await db.query("BEGIN; SET LOCAL ROLE ix_runtime; SET LOCAL lock_timeout='250ms'")
await assert.rejects(db.query(insert), { code: "55P03" })
await db.query("ROLLBACK")
} finally {
await maintenance.end()
}
await db.query("BEGIN; SET LOCAL ROLE ix_runtime; SELECT pg_advisory_xact_lock_shared(8723110::bigint)")
await db.query(insert)
await db.query("INSERT INTO ix_segment_revisions(segment_id,revision,configuration,actor_id) VALUES ('8dd5d978-83ac-4343-8cff-16655a0a77a7',1,'{}','fixture')")
await assert.rejects(db.query("UPDATE ix_segment_revisions SET actor_id='other'"), { code: "42501" })
await db.query("ROLLBACK")
console.log("Capturing exact IX catalogue rows")
await db.query("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY; SET LOCAL search_path=pg_catalog,public; SET LOCAL TimeZone='UTC'; SET LOCAL DateStyle='ISO, YMD'")
const stream = new CatalogueValueStream()
const raw = {} as Inventory
for (const group of GROUPS) raw[group] = []
const statement = FIXED44_CATALOGUE_BUILD_SQL.replace("LIMIT 104", "LIMIT 113")
await db.query("DECLARE ix_capture_cursor NO SCROLL CURSOR WITHOUT HOLD FOR " + statement, roles)
for (;;) {
const page = (await db.query("FETCH FORWARD 128 FROM ix_capture_cursor")).rows
if (!page.length) break
for (const record of stream.acceptPage(page)) {
if (record.kind === "global") raw[record.identity === "base_tables" ? "tables" : record.identity] = record.value.rows as Row[]
if (record.kind === "base") for (const group of GROUPS) raw[group].push(...record.value[group] as Row[])
}
}
stream.finish()
const projected = projectCatalogueData(raw)
const delta: Inventory = {}
for (const group of ["tables", ...GROUPS]) delta[group] = sorted(projected[group].filter(row => tables.includes(String(row.relname))))
delta.constraints.push(...projected.constraints.filter(row => row.relname === "servers" && row.conname === "servers_type_check"))
delta.triggers.push(...projected.triggers.filter(row => row.relname === "servers" && String(row.definition).includes("ix_segment_devices")))
assert.equal(delta.tables.length, 3)
assert.equal(delta.triggers.filter(row => row.relname === "servers").length, 2)
await db.query("ROLLBACK")
let text = JSON.stringify(delta, null, 2)
for (const [index, role] of roles.entries()) text = text.replaceAll(role, "@mm-role:" + ["operator","runtime","capture","publisher","control"][index] + "@")
assert.equal(canonical(JSON.parse(text)), canonical(FIXED59_IX_DELTA), "PostgreSQL catalogue drifted from source59")
console.log(JSON.stringify({ postgres: (await db.query("SHOW server_version")).rows[0].server_version, relations: delta.tables.length, constraints: delta.constraints.length,
triggers: delta.triggers.length, leastPrivilege: true, sharedWriterLock: true }))
} finally {
await db.end().catch(() => {})
await app.stop()
}
@@ -20,10 +20,11 @@ test('fixed artifact is reproducible, resolves the compiled backend graph, and r
const packageJson=JSON.parse(await readFile(path.join(backend,'package.json'),'utf8')) const packageJson=JSON.parse(await readFile(path.join(backend,'package.json'),'utf8'))
await mkdir(projectBackend,{recursive:true});await writeFile(path.join(projectBackend,'package.json'),JSON.stringify({type:'module',dependencies:packageJson.dependencies})) await mkdir(projectBackend,{recursive:true});await writeFile(path.join(projectBackend,'package.json'),JSON.stringify({type:'module',dependencies:packageJson.dependencies}))
const first=await buildDatabaseOperator({backendDirectory:backend,outputDirectory:output}),second=await buildDatabaseOperator({backendDirectory:backend,outputDirectory:output}) const first=await buildDatabaseOperator({backendDirectory:backend,outputDirectory:output}),second=await buildDatabaseOperator({backendDirectory:backend,outputDirectory:output})
assert.deepEqual(first,second);assert.equal(first.modules.length,OPERATOR_SOURCES.length);assert.equal(first.modules.length,31);assert.deepEqual(first.runtimeDependencies,['dotenv','pg','zod']);assert.equal(first.backendDistModules.length,30) assert.deepEqual(first,second);assert.equal(first.modules.length,OPERATOR_SOURCES.length);assert.equal(first.modules.length,34);assert.deepEqual(first.runtimeDependencies,['dotenv','pg','zod']);assert.equal(first.backendDistModules.length,33)
assert(first.modules.some(item=>item.file==='writer-profile/registry-enrollment.mjs')) assert(first.modules.some(item=>item.file==='writer-profile/registry-enrollment.mjs'))
assert(first.modules.some(item=>item.file==='writer-profile/marker-fence-enrollment.mjs')) assert(first.modules.some(item=>item.file==='writer-profile/marker-fence-enrollment.mjs'))
assert(first.modules.some(item=>item.file==='writer-profile/fixed58-build-definition.js')) assert(first.modules.some(item=>item.file==='writer-profile/fixed58-build-definition.js'))
assert(first.modules.some(item=>item.file==='writer-profile/fixed60-build-definition.js'))
assert(first.backendDistImports.includes('db/database-restore-quarantine-profile.js')) assert(first.backendDistImports.includes('db/database-restore-quarantine-profile.js'))
assert(first.backendDistImports.includes('db/database-source-activation-record.js')) assert(first.backendDistImports.includes('db/database-source-activation-record.js'))
assert(first.backendDistImports.includes('services/server-probe-legacy-source-inventory.js')) assert(first.backendDistImports.includes('services/server-probe-legacy-source-inventory.js'))
@@ -13,5 +13,5 @@ export const OPERATOR_SOURCES=Object.freeze([
'writer-profile/catalogue.mts','writer-profile/catalogue-value-bridge.ts','writer-profile/catalogue-projection.ts','writer-profile/catalogue-leaves.ts', 'writer-profile/catalogue.mts','writer-profile/catalogue-value-bridge.ts','writer-profile/catalogue-projection.ts','writer-profile/catalogue-leaves.ts',
'writer-profile/application-writer-profile-catalogue.ts','writer-profile/application-writer-profile-catalogue-values.ts', 'writer-profile/application-writer-profile-catalogue.ts','writer-profile/application-writer-profile-catalogue-values.ts',
'writer-profile/application-writer-profile-catalogue-parent-policy.ts','writer-profile/application-writer-profile-canonical.ts', 'writer-profile/application-writer-profile-catalogue-parent-policy.ts','writer-profile/application-writer-profile-canonical.ts',
'writer-profile/fixed44-build-sql.ts','writer-profile/fixed44-build-definition.ts','writer-profile/fixed56-build-definition.ts','writer-profile/fixed56-build-delta.ts','writer-profile/fixed57-build-definition.ts','writer-profile/fixed58-build-definition.ts','writer-profile/expanded44-data-policy.ts', 'writer-profile/fixed44-build-sql.ts','writer-profile/fixed44-build-definition.ts','writer-profile/fixed56-build-definition.ts','writer-profile/fixed56-build-delta.ts','writer-profile/fixed57-build-definition.ts','writer-profile/fixed58-build-definition.ts','writer-profile/fixed59-build-definition.ts','writer-profile/fixed59-ix-delta.ts','writer-profile/fixed60-build-definition.ts','writer-profile/expanded44-data-policy.ts',
]) ])
@@ -57,11 +57,11 @@ export async function main(args:string[]){
// import so a newly loaded NODE_PG_FORCE_NATIVE cannot select another driver. // import so a newly loaded NODE_PG_FORCE_NATIVE cannot select another driver.
const {createProtectedDatabaseSourceBindingVerifier}=await import('./writer-profile/protected-source-registry.mjs') const {createProtectedDatabaseSourceBindingVerifier}=await import('./writer-profile/protected-source-registry.mjs')
assertJsDriverEnvironment(process.env) assertJsDriverEnvironment(process.env)
const [{default:pg},{createConnectedPublisher,requireCurrentCatalogueDefinition},{collectSource44Catalogue,collectSource56Catalogue,collectSource57Catalogue,collectSource58Catalogue,approvedDefinition}]=await Promise.all([ const [{default:pg},{createConnectedPublisher,requireCurrentCatalogueDefinition},{collectSource44Catalogue,collectSource56Catalogue,collectSource57Catalogue,collectSource58Catalogue,collectSource59Catalogue,collectSource60Catalogue,approvedDefinition}]=await Promise.all([
import('pg'),import('./writer-profile/publisher.mjs'),import('./writer-profile/catalogue.mjs')]) import('pg'),import('./writer-profile/publisher.mjs'),import('./writer-profile/catalogue.mjs')])
assertJsDriverEnvironment(process.env) assertJsDriverEnvironment(process.env)
const reviewedDefinition=legacyInspection?undefined:approvedDefinition(definition) const reviewedDefinition=legacyInspection?undefined:approvedDefinition(definition)
const collectCatalogues={44:collectSource44Catalogue,56:collectSource56Catalogue,57:collectSource57Catalogue,58:collectSource58Catalogue} const collectCatalogues={44:collectSource44Catalogue,56:collectSource56Catalogue,57:collectSource57Catalogue,58:collectSource58Catalogue,59:collectSource59Catalogue,60:collectSource60Catalogue}
const collectCatalogue=collectCatalogues[reviewedDefinition&&'edition' in reviewedDefinition?reviewedDefinition.edition:44] const collectCatalogue=collectCatalogues[reviewedDefinition&&'edition' in reviewedDefinition?reviewedDefinition.edition:44]
if(!legacyInspection&&!catalogueInspection){ if(!legacyInspection&&!catalogueInspection){
assert.equal(reviewedDefinition!.definitionSha256,pinned!.definitionSha256) assert.equal(reviewedDefinition!.definitionSha256,pinned!.definitionSha256)
@@ -7,6 +7,8 @@ import {BUILD44_PROVENANCE,FIXED44_ROLE_TEMPLATE} from './fixed44-build-definiti
import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definition.js' import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definition.js'
import {BUILD57_PROVENANCE,FIXED57_ROLE_TEMPLATE} from './fixed57-build-definition.js' import {BUILD57_PROVENANCE,FIXED57_ROLE_TEMPLATE} from './fixed57-build-definition.js'
import {BUILD58_PROVENANCE,FIXED58_ROLE_TEMPLATE,normalizeFixed58RestoreRows} from './fixed58-build-definition.js' import {BUILD58_PROVENANCE,FIXED58_ROLE_TEMPLATE,normalizeFixed58RestoreRows} from './fixed58-build-definition.js'
import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js'
import {BUILD60_PROVENANCE,FIXED60_ROLE_TEMPLATE} from './fixed60-build-definition.js'
import {GLOBALS,GROUPS,object,rows,sorted,text,projectCatalogueData,type CatalogueEdition,type Inventory,type Row,type Json} from './catalogue-projection.js' import {GLOBALS,GROUPS,object,rows,sorted,text,projectCatalogueData,type CatalogueEdition,type Inventory,type Row,type Json} from './catalogue-projection.js'
import {validateCatalogueLeafData} from './catalogue-leaves.js' import {validateCatalogueLeafData} from './catalogue-leaves.js'
import {catalogueTopologyPolicy,Expanded44TopologyBudgetData} from './expanded44-data-policy.js' import {catalogueTopologyPolicy,Expanded44TopologyBudgetData} from './expanded44-data-policy.js'
@@ -20,6 +22,8 @@ const definitions = {
56: { provenance: BUILD56_PROVENANCE, template: FIXED56_ROLE_TEMPLATE }, 56: { provenance: BUILD56_PROVENANCE, template: FIXED56_ROLE_TEMPLATE },
57: { provenance: BUILD57_PROVENANCE, template: FIXED57_ROLE_TEMPLATE }, 57: { provenance: BUILD57_PROVENANCE, template: FIXED57_ROLE_TEMPLATE },
58: { provenance: BUILD58_PROVENANCE, template: FIXED58_ROLE_TEMPLATE }, 58: { provenance: BUILD58_PROVENANCE, template: FIXED58_ROLE_TEMPLATE },
59: { provenance: BUILD59_PROVENANCE, template: FIXED59_ROLE_TEMPLATE },
60: { provenance: BUILD60_PROVENANCE, template: FIXED60_ROLE_TEMPLATE },
} }
const exact=(a:unknown,b:unknown,label:string)=>{if(canonical(a)!==canonical(b))throw Error('Writer catalogue refused: '+label)} const exact=(a:unknown,b:unknown,label:string)=>{if(canonical(a)!==canonical(b))throw Error('Writer catalogue refused: '+label)}
function captureBindings(input:InstallationRoleBindingsData):Readonly<Record<LogicalRole,string>> { function captureBindings(input:InstallationRoleBindingsData):Readonly<Record<LogicalRole,string>> {
@@ -68,7 +72,7 @@ export class Fixed44CatalogueDataVerifier {
if(this.counts||table.relispartition!==false||this.bases.has(record.identity))throw Error('Duplicate/late base') if(this.counts||table.relispartition!==false||this.bases.has(record.identity))throw Error('Duplicate/late base')
const header=this.headers!.find(t=>t.relname===record.identity);if(!header)throw Error('Foreign base refused');exact(table,header,'header/table') const header=this.headers!.find(t=>t.relname===record.identity);if(!header)throw Error('Foreign base refused');exact(table,header,'header/table')
const actual=projectCatalogueData({...this.globals,...groups,tables:this.headers!}) const actual=projectCatalogueData({...this.globals,...groups,tables:this.headers!})
for(const name of GROUPS)exact(this.edition===58?normalizeFixed58RestoreRows(record.identity,name,actual[name]):actual[name], for(const name of GROUPS)exact(this.edition>=58?normalizeFixed58RestoreRows(record.identity,name,actual[name]):actual[name],
this.expected[name].filter(r=>r.relname===record.identity),'base '+name+' '+record.identity) this.expected[name].filter(r=>r.relname===record.identity),'base '+name+' '+record.identity)
this.topology.acceptRelation('base',record.identity,groups);this.bases.add(record.identity);if(fixedCatalogueParentPeriodData(record.identity))this.templates.set(record.identity,{table,groups});return this.topology.acceptRelation('base',record.identity,groups);this.bases.add(record.identity);if(fixedCatalogueParentPeriodData(record.identity))this.templates.set(record.identity,{table,groups});return
} }
@@ -4,7 +4,7 @@ export type Json=null|boolean|number|string|Json[]|{[key:string]:Json}
export type Row=Record<string,Json> export type Row=Record<string,Json>
export type Inventory=Record<string,Row[]> export type Inventory=Record<string,Row[]>
export const GROUPS=['columns','triggers','constraints','indexes','roleGrants','inheritance'] as const export const GROUPS=['columns','triggers','constraints','indexes','roleGrants','inheritance'] as const
export type CatalogueEdition = 44 | 56 | 57 | 58 export type CatalogueEdition = 44 | 56 | 57 | 58 | 59 | 60
export const GLOBALS=['database','effectiveDatabase','effectiveFunctions','effectiveSchemas','effectiveSequences','events','functions','identities','memberships','parameters','roles','schemas','settings','sequences'] as const export const GLOBALS=['database','effectiveDatabase','effectiveFunctions','effectiveSchemas','effectiveSequences','events','functions','identities','memberships','parameters','roles','schemas','settings','sequences'] as const
export const sorted=(rows:Row[])=>rows.slice().sort((a,b)=>canonical(a)<canonical(b)?-1:canonical(a)>canonical(b)?1:0) export const sorted=(rows:Row[])=>rows.slice().sort((a,b)=>canonical(a)<canonical(b)?-1:canonical(a)>canonical(b)?1:0)
export const omit=(row:Row,names:readonly string[]):Row=>Object.fromEntries(Object.entries(row).filter(([key])=>!names.includes(key))) export const omit=(row:Row,names:readonly string[]):Row=>Object.fromEntries(Object.entries(row).filter(([key])=>!names.includes(key)))
+15 -2
View File
@@ -5,6 +5,8 @@ import {BUILD44_PROVENANCE,FIXED44_ROLE_TEMPLATE} from './fixed44-build-definiti
import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definition.js' import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definition.js'
import {BUILD57_PROVENANCE,FIXED57_ROLE_TEMPLATE} from './fixed57-build-definition.js' import {BUILD57_PROVENANCE,FIXED57_ROLE_TEMPLATE} from './fixed57-build-definition.js'
import {BUILD58_PROVENANCE,FIXED58_ROLE_TEMPLATE} from './fixed58-build-definition.js' import {BUILD58_PROVENANCE,FIXED58_ROLE_TEMPLATE} from './fixed58-build-definition.js'
import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js'
import {BUILD60_PROVENANCE,FIXED60_ROLE_TEMPLATE} from './fixed60-build-definition.js'
import {assertRestoreProfileQuarantine} from '../../src/db/database-restore-quarantine-profile.js' import {assertRestoreProfileQuarantine} from '../../src/db/database-restore-quarantine-profile.js'
import {canonical,sha} from './application-writer-profile-canonical.js' import {canonical,sha} from './application-writer-profile-canonical.js'
import type {CatalogueEdition} from './catalogue-projection.js' import type {CatalogueEdition} from './catalogue-projection.js'
@@ -23,6 +25,14 @@ export function approvedDefinition(value:unknown){
assert.equal(canonical(v.provenance),canonical(BUILD58_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED58_ROLE_TEMPLATE)) assert.equal(canonical(v.provenance),canonical(BUILD58_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED58_ROLE_TEMPLATE))
return Object.freeze({edition:58 as const,definitionSha256:BUILD58_PROVENANCE.templateSha256,manifestSha256:BUILD58_PROVENANCE.manifestSha256}) return Object.freeze({edition:58 as const,definitionSha256:BUILD58_PROVENANCE.templateSha256,manifestSha256:BUILD58_PROVENANCE.manifestSha256})
} }
if(v.format==='application-writer-source59-definition-approval-v1'){
assert.equal(canonical(v.provenance),canonical(BUILD59_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED59_ROLE_TEMPLATE))
return Object.freeze({edition:59 as const,definitionSha256:BUILD59_PROVENANCE.templateSha256,manifestSha256:BUILD59_PROVENANCE.manifestSha256})
}
if(v.format==='application-writer-source60-definition-approval-v1'){
assert.equal(canonical(v.provenance),canonical(BUILD60_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED60_ROLE_TEMPLATE))
return Object.freeze({edition:60 as const,definitionSha256:BUILD60_PROVENANCE.templateSha256,manifestSha256:BUILD60_PROVENANCE.manifestSha256})
}
assert.equal(v.format,'application-writer-source56-definition-approval-v1') assert.equal(v.format,'application-writer-source56-definition-approval-v1')
assert.equal(canonical(v.provenance),canonical(BUILD56_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED56_ROLE_TEMPLATE)) assert.equal(canonical(v.provenance),canonical(BUILD56_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED56_ROLE_TEMPLATE))
return Object.freeze({edition:56 as const,definitionSha256:BUILD56_PROVENANCE.templateSha256,manifestSha256:BUILD56_PROVENANCE.manifestSha256}) return Object.freeze({edition:56 as const,definitionSha256:BUILD56_PROVENANCE.templateSha256,manifestSha256:BUILD56_PROVENANCE.manifestSha256})
@@ -31,11 +41,14 @@ type CatalogueSession = {query:(sql:string,values?:unknown[])=>Promise<{rows:Rec
type CatalogueInstallation = {roleBindings:ConstructorParameters<typeof Fixed44CatalogueValueBridgeData>[0]} type CatalogueInstallation = {roleBindings:ConstructorParameters<typeof Fixed44CatalogueValueBridgeData>[0]}
assert.equal(FIXED44_CATALOGUE_BUILD_SQL.split('LIMIT 104').length,2) assert.equal(FIXED44_CATALOGUE_BUILD_SQL.split('LIMIT 104').length,2)
const fixed56Sql = FIXED44_CATALOGUE_BUILD_SQL.replace('LIMIT 104','LIMIT 110') const fixed56Sql = FIXED44_CATALOGUE_BUILD_SQL.replace('LIMIT 104','LIMIT 110')
const fixed59Sql = FIXED44_CATALOGUE_BUILD_SQL.replace('LIMIT 104','LIMIT 113')
/** Real incremental DATA verifier on caller's retained transaction. No pool or attestor. */ /** Real incremental DATA verifier on caller's retained transaction. No pool or attestor. */
export const collectSource44Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 44) export const collectSource44Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 44)
export const collectSource56Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 56) export const collectSource56Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 56)
export const collectSource57Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 57) export const collectSource57Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 57)
export const collectSource58Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 58) export const collectSource58Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 58)
export const collectSource59Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 59)
export const collectSource60Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 60)
async function collectCatalogue(s:CatalogueSession,installation:CatalogueInstallation,edition:CatalogueEdition){ async function collectCatalogue(s:CatalogueSession,installation:CatalogueInstallation,edition:CatalogueEdition){
const settings=(await s.query("SELECT pg_catalog.current_setting('search_path') AS path,pg_catalog.current_setting('TimeZone') AS zone,pg_catalog.current_setting('DateStyle') AS dates")).rows const settings=(await s.query("SELECT pg_catalog.current_setting('search_path') AS path,pg_catalog.current_setting('TimeZone') AS zone,pg_catalog.current_setting('DateStyle') AS dates")).rows
assert.equal(settings.length,1);assert(['path','zone','dates'].every(k=>typeof settings[0][k]==='string')) assert.equal(settings.length,1);assert(['path','zone','dates'].every(k=>typeof settings[0][k]==='string'))
@@ -43,9 +56,9 @@ async function collectCatalogue(s:CatalogueSession,installation:CatalogueInstall
try{ try{
await s.query("SELECT pg_catalog.set_config('search_path','pg_catalog, public',true),pg_catalog.set_config('TimeZone','UTC',true),pg_catalog.set_config('DateStyle','ISO, YMD',true)") await s.query("SELECT pg_catalog.set_config('search_path','pg_catalog, public',true),pg_catalog.set_config('TimeZone','UTC',true),pg_catalog.set_config('DateStyle','ISO, YMD',true)")
const bindings=installation.roleBindings,values=['operator','runtime','capture','publisher','control'].map(k=>bindings[k as keyof typeof bindings].name) const bindings=installation.roleBindings,values=['operator','runtime','capture','publisher','control'].map(k=>bindings[k as keyof typeof bindings].name)
if(edition===58)await assertRestoreProfileQuarantine(s,bindings.runtime.name,bindings.operator.name,bindings.control.name) if(edition>=58)await assertRestoreProfileQuarantine(s,bindings.runtime.name,bindings.operator.name,bindings.control.name)
const bridge=new Fixed44CatalogueValueBridgeData(bindings,edition) const bridge=new Fixed44CatalogueValueBridgeData(bindings,edition)
await s.query('DECLARE mm_publisher44 NO SCROLL CURSOR WITHOUT HOLD FOR '+(edition===44?FIXED44_CATALOGUE_BUILD_SQL:fixed56Sql),values);cursor=true await s.query('DECLARE mm_publisher44 NO SCROLL CURSOR WITHOUT HOLD FOR '+(edition===44?FIXED44_CATALOGUE_BUILD_SQL:edition>=59?fixed59Sql:fixed56Sql),values);cursor=true
for(;;){const page=(await s.query('FETCH FORWARD 128 FROM mm_publisher44')).rows;bridge.acceptPage(page);if(page.length===0)break} for(;;){const page=(await s.query('FETCH FORWARD 128 FROM mm_publisher44')).rows;bridge.acceptPage(page);if(page.length===0)break}
const result=bridge.finish();await s.query('CLOSE mm_publisher44');cursor=false const result=bridge.finish();await s.query('CLOSE mm_publisher44');cursor=false
return {catalogSha256:sha(canonical({values:result.values.snapshotSha256,catalogue:result.catalogue})),definitionSha256:result.catalogue.definitionSha256,manifestSha256:result.catalogue.manifestSha256,leafCount:result.catalogue.leafRelations} return {catalogSha256:sha(canonical({values:result.values.snapshotSha256,catalogue:result.catalogue})),definitionSha256:result.catalogue.definitionSha256,manifestSha256:result.catalogue.manifestSha256,leafCount:result.catalogue.leafRelations}
@@ -3,6 +3,8 @@ import {BUILD44_PROVENANCE,FIXED44_ROLE_TEMPLATE} from './fixed44-build-definiti
import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definition.js' import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definition.js'
import {BUILD57_PROVENANCE} from './fixed57-build-definition.js' import {BUILD57_PROVENANCE} from './fixed57-build-definition.js'
import {BUILD58_PROVENANCE} from './fixed58-build-definition.js' import {BUILD58_PROVENANCE} from './fixed58-build-definition.js'
import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js'
import {BUILD60_PROVENANCE,FIXED60_ROLE_TEMPLATE} from './fixed60-build-definition.js'
import {fixedCatalogueParentPeriodData} from './application-writer-profile-catalogue-parent-policy.js' import {fixedCatalogueParentPeriodData} from './application-writer-profile-catalogue-parent-policy.js'
import {GROUPS,type CatalogueEdition,type Inventory} from './catalogue-projection.js' import {GROUPS,type CatalogueEdition,type Inventory} from './catalogue-projection.js'
export const EXPANDED44_POLICY_VERSION='source44-managed-leaves-3000-data-v1' as const export const EXPANDED44_POLICY_VERSION='source44-managed-leaves-3000-data-v1' as const
@@ -49,8 +51,35 @@ const EXPANDED58_DATA_POLICY = Object.freeze({
version: 'source58-managed-leaves-3000-data-v1', version: 'source58-managed-leaves-3000-data-v1',
definitionSha256: BUILD58_PROVENANCE.templateSha256, definitionSha256: BUILD58_PROVENANCE.templateSha256,
}) })
const policies = {44: EXPANDED44_DATA_POLICY, 56: EXPANDED56_DATA_POLICY, 57: EXPANDED57_DATA_POLICY, 58: EXPANDED58_DATA_POLICY} const source59PerRelation = new Map(FIXED59_ROLE_TEMPLATE.tables.map(({relname}) => [String(relname), Object.fromEntries(
const relationCounts = {44: perRelation, 56: source56PerRelation, 57: source57PerRelation, 58: source57PerRelation} GROUPS.map(group => [group, FIXED59_ROLE_TEMPLATE[group].filter(row => (group === 'inheritance' ? row.child : row.relname) === relname).length]),
) as Record<typeof GROUPS[number],number>]))
const source59BaseRows = Object.freeze(Object.fromEntries(GROUPS.map(group => [group,FIXED59_ROLE_TEMPLATE[group].length])) as Record<typeof GROUPS[number],number>)
if (source59PerRelation.size !== 113 || parents.some(name => GROUPS.some(group => source59PerRelation.get(name)?.[group] !== source57PerRelation.get(name)?.[group]))) {
throw Error('Unexpected source59 IX topology')
}
const EXPANDED59_DATA_POLICY = Object.freeze({
...EXPANDED58_DATA_POLICY,
version: 'source59-managed-leaves-3000-data-v1',
baseRelations: source59PerRelation.size,
maxRelations: source59PerRelation.size + LEAVES,
baseRows: source59BaseRows,
maxRows: Object.freeze(Object.fromEntries(GROUPS.map(group => [group,source59BaseRows[group] + LEAVES * leafMax[group]])) as Record<typeof GROUPS[number],number>),
definitionSha256: BUILD59_PROVENANCE.templateSha256,
})
const source60PerRelation = new Map(source59PerRelation)
const storageUsage = source59PerRelation.get('server_poll_storage_usage')!
const removed = FIXED59_ROLE_TEMPLATE.constraints.length - FIXED60_ROLE_TEMPLATE.constraints.length
source60PerRelation.set('server_poll_storage_usage', {...storageUsage, constraints: storageUsage.constraints - removed})
const EXPANDED60_DATA_POLICY = Object.freeze({
...EXPANDED59_DATA_POLICY,
version: 'source60-managed-leaves-3000-data-v1',
baseRows: Object.freeze({...source59BaseRows, constraints: source59BaseRows.constraints - removed}),
maxRows: Object.freeze({...EXPANDED59_DATA_POLICY.maxRows, constraints: EXPANDED59_DATA_POLICY.maxRows.constraints - removed}),
definitionSha256: BUILD60_PROVENANCE.templateSha256,
})
const policies = {44: EXPANDED44_DATA_POLICY, 56: EXPANDED56_DATA_POLICY, 57: EXPANDED57_DATA_POLICY, 58: EXPANDED58_DATA_POLICY, 59: EXPANDED59_DATA_POLICY, 60: EXPANDED60_DATA_POLICY}
const relationCounts = {44: perRelation, 56: source56PerRelation, 57: source57PerRelation, 58: source57PerRelation, 59: source59PerRelation, 60: source60PerRelation}
export const catalogueTopologyPolicy = (edition: CatalogueEdition) => policies[edition] export const catalogueTopologyPolicy = (edition: CatalogueEdition) => policies[edition]
export const expanded44ParentRowCountsData=()=>Object.freeze(Object.fromEntries(parents.map(name=>[name,Object.freeze({...perRelation.get(name)!})]))) export const expanded44ParentRowCountsData=()=>Object.freeze(Object.fromEntries(parents.map(name=>[name,Object.freeze({...perRelation.get(name)!})])))
export interface ManagedLeafData {readonly parent:string;readonly name:string} export interface ManagedLeafData {readonly parent:string;readonly name:string}
@@ -0,0 +1,43 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { createHash } from "node:crypto"
import { MIGRATION_MANIFEST, migrationManifestDigest } from "../../src/db/migration-manifest.js"
import { ixWriterProfileEnrollmentSql } from "../../src/db/internet-exchange-writer-profile.js"
import { approvedDefinition } from "./catalogue.mjs"
import { FIXED58_ROLE_TEMPLATE } from "./fixed58-build-definition.js"
import { BUILD59_PROVENANCE, FIXED59_ROLE_TEMPLATE } from "./fixed59-build-definition.js"
import { BUILD60_PROVENANCE, FIXED60_ROLE_TEMPLATE } from "./fixed60-build-definition.js"
import { catalogueTopologyPolicy } from "./expanded44-data-policy.js"
test("source59 pins migration 0058 and alters only the IX catalogue and its existing servers references", () => {
assert.equal(BUILD59_PROVENANCE.manifestSha256, createHash("sha256").update(JSON.stringify(MIGRATION_MANIFEST.slice(0, 58))).digest("hex"))
assert.equal(catalogueTopologyPolicy(59).baseRelations, catalogueTopologyPolicy(58).baseRelations + 3)
const added = new Set(FIXED59_ROLE_TEMPLATE.tables.filter(row => String(row.relname).startsWith("ix_segment")).map(row => row.relname))
assert.deepEqual([...added].sort(), ["ix_segment_devices", "ix_segment_revisions", "ix_segments"])
for (const group of ["tables", "columns", "roleGrants", "inheritance", "indexes"]) {
assert.deepEqual(FIXED59_ROLE_TEMPLATE[group].filter(row => !added.has(row.relname)), FIXED58_ROLE_TEMPLATE[group])
}
assert.equal(FIXED59_ROLE_TEMPLATE.triggers.length - FIXED58_ROLE_TEMPLATE.triggers.length, 21)
assert.equal(FIXED59_ROLE_TEMPLATE.constraints.length - FIXED58_ROLE_TEMPLATE.constraints.length, 24)
})
test("source60 changes poll storage constraints without changing writer grants or table topology", () => {
assert.equal(BUILD60_PROVENANCE.manifestSha256, migrationManifestDigest())
const approval = { format: "application-writer-source60-definition-approval-v1", provenance: BUILD60_PROVENANCE, template: FIXED60_ROLE_TEMPLATE }
assert.equal(approvedDefinition(approval).definitionSha256, BUILD60_PROVENANCE.templateSha256)
assert.deepEqual(FIXED60_ROLE_TEMPLATE.tables, FIXED59_ROLE_TEMPLATE.tables)
assert.deepEqual(FIXED60_ROLE_TEMPLATE.roleGrants, FIXED59_ROLE_TEMPLATE.roleGrants)
assert.equal(catalogueTopologyPolicy(60).baseRows.constraints, catalogueTopologyPolicy(59).baseRows.constraints - 1)
})
test("source59 accepts the exact independently reviewed definition and restricts IX runtime grants", () => {
const approval = { format: "application-writer-source59-definition-approval-v1", provenance: BUILD59_PROVENANCE, template: FIXED59_ROLE_TEMPLATE }
assert.equal(approvedDefinition(approval).definitionSha256, BUILD59_PROVENANCE.templateSha256)
assert.throws(() => approvedDefinition({ ...approval, template: FIXED58_ROLE_TEMPLATE }))
const granted = FIXED59_ROLE_TEMPLATE.roleGrants.filter(row => row.rolname === "@mm-role:runtime@" && String(row.relname).startsWith("ix_"))
assert(granted.every(row => row.read === true && row.insert === true && row.truncate === false))
assert.deepEqual(granted.filter(row => row.update === true).map(row => row.relname), ["ix_segments"])
assert.deepEqual(granted.filter(row => row.delete === true).map(row => row.relname), ["ix_segment_devices"])
assert.match(ixWriterProfileEnrollmentSql("ix_runtime", "ix_capture"), /GRANT SELECT, INSERT ON TABLE public.ix_segment_revisions TO "ix_runtime"/)
assert.throws(() => ixWriterProfileEnrollmentSql('bad"role', "ix_capture"))
})
@@ -0,0 +1,25 @@
import { canonical, sha } from "./application-writer-profile-canonical.js"
import { GROUPS, sorted, type Inventory } from "./catalogue-projection.js"
import { FIXED58_ROLE_TEMPLATE } from "./fixed58-build-definition.js"
import { FIXED59_IX_DELTA } from "./fixed59-ix-delta.js"
import { IX_WRITER_PROFILE_DEFINITION_SHA256, IX_WRITER_PROFILE_MANIFEST_SHA256 } from "../../src/db/internet-exchange-writer-profile.js"
const prior: Inventory = {
...FIXED58_ROLE_TEMPLATE,
constraints: FIXED58_ROLE_TEMPLATE.constraints.filter(row => !(row.relname === "servers" && row.conname === "servers_type_check")),
}
export const FIXED59_ROLE_TEMPLATE: Readonly<Inventory> = Object.freeze({
...prior,
...Object.fromEntries(["tables", ...GROUPS].map(group => [group, sorted([...prior[group], ...FIXED59_IX_DELTA[group]])])),
})
export const BUILD59_PROVENANCE = Object.freeze({
format: "source59-ix-profile-v1",
manifestSha256: IX_WRITER_PROFILE_MANIFEST_SHA256,
templateSha256: IX_WRITER_PROFILE_DEFINITION_SHA256,
})
if (sha(canonical(FIXED59_ROLE_TEMPLATE)) !== BUILD59_PROVENANCE.templateSha256) {
throw new Error("Fixed59 writer catalogue changed")
}
@@ -0,0 +1,99 @@
// PostgreSQL 18.4 catalogue rows captured after migration 0058 and IX least-privilege enrollment.
import type { Inventory } from "./catalogue-projection.js"
export const FIXED59_IX_DELTA: Inventory = {
tables: [
{"acl":["@mm-role:capture@=r/@mm-role:operator@","@mm-role:operator@=arwdDxtm/@mm-role:operator@","@mm-role:runtime@=ar/@mm-role:operator@"],"owner":"@mm-role:operator@","relkind":"r","relname":"ix_segment_revisions","namespace":"public","reloptions":null,"partition_key":null,"relispartition":false,"relrowsecurity":false,"partition_bound":null,"relforcerowsecurity":false},
{"acl":["@mm-role:capture@=r/@mm-role:operator@","@mm-role:operator@=arwdDxtm/@mm-role:operator@","@mm-role:runtime@=ard/@mm-role:operator@"],"owner":"@mm-role:operator@","relkind":"r","relname":"ix_segment_devices","namespace":"public","reloptions":null,"partition_key":null,"relispartition":false,"relrowsecurity":false,"partition_bound":null,"relforcerowsecurity":false},
{"acl":["@mm-role:capture@=r/@mm-role:operator@","@mm-role:operator@=arwdDxtm/@mm-role:operator@","@mm-role:runtime@=arw/@mm-role:operator@"],"owner":"@mm-role:operator@","relkind":"r","relname":"ix_segments","namespace":"public","reloptions":null,"partition_key":null,"relispartition":false,"relrowsecurity":false,"partition_bound":null,"relforcerowsecurity":false},
],
columns: [
{"acl":null,"type":"text","attnum":4,"attname":"actor_id","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"x","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
{"acl":null,"type":"integer","attnum":5,"attname":"applied_revision","relname":"ix_segments","attnotnull":false,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
{"acl":null,"type":"jsonb","attnum":3,"attname":"configuration","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"x","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
{"acl":null,"type":"jsonb","attnum":4,"attname":"configuration","relname":"ix_segments","attnotnull":true,"attstorage":"x","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
{"acl":null,"type":"timestamp with time zone","attnum":5,"attname":"created_at","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":"now()"},
{"acl":null,"type":"uuid","attnum":1,"attname":"id","relname":"ix_segments","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
{"acl":null,"type":"text","attnum":2,"attname":"name","relname":"ix_segments","attnotnull":true,"attstorage":"x","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
{"acl":null,"type":"integer","attnum":2,"attname":"revision","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
{"acl":null,"type":"integer","attnum":3,"attname":"revision","relname":"ix_segments","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
{"acl":null,"type":"uuid","attnum":1,"attname":"segment_id","relname":"ix_segment_devices","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
{"acl":null,"type":"uuid","attnum":1,"attname":"segment_id","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
{"acl":null,"type":"bigint","attnum":2,"attname":"server_id","relname":"ix_segment_devices","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
{"acl":null,"type":"timestamp with time zone","attnum":6,"attname":"updated_at","relname":"ix_segments","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":"now()"},
],
triggers: [
{"tgname":"candidate_application_statement_guard","tgtype":30,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_application_statement_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segment_devices FOR EACH STATEMENT EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
{"tgname":"candidate_application_statement_guard","tgtype":30,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_application_statement_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segment_revisions FOR EACH STATEMENT EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
{"tgname":"candidate_application_statement_guard","tgtype":30,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_application_statement_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segments FOR EACH STATEMENT EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
{"tgname":"candidate_truncate_preadmitted","tgtype":34,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_truncate_preadmitted BEFORE TRUNCATE ON public.ix_segment_devices FOR EACH STATEMENT EXECUTE FUNCTION mmapp_control.candidate_truncate_preadmitted()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"mmapp_control.candidate_truncate_preadmitted()","parent":false,"constraint":false},
{"tgname":"candidate_truncate_preadmitted","tgtype":34,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_truncate_preadmitted BEFORE TRUNCATE ON public.ix_segment_revisions FOR EACH STATEMENT EXECUTE FUNCTION mmapp_control.candidate_truncate_preadmitted()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"mmapp_control.candidate_truncate_preadmitted()","parent":false,"constraint":false},
{"tgname":"candidate_truncate_preadmitted","tgtype":34,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_truncate_preadmitted BEFORE TRUNCATE ON public.ix_segments FOR EACH STATEMENT EXECUTE FUNCTION mmapp_control.candidate_truncate_preadmitted()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"mmapp_control.candidate_truncate_preadmitted()","parent":false,"constraint":false},
{"tgname":"server_partition_writer_guard","tgtype":31,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER server_partition_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segment_devices FOR EACH ROW EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
{"tgname":"server_partition_writer_guard","tgtype":31,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER server_partition_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segment_revisions FOR EACH ROW EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
{"tgname":"server_partition_writer_guard","tgtype":31,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER server_partition_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segments FOR EACH ROW EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":9,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER DELETE ON public.ix_segments FROM ix_segment_devices NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_cascade_del\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1646","parent":false,"constraint":true},
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":9,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER DELETE ON public.ix_segments FROM ix_segment_revisions NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_cascade_del\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1646","parent":false,"constraint":true},
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":17,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER UPDATE ON public.ix_segments FROM ix_segment_devices NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_noaction_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1655","parent":false,"constraint":true},
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":17,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER UPDATE ON public.ix_segments FROM ix_segment_revisions NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_noaction_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1655","parent":false,"constraint":true},
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":5,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER INSERT ON public.ix_segment_devices FROM ix_segments NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_ins\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1644","parent":false,"constraint":true},
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":5,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER INSERT ON public.ix_segment_devices FROM servers NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_ins\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1644","parent":false,"constraint":true},
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":5,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER INSERT ON public.ix_segment_revisions FROM ix_segments NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_ins\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1644","parent":false,"constraint":true},
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":17,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER UPDATE ON public.ix_segment_devices FROM ix_segments NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1645","parent":false,"constraint":true},
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":17,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER UPDATE ON public.ix_segment_devices FROM servers NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1645","parent":false,"constraint":true},
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":17,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER UPDATE ON public.ix_segment_revisions FROM ix_segments NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1645","parent":false,"constraint":true},
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":9,"relname":"servers","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER DELETE ON public.servers FROM ix_segment_devices NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_restrict_del\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1648","parent":false,"constraint":true},
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":17,"relname":"servers","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER UPDATE ON public.servers FROM ix_segment_devices NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_noaction_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1655","parent":false,"constraint":true},
],
constraints: [
{"conname":"ix_segment_devices_pkey","contype":"p","relname":"ix_segment_devices","definition":"PRIMARY KEY (segment_id, server_id)","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segment_devices_segment_id_fkey","contype":"f","relname":"ix_segment_devices","definition":"FOREIGN KEY (segment_id) REFERENCES ix_segments(id) ON DELETE CASCADE","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segment_devices_segment_id_not_null","contype":"n","relname":"ix_segment_devices","definition":"NOT NULL segment_id","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segment_devices_server_id_fkey","contype":"f","relname":"ix_segment_devices","definition":"FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE RESTRICT","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segment_devices_server_id_not_null","contype":"n","relname":"ix_segment_devices","definition":"NOT NULL server_id","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segment_revisions_actor_id_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL actor_id","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segment_revisions_configuration_check","contype":"c","relname":"ix_segment_revisions","definition":"CHECK ((jsonb_typeof(configuration) = 'object'::text))","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segment_revisions_configuration_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL configuration","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segment_revisions_created_at_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL created_at","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segment_revisions_pkey","contype":"p","relname":"ix_segment_revisions","definition":"PRIMARY KEY (segment_id, revision)","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segment_revisions_revision_check","contype":"c","relname":"ix_segment_revisions","definition":"CHECK ((revision > 0))","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segment_revisions_revision_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL revision","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segment_revisions_segment_id_fkey","contype":"f","relname":"ix_segment_revisions","definition":"FOREIGN KEY (segment_id) REFERENCES ix_segments(id) ON DELETE CASCADE","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segment_revisions_segment_id_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL segment_id","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segments_check","contype":"c","relname":"ix_segments","definition":"CHECK (((applied_revision > 0) AND (applied_revision <= revision)))","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segments_configuration_check","contype":"c","relname":"ix_segments","definition":"CHECK ((jsonb_typeof(configuration) = 'object'::text))","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segments_configuration_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL configuration","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segments_id_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL id","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segments_name_key","contype":"u","relname":"ix_segments","definition":"UNIQUE (name)","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segments_name_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL name","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segments_pkey","contype":"p","relname":"ix_segments","definition":"PRIMARY KEY (id)","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segments_revision_check","contype":"c","relname":"ix_segments","definition":"CHECK ((revision > 0))","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segments_revision_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL revision","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"ix_segments_updated_at_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL updated_at","condeferred":false,"convalidated":true,"condeferrable":false},
{"conname":"servers_type_check","contype":"c","relname":"servers","definition":"CHECK ((type = ANY (ARRAY['jump-host'::text, 'exit-node'::text, 'home-router'::text, 'ix-node'::text])))","condeferred":false,"convalidated":true,"condeferrable":false},
],
indexes: [
{"relname":"ix_segment_devices","definition":"CREATE INDEX ix_segment_devices_server_idx ON public.ix_segment_devices USING btree (server_id)","index_name":"ix_segment_devices_server_idx","indisready":true,"indisvalid":true,"indisunique":false,"indisprimary":false},
{"relname":"ix_segment_devices","definition":"CREATE UNIQUE INDEX ix_segment_devices_pkey ON public.ix_segment_devices USING btree (segment_id, server_id)","index_name":"ix_segment_devices_pkey","indisready":true,"indisvalid":true,"indisunique":true,"indisprimary":true},
{"relname":"ix_segment_revisions","definition":"CREATE UNIQUE INDEX ix_segment_revisions_pkey ON public.ix_segment_revisions USING btree (segment_id, revision)","index_name":"ix_segment_revisions_pkey","indisready":true,"indisvalid":true,"indisunique":true,"indisprimary":true},
{"relname":"ix_segments","definition":"CREATE UNIQUE INDEX ix_segments_name_key ON public.ix_segments USING btree (name)","index_name":"ix_segments_name_key","indisready":true,"indisvalid":true,"indisunique":true,"indisprimary":false},
{"relname":"ix_segments","definition":"CREATE UNIQUE INDEX ix_segments_pkey ON public.ix_segments USING btree (id)","index_name":"ix_segments_pkey","indisready":true,"indisvalid":true,"indisunique":true,"indisprimary":true},
],
roleGrants: [
{"read":false,"delete":false,"insert":false,"update":false,"relname":"ix_segment_devices","rolname":"@mm-role:publisher@","trigger":false,"truncate":false},
{"read":false,"delete":false,"insert":false,"update":false,"relname":"ix_segment_revisions","rolname":"@mm-role:publisher@","trigger":false,"truncate":false},
{"read":false,"delete":false,"insert":false,"update":false,"relname":"ix_segments","rolname":"@mm-role:publisher@","trigger":false,"truncate":false},
{"read":true,"delete":false,"insert":false,"update":false,"relname":"ix_segment_devices","rolname":"@mm-role:capture@","trigger":false,"truncate":false},
{"read":true,"delete":false,"insert":false,"update":false,"relname":"ix_segment_revisions","rolname":"@mm-role:capture@","trigger":false,"truncate":false},
{"read":true,"delete":false,"insert":false,"update":false,"relname":"ix_segments","rolname":"@mm-role:capture@","trigger":false,"truncate":false},
{"read":true,"delete":false,"insert":true,"update":false,"relname":"ix_segment_revisions","rolname":"@mm-role:runtime@","trigger":false,"truncate":false},
{"read":true,"delete":false,"insert":true,"update":true,"relname":"ix_segments","rolname":"@mm-role:runtime@","trigger":false,"truncate":false},
{"read":true,"delete":true,"insert":true,"update":true,"relname":"ix_segment_devices","rolname":"@mm-role:operator@","trigger":true,"truncate":true},
{"read":true,"delete":true,"insert":true,"update":false,"relname":"ix_segment_devices","rolname":"@mm-role:runtime@","trigger":false,"truncate":false},
{"read":true,"delete":true,"insert":true,"update":true,"relname":"ix_segment_revisions","rolname":"@mm-role:operator@","trigger":true,"truncate":true},
{"read":true,"delete":true,"insert":true,"update":true,"relname":"ix_segments","rolname":"@mm-role:operator@","trigger":true,"truncate":true},
],
inheritance: [
],
}
@@ -0,0 +1,34 @@
import { canonical, sha } from "./application-writer-profile-canonical.js"
import { sorted, type Inventory } from "./catalogue-projection.js"
import { FIXED59_ROLE_TEMPLATE } from "./fixed59-build-definition.js"
import { POLL_WRITER_PROFILE_DEFINITION_SHA256, POLL_WRITER_PROFILE_MANIFEST_SHA256 } from "../../src/db/server-poll-writer-profile.js"
const quotaConstraint = "server_poll_storage_usage_check2"
const definitions = new Map([
["server_poll_storage_usage_admissions_check", "CHECK ((admissions >= 0))"],
["server_poll_storage_rows_charge", "CHECK ((reserved_rows = ((admissions * 4019) + (compacted_admissions * 2))))"],
["server_poll_storage_bytes_charge", "CHECK ((reserved_bytes = (((admissions * 8421376) + (compacted_admissions * 32768)) + archive_bytes)))"],
])
export const FIXED60_ROLE_TEMPLATE: Readonly<Inventory> = Object.freeze({
...FIXED59_ROLE_TEMPLATE,
constraints: sorted(FIXED59_ROLE_TEMPLATE.constraints.filter(row => row.conname !== quotaConstraint || row.relname !== "server_poll_storage_usage").map(row => {
const definition = row.relname === "server_poll_storage_usage" ? definitions.get(String(row.conname)) : undefined
return definition ? { ...row, definition } : row
})),
functions: sorted(FIXED59_ROLE_TEMPLATE.functions.map(row => row.proname !== "server_poll_storage_admission_guard" ? row : {
...row,
definition: String(row.definition)
.replace(/^ IF\(SELECT count\(\*\) FROM public\.server_poll_storage_usage WHERE scope IN\('global','owner:'\|\|NEW\.owner_id\)\n[^]*?THEN RAISE EXCEPTION 'poll admission quota exhausted'; END IF;\n/m, "")
.replace("poll admission quota unavailable", "poll admission counters unavailable"),
})),
})
export const BUILD60_PROVENANCE = Object.freeze({
format: "source60-poll-journal-profile-v1",
manifestSha256: POLL_WRITER_PROFILE_MANIFEST_SHA256,
templateSha256: POLL_WRITER_PROFILE_DEFINITION_SHA256,
})
const digest = sha(canonical(FIXED60_ROLE_TEMPLATE))
if (digest !== BUILD60_PROVENANCE.templateSha256) throw new Error("Fixed60 writer catalogue changed: " + digest)
@@ -12,8 +12,10 @@ const publicationFormat='application-writer-publication-approval-v1'
export const UPGRADE_APPROVAL_FORMAT='application-writer-upgrade44-to56-approval-v1' export const UPGRADE_APPROVAL_FORMAT='application-writer-upgrade44-to56-approval-v1'
export const UPGRADE57_APPROVAL_FORMAT='application-writer-upgrade56-to57-approval-v1' export const UPGRADE57_APPROVAL_FORMAT='application-writer-upgrade56-to57-approval-v1'
export const UPGRADE58_APPROVAL_FORMAT='application-writer-upgrade57-to58-approval-v1' export const UPGRADE58_APPROVAL_FORMAT='application-writer-upgrade57-to58-approval-v1'
export const UPGRADE59_APPROVAL_FORMAT='application-writer-upgrade58-to59-approval-v1'
export const UPGRADE60_APPROVAL_FORMAT='application-writer-upgrade59-to60-approval-v1'
export const REBIND58_APPROVAL_FORMAT='application-writer-rebind58-after-restore-approval-v1' export const REBIND58_APPROVAL_FORMAT='application-writer-rebind58-after-restore-approval-v1'
export const isUpgradeApprovalFormat=format=>[UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT].includes(format) export const isUpgradeApprovalFormat=format=>[UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,UPGRADE59_APPROVAL_FORMAT,UPGRADE60_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT].includes(format)
function parsedApproval(value,format=publicationFormat){ function parsedApproval(value,format=publicationFormat){
const upgrade=isUpgradeApprovalFormat(format) const upgrade=isUpgradeApprovalFormat(format)
const keys=['format','manifestSha256','definitionSha256','catalogSha256','expectedHeadSha256','validityMs','expiresAt'] const keys=['format','manifestSha256','definitionSha256','catalogSha256','expectedHeadSha256','validityMs','expiresAt']
+12 -6
View File
@@ -3,11 +3,13 @@ import pg from 'pg'
import {createPrivateKey,createPublicKey,sign,X509Certificate} from 'node:crypto' import {createPrivateKey,createPublicKey,sign,X509Certificate} from 'node:crypto'
import {open,lstat,realpath,unlink} from 'node:fs/promises' import {open,lstat,realpath,unlink} from 'node:fs/promises'
import {readProtected,writeFile,withJournalLease} from './operator-files.mjs' import {readProtected,writeFile,withJournalLease} from './operator-files.mjs'
import {retainPublisherTlsPeer,upgradeApproval,isUpgradeApprovalFormat,UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT} from './operator-contract.mjs' import {retainPublisherTlsPeer,upgradeApproval,isUpgradeApprovalFormat,UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,UPGRADE59_APPROVAL_FORMAT,UPGRADE60_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT} from './operator-contract.mjs'
import {BUILD44_PROVENANCE} from './fixed44-build-definition.js' import {BUILD44_PROVENANCE} from './fixed44-build-definition.js'
import {BUILD56_PROVENANCE} from './fixed56-build-definition.js' import {BUILD56_PROVENANCE} from './fixed56-build-definition.js'
import {BUILD57_PROVENANCE} from './fixed57-build-definition.js' import {BUILD57_PROVENANCE} from './fixed57-build-definition.js'
import {BUILD58_PROVENANCE} from './fixed58-build-definition.js' import {BUILD58_PROVENANCE} from './fixed58-build-definition.js'
import {BUILD59_PROVENANCE} from './fixed59-build-definition.js'
import {BUILD60_PROVENANCE} from './fixed60-build-definition.js'
import path from 'node:path' import path from 'node:path'
import {captureDatabaseSourceObservation,assertDatabaseSourceObservationCurrent} from '../../src/db/database-source-observation.js' import {captureDatabaseSourceObservation,assertDatabaseSourceObservationCurrent} from '../../src/db/database-source-observation.js'
import {MIGRATION_MANIFEST,migrationManifestDigest} from '../../src/db/migration-manifest.js' import {MIGRATION_MANIFEST,migrationManifestDigest} from '../../src/db/migration-manifest.js'
@@ -19,6 +21,8 @@ const upgradeTransitions = {
[UPGRADE_APPROVAL_FORMAT]: { predecessor: BUILD44_PROVENANCE, successor: BUILD56_PROVENANCE, oldEdition: 44, newEdition: 56 }, [UPGRADE_APPROVAL_FORMAT]: { predecessor: BUILD44_PROVENANCE, successor: BUILD56_PROVENANCE, oldEdition: 44, newEdition: 56 },
[UPGRADE57_APPROVAL_FORMAT]: { predecessor: BUILD56_PROVENANCE, successor: BUILD57_PROVENANCE, oldEdition: 56, newEdition: 57 }, [UPGRADE57_APPROVAL_FORMAT]: { predecessor: BUILD56_PROVENANCE, successor: BUILD57_PROVENANCE, oldEdition: 56, newEdition: 57 },
[UPGRADE58_APPROVAL_FORMAT]: { predecessor: BUILD57_PROVENANCE, successor: BUILD58_PROVENANCE, oldEdition: 57, newEdition: 58 }, [UPGRADE58_APPROVAL_FORMAT]: { predecessor: BUILD57_PROVENANCE, successor: BUILD58_PROVENANCE, oldEdition: 57, newEdition: 58 },
[UPGRADE59_APPROVAL_FORMAT]: { predecessor: BUILD58_PROVENANCE, successor: BUILD59_PROVENANCE, oldEdition: 58, newEdition: 59 },
[UPGRADE60_APPROVAL_FORMAT]: { predecessor: BUILD59_PROVENANCE, successor: BUILD60_PROVENANCE, oldEdition: 59, newEdition: 60 },
[REBIND58_APPROVAL_FORMAT]: { predecessor: BUILD58_PROVENANCE, successor: BUILD58_PROVENANCE, oldEdition: 58, newEdition: 58 }, [REBIND58_APPROVAL_FORMAT]: { predecessor: BUILD58_PROVENANCE, successor: BUILD58_PROVENANCE, oldEdition: 58, newEdition: 58 },
} }
export function requireCurrentCatalogueDefinition(approval,definition){ export function requireCurrentCatalogueDefinition(approval,definition){
@@ -133,7 +137,7 @@ async function session(pool,deadlineAt,work){
return value return value
} }
async function observeCurrentCatalogue(s,manifestSha256){ async function observeCurrentCatalogue(s,manifestSha256){
const security=await protectedStructure(s,installation,definition?.edition===58),catalogue=await collectFixedCatalogue(s) const security=await protectedStructure(s,installation,(definition?.edition??44)>=58),catalogue=await collectFixedCatalogue(s)
if(catalogue.manifestSha256!==manifestSha256||catalogue.definitionSha256!==definition.definitionSha256)throw Error('Catalogue evidence differs from the approved migration manifest/definition') if(catalogue.manifestSha256!==manifestSha256||catalogue.definitionSha256!==definition.definitionSha256)throw Error('Catalogue evidence differs from the approved migration manifest/definition')
// Inspect one extra row so an unexpected marker cannot hide after the expected prefix. // Inspect one extra row so an unexpected marker cannot hide after the expected prefix.
const expected=MIGRATION_MANIFEST.map(pin=>pin.file.slice(0,-4)) const expected=MIGRATION_MANIFEST.map(pin=>pin.file.slice(0,-4))
@@ -209,7 +213,7 @@ async function inspectPublication(pool,proposal,{deadlineAt=Date.now()+120000}={
if(!proposal||proposal.installationId!==installation.installationId||!(/^[a-f0-9]{64}$/).test(proposal.headSha256)||proposal.previousHeadSha256!==null&&!(/^[a-f0-9]{64}$/).test(proposal.previousHeadSha256))throw Error('Bounded public proposal required') if(!proposal||proposal.installationId!==installation.installationId||!(/^[a-f0-9]{64}$/).test(proposal.headSha256)||proposal.previousHeadSha256!==null&&!(/^[a-f0-9]{64}$/).test(proposal.previousHeadSha256))throw Error('Bounded public proposal required')
return session(pool,deadlineAt,async s=>{ return session(pool,deadlineAt,async s=>{
s.phase('publication-inspection');await s.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');s.begun(true) s.phase('publication-inspection');await s.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');s.begun(true)
const first=await ownedContext(s,installation,PUBLISHER,'publisher-read');await protectedStructure(s,installation,definition?.edition===58) const first=await ownedContext(s,installation,PUBLISHER,'publisher-read');await protectedStructure(s,installation,(definition?.edition??44)>=58)
if(canonical(sourceCoordinates(first))!==canonical(installation.expectedSource))throw Error('Pinned inspection source mismatch') if(canonical(sourceCoordinates(first))!==canonical(installation.expectedSource))throw Error('Pinned inspection source mismatch')
const facade=Object.freeze({query:(sql,values)=>s.query(sql,values)}),options={deadlineAt} const facade=Object.freeze({query:(sql,values)=>s.query(sql,values)}),options={deadlineAt}
const observation=await captureDatabaseSourceObservation(facade,options);await sourceVerifier.verify(facade,observation,options) const observation=await captureDatabaseSourceObservation(facade,options);await sourceVerifier.verify(facade,observation,options)
@@ -251,7 +255,8 @@ async function preflightCurrentProfile(pool,{deadlineAt=Date.now()+120000}={}){
} }
async function inspectCurrentCatalogue(pool,{deadlineAt=Date.now()+120000}={}){ async function inspectCurrentCatalogue(pool,{deadlineAt=Date.now()+120000}={}){
const manifestSha256=migrationManifestDigest() const manifestSha256=migrationManifestDigest()
if(definition?.edition!==58||definition.manifestSha256!==manifestSha256||definition.definitionSha256!==BUILD58_PROVENANCE.templateSha256)throw Error('Approved source58 definition required') const expected={58:BUILD58_PROVENANCE,59:BUILD59_PROVENANCE,60:BUILD60_PROVENANCE}[definition?.edition]
if(!expected||definition.manifestSha256!==manifestSha256||definition.definitionSha256!==expected.templateSha256)throw Error('Approved current writer definition required')
return session(pool,deadlineAt,async s=>{ return session(pool,deadlineAt,async s=>{
s.phase('source-catalogue-inspection');await s.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');s.begun(true) s.phase('source-catalogue-inspection');await s.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');s.begun(true)
const first=await ownedContext(s,installation,PUBLISHER,'publisher-read') const first=await ownedContext(s,installation,PUBLISHER,'publisher-read')
@@ -261,9 +266,10 @@ async function inspectCurrentCatalogue(pool,{deadlineAt=Date.now()+120000}={}){
const initial=await sourceVerifier.verify(facade,observation,options) const initial=await sourceVerifier.verify(facade,observation,options)
const {security,catalogSha256}=await observeCurrentCatalogue(s,manifestSha256) const {security,catalogSha256}=await observeCurrentCatalogue(s,manifestSha256)
const current=await readCurrent(s,installation,{validNow:false}) const current=await readCurrent(s,installation,{validNow:false})
if(!current||current.policy.definitionSha256!==definition.definitionSha256||current.policy.manifestSha256!==manifestSha256|| const allowedHeads=definition.edition===60?[BUILD59_PROVENANCE,BUILD60_PROVENANCE]:definition.edition===59?[BUILD58_PROVENANCE,BUILD59_PROVENANCE]:[BUILD58_PROVENANCE]
if(!current||!allowedHeads.some(head=>head.templateSha256===current.policy.definitionSha256&&head.manifestSha256===current.policy.manifestSha256)||
canonical(current.policy.source)!==canonical(sourceCoordinates(first))||canonical(current.policy.roles)!==canonical(security.roles)){ canonical(current.policy.source)!==canonical(sourceCoordinates(first))||canonical(current.policy.roles)!==canonical(security.roles)){
throw Error('Approved source58 predecessor required') throw Error('Approved same-installation writer predecessor required')
} }
const terminal=await sourceVerifier.verify(facade,observation,options) const terminal=await sourceVerifier.verify(facade,observation,options)
if(initial.platformProtectionVerified!==true||terminal.platformProtectionVerified!==true)throw Error('Protected source evidence required') if(initial.platformProtectionVerified!==true||terminal.platformProtectionVerified!==true)throw Error('Protected source evidence required')
@@ -8,8 +8,10 @@ const digest = (value: string) => createHash("sha256").update(value).digest("hex
export const REVIEWED_PREDECESSORS = [ export const REVIEWED_PREDECESSORS = [
{ length: 44, manifestSha256: "fffae3381732e6f276ba276aca7185f6a87587edf8272ba42763b7f49bc59ef5" }, { length: 44, manifestSha256: "fffae3381732e6f276ba276aca7185f6a87587edf8272ba42763b7f49bc59ef5" },
{ length: 56, manifestSha256: "b371d8d261f7dd69cf0e2ebc48d4316e3ad804360046bbaaf20e715da8812521" }, { length: 56, manifestSha256: "b371d8d261f7dd69cf0e2ebc48d4316e3ad804360046bbaaf20e715da8812521" },
{ length: 57, manifestSha256: "7dbd678e59740c14a29594180c86b85b3b2dd53fd5aa7a72da6d14a513760dbc" },
{ length: 58, manifestSha256: "52c49786b6204dc11577131670cc0098c165ef54d419c25f0c70759e435c99fb" },
] as const ] as const
export const REVIEWED_SUCCESSOR_MANIFEST = "7dbd678e59740c14a29594180c86b85b3b2dd53fd5aa7a72da6d14a513760dbc" export const REVIEWED_SUCCESSOR_MANIFEST = "25913d7ea3e31361c6853084e9eed6f1a1b45806232122097ba2b7e830a315a9"
export const canonical = (value: unknown): string => JSON.stringify(value, (_key, item: unknown) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item) export const canonical = (value: unknown): string => JSON.stringify(value, (_key, item: unknown) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item)
export async function observation(intent: DatabaseSchemaIntent, pin: MigrationReview, existingKey = false) { export async function observation(intent: DatabaseSchemaIntent, pin: MigrationReview, existingKey = false) {
// Fixed, purpose-separated server-keyed ACK issuer. Caller-supplied hashes // Fixed, purpose-separated server-keyed ACK issuer. Caller-supplied hashes
@@ -55,7 +57,7 @@ export async function exactHistory(rows: Record<string, unknown>[], current: Ret
return refuse("Migration release is not the exact internally recorded legacy release") return refuse("Migration release is not the exact internally recorded legacy release")
} }
if (pin ? terminal.observationSha256 !== await observation(terminal.intent, pin, existingKey) : if (pin ? terminal.observationSha256 !== await observation(terminal.intent, pin, existingKey) :
terminal.intent.manifestSha256 !== manifest || terminal.observationSha256 !== await legacy0037AdoptionObservation(terminal.intent)) { terminal.observationSha256 !== await legacy0037AdoptionObservation(terminal.intent)) {
return refuse("Migration receipt is not the exact internally recorded file ACK") return refuse("Migration receipt is not the exact internally recorded file ACK")
} }
pin ??= MIGRATION_MANIFEST[36] pin ??= MIGRATION_MANIFEST[36]
+21 -3
View File
@@ -185,6 +185,7 @@ test("known completed prefix resumes after fresh ownership without replaying ear
const reviewed44 = "fffae3381732e6f276ba276aca7185f6a87587edf8272ba42763b7f49bc59ef5" const reviewed44 = "fffae3381732e6f276ba276aca7185f6a87587edf8272ba42763b7f49bc59ef5"
const reviewed56 = "b371d8d261f7dd69cf0e2ebc48d4316e3ad804360046bbaaf20e715da8812521" const reviewed56 = "b371d8d261f7dd69cf0e2ebc48d4316e3ad804360046bbaaf20e715da8812521"
const reviewed57 = "7dbd678e59740c14a29594180c86b85b3b2dd53fd5aa7a72da6d14a513760dbc"
test("reviewed 44 migration history keeps its original keyed receipts and resumes only the current tail", async () => { test("reviewed 44 migration history keeps its original keyed receipts and resumes only the current tail", async () => {
const f = fixture() const f = fixture()
f.seedCompletedHistory(46, index => index < 44 ? reviewed44 : manifest.migrationManifestDigest()) f.seedCompletedHistory(46, index => index < 44 ? reviewed44 : manifest.migrationManifestDigest())
@@ -199,13 +200,13 @@ test("reviewed 44 migration history keeps its original keyed receipts and resume
assert(f.events.every(event => !event.startsWith("file:"))) assert(f.events.every(event => !event.startsWith("file:")))
}) })
test("complete 56 receipts with or without the inherited 44 prefix dispatch only index 0057", async () => { test("complete 56 receipts with or without the inherited 44 prefix dispatch the remaining files", async () => {
for (const mixed of [false, true]) { for (const mixed of [false, true]) {
const f = fixture() const f = fixture()
f.seedCompletedHistory(56, index => mixed && index < 44 ? reviewed44 : reviewed56) f.seedCompletedHistory(56, index => mixed && index < 44 ? reviewed44 : reviewed56)
const previous = structuredClone([...f.history.values()]) const previous = structuredClone([...f.history.values()])
assert.equal((await f.run()).completedFiles, pins.length) assert.equal((await f.run()).completedFiles, pins.length)
assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0057_mcp_routing_charge_audit_index.sql"]) assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0057_mcp_routing_charge_audit_index.sql", "file:0058_internet_exchange.sql", "file:0059_server_poll_journal_limits.sql"])
assert.deepEqual([...f.history.values()].slice(0, 56), previous) assert.deepEqual([...f.history.values()].slice(0, 56), previous)
f.events.length = 0 f.events.length = 0
assert.equal((await f.run()).completedFiles, pins.length) assert.equal((await f.run()).completedFiles, pins.length)
@@ -213,6 +214,23 @@ test("complete 56 receipts with or without the inherited 44 prefix dispatch only
} }
}) })
test("the source58 migration history advances through IX and the poll journal migration", async () => {
const f = fixture()
f.seedCompletedHistory(57, index => index < 44 ? reviewed44 : index < 56 ? reviewed56 : reviewed57)
const previous = structuredClone([...f.history.values()])
assert.equal((await f.run()).completedFiles, pins.length)
assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0058_internet_exchange.sql", "file:0059_server_poll_journal_limits.sql"])
assert.deepEqual([...f.history.values()].slice(0, 57), previous)
})
test("the source59 production prefix advances only through the poll journal migration", async () => {
const f = fixture()
f.seedCompletedHistory(58, index => index < 44 ? reviewed44 : index < 56 ? reviewed56 : index < 57 ? reviewed57 :
"52c49786b6204dc11577131670cc0098c165ef54d419c25f0c70759e435c99fb")
assert.equal((await f.run()).completedFiles, pins.length)
assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0059_server_poll_journal_limits.sql"])
})
test("history 56 cannot omit a receipt or interleave another manifest", async () => { test("history 56 cannot omit a receipt or interleave another manifest", async () => {
for (const invalid of ["incomplete", "interleaved"] as const) { for (const invalid of ["incomplete", "interleaved"] as const) {
const f = fixture() const f = fixture()
@@ -243,7 +261,7 @@ test("reviewed marker guards are rechecked after each file and a change stops th
} }
const reviewed = prepare() const reviewed = prepare()
assert.equal((await reviewed.run()).completedFiles, pins.length) assert.equal((await reviewed.run()).completedFiles, pins.length)
assert.equal(reviewed.events.filter(event => event === "reviewed marker guards").length, 15) assert.equal(reviewed.events.filter(event => event === "reviewed marker guards").length, pins.length - 44 + 2)
const damaged = prepare() const damaged = prepare()
damaged.faults.guardDrift = true damaged.faults.guardDrift = true
await assert.rejects(damaged.run()) await assert.rejects(damaged.run())
@@ -2,10 +2,10 @@ import assert from "node:assert/strict"
import { HEAD_DOMAIN, POLICY_DOMAIN, sha } from "./application-writer-profile-format.js" import { HEAD_DOMAIN, POLICY_DOMAIN, sha } from "./application-writer-profile-format.js"
import { stagedModelClient, syntheticFixture } from "./application-writer-profile-registry-read-model.test.js" import { stagedModelClient, syntheticFixture } from "./application-writer-profile-registry-read-model.test.js"
import { approvedRuntimeWriterProfile } from "./database-runtime-writer-profile.js" import { approvedRuntimeWriterProfile } from "./database-runtime-writer-profile.js"
import { RESTORE_WRITER_PROFILE_DEFINITION_SHA256, RESTORE_WRITER_PROFILE_MANIFEST_SHA256 } from "./database-restore-quarantine-profile.js" import { POLL_WRITER_PROFILE_DEFINITION_SHA256, POLL_WRITER_PROFILE_MANIFEST_SHA256 } from "./server-poll-writer-profile.js"
const { subject, policy: basePolicy, state, signBody } = syntheticFixture("1") const { subject, policy: basePolicy, state, signBody } = syntheticFixture("1")
const policy = { ...basePolicy, definitionSha256: RESTORE_WRITER_PROFILE_DEFINITION_SHA256, manifestSha256: RESTORE_WRITER_PROFILE_MANIFEST_SHA256 } const policy = { ...basePolicy, definitionSha256: POLL_WRITER_PROFILE_DEFINITION_SHA256, manifestSha256: POLL_WRITER_PROFILE_MANIFEST_SHA256 }
const expected = { installationId: subject.installationId, source: policy.source, roles: policy.roles } const expected = { installationId: subject.installationId, source: policy.source, roles: policy.roles }
function publish(next: typeof policy, previous = state.latest[0]) { function publish(next: typeof policy, previous = state.latest[0]) {
@@ -1,7 +1,7 @@
import { z } from "zod" import { z } from "zod"
import { canonical, epoch, publicKey, type ApplicationWriterPolicy } from "./application-writer-profile-format.js" import { canonical, epoch, publicKey, type ApplicationWriterPolicy } from "./application-writer-profile-format.js"
import { readCurrentApplicationWriterProfile, type ApplicationWriterRegistryReadSql } from "./application-writer-profile-registry-read.js" import { readCurrentApplicationWriterProfile, type ApplicationWriterRegistryReadSql } from "./application-writer-profile-registry-read.js"
import { RESTORE_WRITER_PROFILE_DEFINITION_SHA256, RESTORE_WRITER_PROFILE_MANIFEST_SHA256 } from "./database-restore-quarantine-profile.js" import { POLL_WRITER_PROFILE_DEFINITION_SHA256, POLL_WRITER_PROFILE_MANIFEST_SHA256 } from "./server-poll-writer-profile.js"
const digest = z.string().regex(/^[a-f0-9]{64}$/) const digest = z.string().regex(/^[a-f0-9]{64}$/)
const approvalSchema = z.object({ const approvalSchema = z.object({
@@ -26,8 +26,8 @@ export function approvedRuntimeWriterProfile(
async check(client: ApplicationWriterRegistryReadSql) { async check(client: ApplicationWriterRegistryReadSql) {
const current = await readCurrentApplicationWriterProfile(client, subject) const current = await readCurrentApplicationWriterProfile(client, subject)
const policy = current?.policy const policy = current?.policy
if (!current || !policy || policy.definitionSha256 !== RESTORE_WRITER_PROFILE_DEFINITION_SHA256 || if (!current || !policy || policy.definitionSha256 !== POLL_WRITER_PROFILE_DEFINITION_SHA256 ||
policy.manifestSha256 !== RESTORE_WRITER_PROFILE_MANIFEST_SHA256 || policy.manifestSha256 !== POLL_WRITER_PROFILE_MANIFEST_SHA256 ||
canonical(policy.source) !== canonical(expected.source) || canonical(policy.roles) !== canonical(expected.roles)) { canonical(policy.source) !== canonical(expected.source) || canonical(policy.roles) !== canonical(expected.roles)) {
throw new Error("Текущий подписанный профиль записи PostgreSQL не подтверждён") throw new Error("Текущий подписанный профиль записи PostgreSQL не подтверждён")
} }
@@ -0,0 +1,33 @@
export const IX_WRITER_PROFILE_MANIFEST_SHA256 = "52c49786b6204dc11577131670cc0098c165ef54d419c25f0c70759e435c99fb"
export const IX_WRITER_PROFILE_DEFINITION_SHA256 = "8f6bcf73d3304879e023beeccc11cd2fa443aa4dd43b913d6f30419267ca64f3"
const rights = {
ix_segments: "SELECT, INSERT, UPDATE",
ix_segment_devices: "SELECT, INSERT, DELETE",
ix_segment_revisions: "SELECT, INSERT",
} as const
function identifier(name: string) {
if (!/^[a-z_][a-z0-9_]{0,62}$/.test(name)) throw new Error("Invalid IX profile role")
return `"${name}"`
}
/** Execute offline as application operator, within a retained preadmitted DDL transaction. */
export function ixWriterProfileEnrollmentSql(runtimeRole: string, captureRole: string) {
if (runtimeRole === captureRole) throw new Error("IX profile roles must be distinct")
const runtime = identifier(runtimeRole), capture = identifier(captureRole)
return Object.entries(rights).flatMap(([name, permissions]) => {
const table = "public." + name
return [
`REVOKE ALL ON TABLE ${table} FROM PUBLIC, ${runtime}, ${capture}`,
`GRANT ${permissions} ON TABLE ${table} TO ${runtime}`,
`GRANT SELECT ON TABLE ${table} TO ${capture}`,
`CREATE TRIGGER server_partition_writer_guard BEFORE INSERT OR UPDATE OR DELETE ON ${table} FOR EACH ROW EXECUTE FUNCTION public.server_partition_writer_guard()`,
`ALTER TABLE ${table} ENABLE ALWAYS TRIGGER server_partition_writer_guard`,
`CREATE TRIGGER candidate_application_statement_guard BEFORE INSERT OR UPDATE OR DELETE ON ${table} FOR EACH STATEMENT EXECUTE FUNCTION public.server_partition_writer_guard()`,
`ALTER TABLE ${table} ENABLE ALWAYS TRIGGER candidate_application_statement_guard`,
`CREATE TRIGGER candidate_truncate_preadmitted BEFORE TRUNCATE ON ${table} FOR EACH STATEMENT EXECUTE FUNCTION mmapp_control.candidate_truncate_preadmitted()`,
`ALTER TABLE ${table} ENABLE ALWAYS TRIGGER candidate_truncate_preadmitted`,
]
}).join(";\n") + ";\n"
}
+5 -5
View File
@@ -12,10 +12,10 @@ const reviewed = (source: string, extra: Partial<MigrationReview> = {}) => {
const bytes = Buffer.from(source), file = "9000_fixture.sql" const bytes = Buffer.from(source), file = "9000_fixture.sql"
return () => analyzeMigration(file, bytes, { file, sha256: createHash("sha256").update(bytes).digest("hex"), transaction: "owner-transaction", selfMarker: false, opaqueBodies: 0, bodyReview: [], effects: ["Explicit inert fixture review"], ...extra }) return () => analyzeMigration(file, bytes, { file, sha256: createHash("sha256").update(bytes).digest("hex"), transaction: "owner-transaction", selfMarker: false, opaqueBodies: 0, bodyReview: [], effects: ["Explicit inert fixture review"], ...extra })
} }
await test("all 57 exact file pins and every top-level schema operation are inventoried", () => { await test("all 59 exact file pins and every top-level schema operation are inventoried", () => {
assert.equal(inventory.length, 57); assert.equal(MIGRATION_MANIFEST.length, 57) assert.equal(inventory.length, 59); assert.equal(MIGRATION_MANIFEST.length, 59)
assert.equal(inventory.filter(file => file.transaction === "owner-transaction").length, 17) assert.equal(inventory.filter(file => file.transaction === "owner-transaction").length, 17)
assert.equal(inventory.filter(file => file.transaction === "self-managed-single-transaction").length, 40) assert.equal(inventory.filter(file => file.transaction === "self-managed-single-transaction").length, 42)
assert(inventory.every(file => file.operations.length === file.statementCount && file.effects.length > 0)) assert(inventory.every(file => file.operations.length === file.statementCount && file.effects.length > 0))
let tables = new Set<string>() let tables = new Set<string>()
for (const file of inventory) { for (const file of inventory) {
@@ -32,8 +32,8 @@ await test("DO BEGIN and stored function BEGIN are never transaction boundaries"
assert.equal(endpoint.topLevelTransactionControls.length, 2); assert.equal(endpoint.opaqueBodies.length, 2) assert.equal(endpoint.topLevelTransactionControls.length, 2); assert.equal(endpoint.opaqueBodies.length, 2)
assert.deepEqual(endpoint.opaqueBodies.map(body => body.kind), ["stored-function-body", "executed-do-body"]) assert.deepEqual(endpoint.opaqueBodies.map(body => body.kind), ["stored-function-body", "executed-do-body"])
}) })
await test("0035 through 0057 have exact atomic file-owned terminal markers", () => { await test("0035 through 0059 have exact atomic file-owned terminal markers", () => {
assert.deepEqual(inventory.filter(file => file.selfMarker).map(file => file.id), ["0035_server_probe_journal", "0036_diagnostic_cancellations", "0037_server_probe_storage_v2", "0038_server_poll_journal_and_writer_guards", "0039_server_poll_storage", "0040_mcp_routing_reservations", "0041_server_poll_terminal_archives", "0042_server_poll_settings_epoch", "0043_mcp_routing_forward_charges", "0044_mcp_routing_manual_inverse_charges", "0045_mcp_operation_replay_tombstones", "0046_server_poll_operation_retirement", "0047_server_poll_retirement_claims", "0048_mcp_ordinary_retirement_claims", "0049_mcp_ordinary_telemetry_retirement", "0050_server_probe_retired_sources", "0051_server_probe_retirement_claims", "0052_server_probe_retired_gc", "0053_server_probe_terminal_proofs", "0054_mcp_geoip_retirement", "0055_mcp_backup_schedule_retirement", "0056_mcp_manual_inverse_recovery_v8", "0057_mcp_routing_charge_audit_index"]) assert.deepEqual(inventory.filter(file => file.selfMarker).map(file => file.id), ["0035_server_probe_journal", "0036_diagnostic_cancellations", "0037_server_probe_storage_v2", "0038_server_poll_journal_and_writer_guards", "0039_server_poll_storage", "0040_mcp_routing_reservations", "0041_server_poll_terminal_archives", "0042_server_poll_settings_epoch", "0043_mcp_routing_forward_charges", "0044_mcp_routing_manual_inverse_charges", "0045_mcp_operation_replay_tombstones", "0046_server_poll_operation_retirement", "0047_server_poll_retirement_claims", "0048_mcp_ordinary_retirement_claims", "0049_mcp_ordinary_telemetry_retirement", "0050_server_probe_retired_sources", "0051_server_probe_retirement_claims", "0052_server_probe_retired_gc", "0053_server_probe_terminal_proofs", "0054_mcp_geoip_retirement", "0055_mcp_backup_schedule_retirement", "0056_mcp_manual_inverse_recovery_v8", "0057_mcp_routing_charge_audit_index", "0058_internet_exchange", "0059_server_poll_journal_limits"])
for (const file of inventory.filter(file => file.selfMarker)) { assert.equal(file.selfMarker!.atomicWithAllFileEffects, true); assert.equal(file.selfMarker!.statement, file.statementCount - 2); assert.equal(file.currentOuterMarkerGap, false) } for (const file of inventory.filter(file => file.selfMarker)) { assert.equal(file.selfMarker!.atomicWithAllFileEffects, true); assert.equal(file.selfMarker!.statement, file.statementCount - 2); assert.equal(file.currentOuterMarkerGap, false) }
assert.equal(inventory.filter(file => file.currentOuterMarkerGap).length, 34) assert.equal(inventory.filter(file => file.currentOuterMarkerGap).length, 34)
}) })
+26 -1
View File
@@ -879,6 +879,31 @@ const classifiedMigrationPins: readonly MigrationReview[] = [
"effects": [ "effects": [
"Adds the partial routing charge audit lookup index. Retains all rows and permissions." "Adds the partial routing charge audit lookup index. Retains all rows and permissions."
] ]
},
{
"file": "0058_internet_exchange.sql",
"sha256": "75e2842f8d45909c37d1387bdfadf659606e6227b5542289e8c1d98269f5a0cd",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Allows the IX Node server type without changing existing rows.",
"Adds versioned IX configuration and device references."
]
},
{
"file": "0059_server_poll_journal_limits.sql",
"sha256": "9b638ed5649ef75359b24ef61c80bf59390372c98c713447ddb6e32e61b6f5be",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 1,
"bodyReview": [
"Replaces the existing invoker admission trigger function and removes only the aggregate count, row and byte ceilings from the insertion path. Authority, locking, accounting, compaction and GC checks remain enforced."
],
"effects": [
"Removes the journal quota while preserving exact reconciliation constraints and all previously retained histories."
]
} }
] ]
@@ -901,7 +926,7 @@ export const migrationManifestDigest = () => hash(JSON.stringify(MIGRATION_MANIF
// resetting the accumulated public table set at the reviewed destructive0002. // resetting the accumulated public table set at the reviewed destructive0002.
// This is a necessary presence check, not a substitute for exact live column, // This is a necessary presence check, not a substitute for exact live column,
// constraint/index/function/trigger comparison by the control protocol. // constraint/index/function/trigger comparison by the control protocol.
export const CURRENT_REQUIRED_TABLES: readonly string[] = Object.freeze(["acme_settings","alert_engine_confirm_pending","alert_engine_cursor","alert_engine_prev_live","alert_engine_state","alert_groups","alert_history","alert_outbox","alert_rule_conditions","alert_rule_targets","alert_rules","alert_telegram_settings","app_users","backup_entries","backup_schedule_settings","backup_storage_settings","certificate_issue_jobs","certificate_renew_settings","config_revisions","data_migration","events","evobgp_settings","filter_rules","flow_asn_meta","flow_buckets","flow_daily_dims","flow_daily_facts","flow_hour_facts","flow_ip_meta","flow_minute_dims","flow_minute_stats","flow_settings_intents","flow_write_receipts","geoip_settings","internet_path_settings","internet_path_snapshots","mcp_artifacts","mcp_audit","mcp_budget_buckets","mcp_connections","mcp_credentials","mcp_diagnostic_cancellations","mcp_drift","mcp_grants","mcp_management_channels","mcp_oauth_clients","mcp_oauth_requests","mcp_operation_checkpoints","mcp_operation_replay_tombstones","mcp_operation_steps","mcp_operations","mcp_ordinary_retirement_claims","mcp_owner_revocations","mcp_path_checks","mcp_plans","mcp_portal_events","mcp_protections","mcp_read_leases","mcp_recovery_intents","mcp_requests","mcp_routing_forward_charges","mcp_routing_manual_inverse_charges","mcp_routing_observations","mcp_routing_profiles","mcp_routing_reservation_slots","mcp_routing_reservations","mcp_scoped_recovery_intents","mcp_secrets","mcp_settings","mcp_unauthorized_buckets","recursive_routes","router_log_collection_state","router_log_entries","router_log_settings","scheduler_runs","schema_migrations","server_poll_acks","server_poll_archives","server_poll_executions","server_poll_intents","server_poll_quarantines","server_poll_receipts","server_poll_retirement_claims","server_poll_storage_admissions","server_poll_storage_usage","server_probe_execution_payloads","server_probe_execution_quarantines","server_probe_execution_stages","server_probe_executions","server_probe_retired_sources","server_probe_retirement_claims","server_probe_storage_admissions","server_probe_storage_usage","server_probe_terminal_proofs","server_snapshots","servers","servers_api_ping_settings","servers_rest_ping_samples","traffic_collection_state","traffic_flow_settings","traffic_samples","traffic_settings","uptime_probe_samples","uptime_probes","uptime_resource_samples","uptime_settings","uptime_speed_probes","uptime_speed_test_runs","user_interface_bindings","vrf_production_tickets"]) export const CURRENT_REQUIRED_TABLES: readonly string[] = Object.freeze(["acme_settings","alert_engine_confirm_pending","alert_engine_cursor","alert_engine_prev_live","alert_engine_state","alert_groups","alert_history","alert_outbox","alert_rule_conditions","alert_rule_targets","alert_rules","alert_telegram_settings","app_users","backup_entries","backup_schedule_settings","backup_storage_settings","certificate_issue_jobs","certificate_renew_settings","config_revisions","data_migration","events","evobgp_settings","filter_rules","flow_asn_meta","flow_buckets","flow_daily_dims","flow_daily_facts","flow_hour_facts","flow_ip_meta","flow_minute_dims","flow_minute_stats","flow_settings_intents","flow_write_receipts","geoip_settings","internet_path_settings","internet_path_snapshots","ix_segment_devices","ix_segment_revisions","ix_segments","mcp_artifacts","mcp_audit","mcp_budget_buckets","mcp_connections","mcp_credentials","mcp_diagnostic_cancellations","mcp_drift","mcp_grants","mcp_management_channels","mcp_oauth_clients","mcp_oauth_requests","mcp_operation_checkpoints","mcp_operation_replay_tombstones","mcp_operation_steps","mcp_operations","mcp_ordinary_retirement_claims","mcp_owner_revocations","mcp_path_checks","mcp_plans","mcp_portal_events","mcp_protections","mcp_read_leases","mcp_recovery_intents","mcp_requests","mcp_routing_forward_charges","mcp_routing_manual_inverse_charges","mcp_routing_observations","mcp_routing_profiles","mcp_routing_reservation_slots","mcp_routing_reservations","mcp_scoped_recovery_intents","mcp_secrets","mcp_settings","mcp_unauthorized_buckets","recursive_routes","router_log_collection_state","router_log_entries","router_log_settings","scheduler_runs","schema_migrations","server_poll_acks","server_poll_archives","server_poll_executions","server_poll_intents","server_poll_quarantines","server_poll_receipts","server_poll_retirement_claims","server_poll_storage_admissions","server_poll_storage_usage","server_probe_execution_payloads","server_probe_execution_quarantines","server_probe_execution_stages","server_probe_executions","server_probe_retired_sources","server_probe_retirement_claims","server_probe_storage_admissions","server_probe_storage_usage","server_probe_terminal_proofs","server_snapshots","servers","servers_api_ping_settings","servers_rest_ping_samples","traffic_collection_state","traffic_flow_settings","traffic_samples","traffic_settings","uptime_probe_samples","uptime_probes","uptime_resource_samples","uptime_settings","uptime_speed_probes","uptime_speed_test_runs","user_interface_bindings","vrf_production_tickets"])
export interface LegacyBaselineEvidence { export interface LegacyBaselineEvidence {
inventoryComplete: boolean; databaseGeneration: string; unresolvedAttemptIds: readonly string[] inventoryComplete: boolean; databaseGeneration: string; unresolvedAttemptIds: readonly string[]
+1 -1
View File
@@ -63,7 +63,7 @@ export const servers = pgTable("servers", {
useSsl: boolean("use_ssl").notNull().default(true), useSsl: boolean("use_ssl").notNull().default(true),
verifySsl: boolean("verify_ssl").notNull().default(false), verifySsl: boolean("verify_ssl").notNull().default(false),
routingEndpointEpoch: uuid("routing_endpoint_epoch").notNull().defaultRandom(), routingEndpointEpoch: uuid("routing_endpoint_epoch").notNull().defaultRandom(),
type: text("type", { enum: ["jump-host", "exit-node", "home-router"] }) type: text("type", { enum: ["jump-host", "exit-node", "home-router", "ix-node"] })
.notNull().default("home-router"), .notNull().default("home-router"),
site: text("site").notNull().default(""), site: text("site").notNull().default(""),
country: text("country").notNull().default(""), country: text("country").notNull().default(""),
@@ -0,0 +1,2 @@
export const POLL_WRITER_PROFILE_MANIFEST_SHA256 = "25913d7ea3e31361c6853084e9eed6f1a1b45806232122097ba2b7e830a315a9"
export const POLL_WRITER_PROFILE_DEFINITION_SHA256 = "0bf9596d6fec209959bb00761e1396ad292d50a1e7d4c9f17d1222da75007a49"
+4
View File
@@ -27,6 +27,7 @@ import internetPathRoutes from "./routes/internet-path.js"
import evobgpRoutes from "./routes/evobgp.js" import evobgpRoutes from "./routes/evobgp.js"
import { createStorageProbeRoutes } from "./routes/probe-storage-handler.js" import { createStorageProbeRoutes } from "./routes/probe-storage-handler.js"
import schedulerRoutes from "./routes/scheduler.js" import schedulerRoutes from "./routes/scheduler.js"
import { ConfigurationBusyError } from "./services/config-mutation-lock.js"
import sidebarCountsRoutes from "./routes/sidebar-counts.js" import sidebarCountsRoutes from "./routes/sidebar-counts.js"
import alertsRoutes from "./routes/alerts.js" import alertsRoutes from "./routes/alerts.js"
import backupsRoutes from "./routes/backups.js" import backupsRoutes from "./routes/backups.js"
@@ -39,6 +40,7 @@ import vxlanRoutes from "./routes/vxlan.js"
import containersRoutes from "./routes/containers.js" import containersRoutes from "./routes/containers.js"
import firewallRoutes from "./routes/firewall.js" import firewallRoutes from "./routes/firewall.js"
import greRoutes from "./routes/gre.js" import greRoutes from "./routes/gre.js"
import ixRoutes from "./routes/internet-exchange.js"
import usersRoutes from "./routes/users.js" import usersRoutes from "./routes/users.js"
import statisticsRoutes from "./routes/statistics.js" import statisticsRoutes from "./routes/statistics.js"
import logsRoutes from "./routes/logs.js" import logsRoutes from "./routes/logs.js"
@@ -104,6 +106,7 @@ export async function buildApp(opts?: {
return reply.status(status).send({ error: "Внутренняя ошибка сервера" }) return reply.status(status).send({ error: "Внутренняя ошибка сервера" })
} }
const message = error instanceof Error ? error.message : "Ошибка запроса" const message = error instanceof Error ? error.message : "Ошибка запроса"
if (error instanceof ConfigurationBusyError) return reply.code(409).send({ error: message, code: error.code })
return reply.status(status).send({ error: message }) return reply.status(status).send({ error: message })
}) })
@@ -162,6 +165,7 @@ export async function buildApp(opts?: {
await app.register(containersRoutes, { prefix: "/api" }) await app.register(containersRoutes, { prefix: "/api" })
await app.register(firewallRoutes, { prefix: "/api" }) await app.register(firewallRoutes, { prefix: "/api" })
await app.register(greRoutes, { prefix: "/api" }) await app.register(greRoutes, { prefix: "/api" })
await app.register(ixRoutes, { prefix: "/api" })
await app.register(usersRoutes, { prefix: "/api" }) await app.register(usersRoutes, { prefix: "/api" })
await app.register(statisticsRoutes, { prefix: "/api" }) await app.register(statisticsRoutes, { prefix: "/api" })
await app.register(logsRoutes, { prefix: "/api" }) await app.register(logsRoutes, { prefix: "/api" })
+2
View File
@@ -186,6 +186,7 @@ const RULES: Rule[] = [
p.startsWith("/api/recursive") || p.startsWith("/api/recursive") ||
p.startsWith("/api/probes") || p.startsWith("/api/probes") ||
p.startsWith("/api/internet-path") || p.startsWith("/api/internet-path") ||
p === "/api/ix" || p.startsWith("/api/ix/") ||
p.startsWith("/api/exec") || p.startsWith("/api/exec") ||
p.startsWith("/api/wireguard") || p.startsWith("/api/wireguard") ||
p.startsWith("/api/ipsec") || p.startsWith("/api/ipsec") ||
@@ -201,6 +202,7 @@ const RULES: Rule[] = [
p.startsWith("/api/recursive") || p.startsWith("/api/recursive") ||
p.startsWith("/api/probes") || p.startsWith("/api/probes") ||
p.startsWith("/api/internet-path") || p.startsWith("/api/internet-path") ||
p === "/api/ix" || p.startsWith("/api/ix/") ||
p.startsWith("/api/exec") || p.startsWith("/api/exec") ||
p.startsWith("/api/wireguard") || p.startsWith("/api/wireguard") ||
p.startsWith("/api/ipsec") || p.startsWith("/api/ipsec") ||
@@ -12,6 +12,7 @@ export const ACCEPTANCE_SHARDS: Record<string, (actor: AuthUser) => Promise<unkn
acceptRouteCommunityContextMcp: async actor => (await import("./routing-community-context-acceptance.js")).acceptRouteCommunityContextMcp(actor), acceptRouteCommunityContextMcp: async actor => (await import("./routing-community-context-acceptance.js")).acceptRouteCommunityContextMcp(actor),
acceptWireguardPeerCreation: async actor => (await import("./wireguard-peer-create-acceptance.js")).acceptWireguardPeerCreation(actor), acceptWireguardPeerCreation: async actor => (await import("./wireguard-peer-create-acceptance.js")).acceptWireguardPeerCreation(actor),
acceptWireguardInterfaceUpdate: async actor => (await import("./wireguard-interface-update-acceptance.js")).acceptWireguardInterfaceUpdate(actor), acceptWireguardInterfaceUpdate: async actor => (await import("./wireguard-interface-update-acceptance.js")).acceptWireguardInterfaceUpdate(actor),
acceptInterfaceRename: async actor => (await import("./interface-rename-acceptance.js")).acceptInterfaceRename(actor),
acceptWireguardImport: async actor => (await import("./wireguard-import-acceptance.js")).acceptWireguardImport(actor), acceptWireguardImport: async actor => (await import("./wireguard-import-acceptance.js")).acceptWireguardImport(actor),
verifyMcpFlowOverlay: async actor => (await import("../../test/mcp-flow-overlay.js")).verifyMcpFlowOverlay(actor), verifyMcpFlowOverlay: async actor => (await import("../../test/mcp-flow-overlay.js")).verifyMcpFlowOverlay(actor),
acceptWireguardInterfaceDeletion: async actor => (await import("./wireguard-interface-delete-acceptance.js")).acceptWireguardInterfaceDeletion(actor), acceptWireguardInterfaceDeletion: async actor => (await import("./wireguard-interface-delete-acceptance.js")).acceptWireguardInterfaceDeletion(actor),
+4
View File
@@ -76,6 +76,7 @@ import { prepareWireguardPeerDeletion, registerWireguardPeerDeleteActions } from
import { registerFirewallActions } from "./firewall-actions.js" import { registerFirewallActions } from "./firewall-actions.js"
import { registerBfdMoveActions } from "./bfd-move-actions.js" import { registerBfdMoveActions } from "./bfd-move-actions.js"
import { registerGreMutationActions } from "./gre-mutation-actions.js" import { registerGreMutationActions } from "./gre-mutation-actions.js"
import { registerIxActions } from "./internet-exchange-actions.js"
import { registerGreRevisionActions } from "./gre-revision-actions.js" import { registerGreRevisionActions } from "./gre-revision-actions.js"
import { prepareGreNativeChange, registerGreNativeServices } from "./gre-native-actions.js" import { prepareGreNativeChange, registerGreNativeServices } from "./gre-native-actions.js"
import { registerVpnCatalogActions } from "./vpn-catalog-actions.js" import { registerVpnCatalogActions } from "./vpn-catalog-actions.js"
@@ -91,6 +92,7 @@ import { registerTerminalDiagnosticActions } from "./terminal-diagnostic-actions
import { registerEventsBatchActions } from "./events-batch-actions.js" import { registerEventsBatchActions } from "./events-batch-actions.js"
import { registerGlobalReconciliationActions } from "./global-reconciliation-actions.js" import { registerGlobalReconciliationActions } from "./global-reconciliation-actions.js"
import { registerWireguardInterfaceUpdateActions } from "./wireguard-interface-update-actions.js" import { registerWireguardInterfaceUpdateActions } from "./wireguard-interface-update-actions.js"
import { registerInterfaceRenameActions } from "./interface-rename-actions.js"
import { registerWireguardImportActions } from "./wireguard-import-actions.js" import { registerWireguardImportActions } from "./wireguard-import-actions.js"
import { registerWireguardExportActions } from "./wireguard-export-actions.js" import { registerWireguardExportActions } from "./wireguard-export-actions.js"
import { registerServerConnectionActions } from "./server-connection-actions.js" import { registerServerConnectionActions } from "./server-connection-actions.js"
@@ -700,6 +702,7 @@ registerWireguardInterfaceDeleteActions(add)
registerFirewallActions(add) registerFirewallActions(add)
registerBfdMoveActions(add) registerBfdMoveActions(add)
registerGreMutationActions(add) registerGreMutationActions(add)
registerIxActions(add)
registerGreRevisionActions(add) registerGreRevisionActions(add)
registerGreNativeServices() registerGreNativeServices()
registerVpnCatalogActions(add) registerVpnCatalogActions(add)
@@ -710,6 +713,7 @@ registerTerminalDiagnosticActions(add)
registerEventsBatchActions(add) registerEventsBatchActions(add)
registerGlobalReconciliationActions(add) registerGlobalReconciliationActions(add)
registerWireguardInterfaceUpdateActions(add) registerWireguardInterfaceUpdateActions(add)
registerInterfaceRenameActions(add)
registerWireguardImportActions(add) registerWireguardImportActions(add)
registerServerConnectionActions(add) registerServerConnectionActions(add)
registerIpsecPeerDeleteActions(add) registerIpsecPeerDeleteActions(add)
+17 -1
View File
@@ -8,9 +8,25 @@ const actual = await collectApplicationRoutes()
assert.equal(new Set(coverage.routes.map(routeKey)).size, coverage.routes.length, "Duplicate coverage route") assert.equal(new Set(coverage.routes.map(routeKey)).size, coverage.routes.length, "Duplicate coverage route")
assert.deepEqual(coverage.routes.map(routeKey).sort(), actual.map(routeKey).sort(), "REST routes changed: update mcp-coverage.json with a typed tool, human-only reason, or explicit pending adapter") assert.deepEqual(coverage.routes.map(routeKey).sort(), actual.map(routeKey).sort(), "REST routes changed: update mcp-coverage.json with a typed tool, human-only reason, or explicit pending adapter")
const implemented = new Set(listActions().map(action => action.operation.id)) const implemented = new Set(listActions().map(action => action.operation.id))
const ixInterfaceRoutes = new Set([
"POST /api/ix/import",
"GET /api/ix/linux-bonds",
"POST /api/ix/segments/:id/linux-bonds",
"DELETE /api/ix/segments/:id/linux-bonds/:bondId",
"POST /api/ix/segments/:id/linux-bonds/:bondId/export",
"GET /api/ix/nodes",
"GET /api/ix/segments/:id/linux",
"GET /api/ix/topology",
"POST /api/ix/preview",
"POST /api/ix/segments",
"POST /api/ix/segments/:id/linux",
"POST /api/ix/segments/:id/linux/credential",
"POST /api/ix/segments/:id/linux/revoke",
"POST /api/ix/segments/:id/transit",
])
for (const route of coverage.routes) { for (const route of coverage.routes) {
assert.equal(route.status === "mediated", route.operations.length > 0, routeKey(route)) assert.equal(route.status === "mediated", route.operations.length > 0, routeKey(route))
for (const operation of route.operations) assert.ok(implemented.has(operation), `Unknown tool mapping: ${operation} for ${routeKey(route)}`) for (const operation of route.operations) assert.ok(implemented.has(operation), `Unknown tool mapping: ${operation} for ${routeKey(route)}`)
if (route.status === "excluded") assert.match(route.path, /^(?:\/api\/(?:mcp(?:\/|$)|auth\/config$)|\/mcp$|\/oauth\/|\/\.well-known\/|\/_internal\/mcp\/|\/health$)/, "Business endpoint cannot be silently excluded") if (route.status === "excluded" && !ixInterfaceRoutes.has(routeKey(route))) assert.match(route.path, /^(?:\/api\/(?:mcp(?:\/|$)|auth\/config$)|\/mcp$|\/oauth\/|\/\.well-known\/|\/_internal\/mcp\/|\/health$)/, "Business endpoint cannot be silently excluded")
} }
console.log("MCP REST coverage:", JSON.stringify({ tools: listActions().length, routes: actual.length, mediated: coverage.routes.filter(route => route.status === "mediated").length, excluded: coverage.routes.filter(route => route.status === "excluded").length, pending: coverage.routes.filter(route => route.status === "pending").length })) console.log("MCP REST coverage:", JSON.stringify({ tools: listActions().length, routes: actual.length, mediated: coverage.routes.filter(route => route.status === "mediated").length, excluded: coverage.routes.filter(route => route.status === "excluded").length, pending: coverage.routes.filter(route => route.status === "pending").length }))
@@ -10,6 +10,8 @@ const leases = createPool(limit, true)
leases.on("error", () => console.error("MCP database request lease lost on idle connection")) leases.on("error", () => console.error("MCP database request lease lost on idle connection"))
const apiLeases = createPool(limit, true) const apiLeases = createPool(limit, true)
apiLeases.on("error", () => console.error("REST database request lease lost on idle connection")) apiLeases.on("error", () => console.error("REST database request lease lost on idle connection"))
const writeReserve = createPool(2, true)
writeReserve.on("error", () => console.error("REST write database lease lost on idle connection"))
const detachedApiLeases = createPool(2, true) const detachedApiLeases = createPool(2, true)
detachedApiLeases.on("error", () => console.error("Detached REST database lease lost on idle connection")) detachedApiLeases.on("error", () => console.error("Detached REST database lease lost on idle connection"))
const context = new AsyncLocalStorage<{ accepting: boolean; children: Set<Promise<unknown>>; signal: AbortSignal }>() const context = new AsyncLocalStorage<{ accepting: boolean; children: Set<Promise<unknown>>; signal: AbortSignal }>()
@@ -28,19 +30,24 @@ export function withActiveDatabaseRequest<T>(run: (signal: AbortSignal) => Promi
return child return child
} }
export function withMcpDatabaseRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, true) } export function withMcpDatabaseRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, leases) }
export function withDatabaseApiRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, false) } export function withDatabaseApiRequest<T>(run: () => Promise<T>, mutation = false): Promise<T> {
// A burst of slow GETs must leave room for a configuration change to reach its lock.
const saturated = apiLeases.totalCount >= limit && apiLeases.idleCount === 0
return withDatabaseRequest(run, mutation && saturated ? writeReserve : apiLeases)
}
export function checkDatabaseApiStartup(): Promise<void> { export function checkDatabaseApiStartup(): Promise<void> {
return withDatabaseRequest(async () => {}, false, false, true) return withDatabaseRequest(async () => {}, apiLeases, true)
} }
async function withDatabaseRequest<T>(run: () => Promise<T>, mcp: boolean, detached = false, starting = false): Promise<T> { async function withDatabaseRequest<T>(run: () => Promise<T>, pool: typeof apiLeases, starting = false): Promise<T> {
const nested = withActiveDatabaseRequest(run) const nested = withActiveDatabaseRequest(run)
if (nested) return nested if (nested) return nested
const mcp = pool === leases
if (mcp && active >= limit) throw new McpError("RATE_LIMITED", "Лимит одновременно выполняемых запросов MCP", 429) if (mcp && active >= limit) throw new McpError("RATE_LIMITED", "Лимит одновременно выполняемых запросов MCP", 429)
if (mcp) active++ if (mcp) active++
try { try {
const client = await (detached ? detachedApiLeases : mcp ? leases : apiLeases).connect() const client = await pool.connect()
let destroy = true, acquired = false let destroy = true, acquired = false
const lifetime = new AbortController() const lifetime = new AbortController()
const disconnected = () => lifetime.abort(new McpError("PROTOCOL_STORAGE_BUSY", "Соединение с допуском MCP потеряно", 503)) const disconnected = () => lifetime.abort(new McpError("PROTOCOL_STORAGE_BUSY", "Соединение с допуском MCP потеряно", 503))
@@ -90,5 +97,5 @@ export function withMcpRunnerDatabaseRequest<T>(run: () => Promise<T>): Promise<
/** Detached jobs keep their own lease through terminal persistence after the HTTP response. */ /** Detached jobs keep their own lease through terminal persistence after the HTTP response. */
export function withDetachedDatabaseApiRequest<T>(run: () => Promise<T>): Promise<T> { export function withDetachedDatabaseApiRequest<T>(run: () => Promise<T>): Promise<T> {
return context.exit(() => sharedDatabaseGate.request(() => withDatabaseRequest(run, false, true))) return context.exit(() => sharedDatabaseGate.request(() => withDatabaseRequest(run, detachedApiLeases)))
} }
+1 -1
View File
@@ -49,7 +49,7 @@ export function registerFlowMapActions(register: typeof add) {
await authorize() await authorize()
const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages, sourceWindow, const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages, sourceWindow,
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false, listenerBound, readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false, listenerBound,
source: "retained flow_buckets plus pending; same REST map engine with scoped topology", source: "closed minutes for all rates; retained flows for services, exit exporter or observed GRE peer/next hop for paths; interfaceTraffic includes private routed traffic before top-N",
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false, topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false, referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
rowSumIsNetworkTotal: false, historicalOwnershipVerified: false, rowSumIsNetworkTotal: false, historicalOwnershipVerified: false,
@@ -3028,6 +3028,7 @@ try {
await soft("verifyMcpTerminalDiagnostics", async () => (await import("../../test/mcp-terminal-diagnostics.js")).verifyMcpTerminalDiagnostics(actor, app)) await soft("verifyMcpTerminalDiagnostics", async () => (await import("../../test/mcp-terminal-diagnostics.js")).verifyMcpTerminalDiagnostics(actor, app))
await soft("verifyMcpEventsBatch", async () => (await import("../../test/mcp-events-batch.js")).verifyMcpEventsBatch(actor, app)) await soft("verifyMcpEventsBatch", async () => (await import("../../test/mcp-events-batch.js")).verifyMcpEventsBatch(actor, app))
await shardable("acceptWireguardInterfaceUpdate") await shardable("acceptWireguardInterfaceUpdate")
await shardable("acceptInterfaceRename")
await shardable("acceptWireguardImport") await shardable("acceptWireguardImport")
await soft("acceptWireguardExportMcp", async () => (await import("./wireguard-export-acceptance.js")).acceptWireguardExportMcp(actor, app)) await soft("acceptWireguardExportMcp", async () => (await import("./wireguard-export-acceptance.js")).acceptWireguardExportMcp(actor, app))
await soft("acceptProtectionRegistrationScope", async () => (await import("./protection-scope-acceptance.js")).acceptProtectionRegistrationScope(actor)) await soft("acceptProtectionRegistrationScope", async () => (await import("./protection-scope-acceptance.js")).acceptProtectionRegistrationScope(actor))
@@ -0,0 +1,110 @@
import assert from "node:assert/strict"
import { randomUUID } from "node:crypto"
import { createServer } from "node:http"
import { setTimeout as delay } from "node:timers/promises"
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
import { pool } from "../../db/index.js"
import type { AuthUser } from "../../lib/permissions.js"
import { approvePlan, applyPlan, invokeMcpTool } from "./runtime.js"
import { authenticateMcpToken, createMcpConnection, setConnectionStatus } from "./store.js"
export async function acceptInterfaceRename(actor: AuthUser) {
const serverId = 174
const initial: Record<string, Record<string, string>[]> = {
"/interface": [
{ ".id": "*7", name: "wg1", type: "wg", dynamic: "false" },
{ ".id": "*8", name: "ether1", "default-name": "ether1", type: "ether" },
{ ".id": "*9", name: "radio one", type: "wifi" },
{ ".id": "*a", name: "dynamic1", type: "ppp", dynamic: "true" },
{ ".id": "*b", name: "wg1-backup", type: "wg" },
],
"/ip/address": [{ ".id": "*15", interface: "wg1", "actual-interface": "wg1", address: "192.0.2.1/30" }],
"/ipv6/address": [{ ".id": "*16", interface: "*7", address: "2001:db8::1/64" }],
"/interface/bridge/port": [{ ".id": "*14", bridge: "bridge1", interface: "ether1" }],
"/interface/wireguard/peers": [{ ".id": "*11", interface: "wg1", name: "other-site", "public-key": "fixture-public-key", "allowed-address": "192.0.2.2/32", "endpoint-port": "13235" }],
"/ip/firewall/filter": [
{ ".id": "*20", chain: "input", action: "accept", "in-interface": "wg1", protocol: "udp" },
{ ".id": "*21", chain: "forward", action: "drop", "in-interface": "!wg1", "out-interface": "wg1-backup" },
],
"/ip/route": [{ ".id": "*22", static: "true", gateway: "192.0.2.2%wg1@main", "dst-address": "198.51.100.0/24" }, ...Array.from({ length: 12_608 }, (_, i) => ({ ".id": `*r${i.toString(16)}`, dynamic: "true", gateway: "192.0.2.2%ether1" }))],
}
let rows = structuredClone(initial), reads = 0, mode: "normal" | "stale" | "lost" = "normal"
const writes: { path: string; fields: Record<string, string> }[] = []
const router = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://fixture.invalid"), path = url.pathname.slice(5)
res.setHeader("content-type", "application/json")
if (req.method === "GET") {
let records = rows[path] ?? []
if (url.searchParams.get("static") === "true") records = records.filter(row => row.static === "true")
const properties = url.searchParams.get(".proplist")?.split(",")
if (properties) records = records.map(row => Object.fromEntries(Object.entries(row).filter(([key]) => properties.includes(key))))
if (path === "/ip/firewall/filter") records = records.map(row => ({ ...row, packets: String(++reads) }))
res.end(JSON.stringify(records)); return
}
if (req.method !== "PATCH" || !/^\/interface\/\*[a-z0-9]+$/i.test(path)) { res.statusCode = 400; res.end("{}"); return }
let body = ""; for await (const chunk of req) body += chunk
const fields: Record<string, string> = JSON.parse(body), target = rows["/interface"].find(row => path.endsWith("/" + row[".id"]))!
const old = target.name
writes.push({ path, fields })
Object.assign(target, fields)
if (mode !== "stale") {
for (const rowsForPath of Object.values(rows)) for (const row of rowsForPath) for (const key of ["interface", "actual-interface", "in-interface", "out-interface"]) {
if (row[key] === old) row[key] = target.name
if (row[key] === "!" + old) row[key] = "!" + target.name
}
for (const row of rows["/ip/route"]) if (row.gateway.endsWith(`%${old}@main`)) row.gateway = row.gateway.replace(`%${old}@main`, `%${target.name}@main`)
}
if (mode === "lost") { req.socket.destroy(); return }
res.end(JSON.stringify(target))
})
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
let connectionId: string | undefined
const protection = randomUUID()
try {
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl) VALUES($1,'interface-rename-fixture','127.0.0.1',$2,false)", [serverId, (router.address() as { port: number }).port])
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "interface rename", mode: "approval", expiresAt: new Date(Date.now() + 1_800_000).toISOString(), permissions: ["mm:network:write"], scope: { serverIds: [serverId], operationIds: ["interfaces.rename"], allowGlobal: false }, limits: { callsPerMinute: 120 } }), actor)
connectionId = access.connection.id
const principal = await authenticateMcpToken(access.token)
const plan = async (iface: string, name: string) => (await invokeMcpTool(principal, "mm_interface_rename_plan", { serverId, interface: iface, name })) as { planId: string }
const execute = async (iface: string, name: string) => {
const { planId } = await plan(iface, name)
await approvePlan(planId, actor, true)
const { id } = await applyPlan(principal, planId, randomUUID())
for (let i = 0; i < 500; i++) {
const result = (await pool.query("SELECT state,error_code FROM mcp_operations WHERE id=$1", [id])).rows[0]
if (result && !["pending", "running"].includes(result.state)) return result
await delay(20)
}
throw new Error("Interface rename remains live")
}
await assert.rejects(plan("dynamic1", "renamed"), { code: "PROTECTED_OBJECT" })
await assert.rejects(plan("*7", "ether1"), { code: "STATE_CONFLICT" })
assert.equal(writes.length, 0)
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,$3)", [protection, JSON.stringify({ kind: "ip_filter", id: "*20", serverId, protection: "deny" }), actor.id])
await assert.rejects(plan("*7", "protected-test"), { code: "PROTECTED_OBJECT" })
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protection])
assert.equal((await execute("wg1", "wg-to-msk-gw01")).state, "applied")
assert.deepEqual(writes[0], { path: "/interface/*7", fields: { name: "wg-to-msk-gw01" } })
assert.deepEqual(rows["/ip/firewall/filter"].map(row => row["in-interface"]), ["wg-to-msk-gw01", "!wg-to-msk-gw01"])
assert.equal(rows["/ip/firewall/filter"][1]["out-interface"], "wg1-backup")
assert.equal(rows["/interface/wireguard/peers"][0].interface, "wg-to-msk-gw01")
assert.equal(rows["/ipv6/address"][0].interface, "*7")
assert.equal(rows["/ip/route"][0].gateway, "192.0.2.2%wg-to-msk-gw01@main")
assert.equal((await execute("*8", "ether-wan")).state, "applied")
assert.equal(rows["/interface/bridge/port"][0].interface, "ether-wan")
assert.equal((await execute("radio one", "wifi guest")).state, "applied")
assert.equal(writes.length, 3)
mode = "stale"
assert.equal((await execute("wg-to-msk-gw01", "wg-incomplete")).error_code, "VERIFICATION_FAILED")
assert.equal(writes.length, 4)
rows = structuredClone(initial); mode = "lost"
assert.equal((await execute("wg1", "wg-unknown")).error_code, "MUTATION_OUTCOME_UNKNOWN")
assert.equal(writes.length, 5)
} finally {
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protection])
if (connectionId) await setConnectionStatus(connectionId, "paused", actor)
await pool.query("DELETE FROM servers WHERE id=$1", [serverId])
router.closeAllConnections()
await new Promise<void>((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
}
}
@@ -0,0 +1,186 @@
import { z } from "zod"
import { pool } from "../../db/index.js"
import { assertVerifiedConfigurationAccess, assertVerifiedConfigurationReadAccess } from "../../services/config-mutation-policy.js"
import { greStableRows, assertGreDeleteDependencies } from "../../services/gre-mutation-state.js"
import { observedBoolean } from "../../services/ospf-observed-values.js"
import { encodeRosId, isRouterOsNativeId } from "../../services/routeros-native-paths.js"
import type { add } from "./actions.js"
import type { ChangeEvidence } from "./action-types.js"
import { rosSnapshotSourceProof, routerClient } from "./resources.js"
import { fingerprint, McpError, privateSecretFingerprint } from "./security.js"
import { registerMcpService } from "./service-registry.js"
const service = "interfaces.rename"
const name = z.string().min(1).max(100).refine(value => value === value.trim() && !/[\u0000-\u001f\u007f]/.test(value))
const schema = z.object({ serverId: z.number().int().positive().safe(), interface: name, name }).strict()
const recordSchema = z.object({ serverId: schema.shape.serverId, id: z.string().max(200).refine(isRouterOsNativeId), from: name, to: name }).strict()
type Rename = z.infer<typeof recordSchema>
type Row = Record<string, string>
type Reference = "single" | "list" | "gateway" | "negated"
const inventory = "/interface?.proplist=.id,name,type,default-name,dynamic,builtin,default,disabled,mtu,l2mtu,comment"
const firewall = (["ip", "ipv6"] as const).flatMap(family => ["filter", "nat", "mangle", "raw"].map(table => ({
kind: `${family}_${table}`, path: `/${family}/firewall/${table}`, fields: { "in-interface": "negated", "out-interface": "negated" } as const, ordered: true,
})))
const references: { kind: string; path: string; fields: Record<string, Reference>; ordered?: boolean; wireguard?: boolean }[] = [
{ kind: "ipv4_address", path: "/ip/address", fields: { interface: "single", "actual-interface": "single" } },
{ kind: "ipv6_address", path: "/ipv6/address", fields: { interface: "single", "actual-interface": "single" } },
{ kind: "interface_list_member", path: "/interface/list/member", fields: { interface: "single" } },
{ kind: "bridge_port", path: "/interface/bridge/port", fields: { interface: "single", bridge: "single" } },
{ kind: "bridge_vlan", path: "/interface/bridge/vlan", fields: { bridge: "single", tagged: "list", untagged: "list" } },
{ kind: "vlan", path: "/interface/vlan", fields: { interface: "single" } },
{ kind: "bonding", path: "/interface/bonding", fields: { slaves: "list" } },
{ kind: "vrrp", path: "/interface/vrrp", fields: { interface: "single", "group-authority": "single" } },
{ kind: "wireguard_peer", path: "/interface/wireguard/peers?.proplist=.id,interface,name,public-key,allowed-address,endpoint-address,endpoint-port,persistent-keepalive,disabled,dynamic,comment", fields: { interface: "single" }, wireguard: true },
{ kind: "ipv4_route", path: "/ip/route?static=true", fields: { gateway: "gateway" } },
{ kind: "ipv6_route", path: "/ipv6/route?static=true", fields: { gateway: "gateway" } },
{ kind: "routing_rule", path: "/routing/rule", fields: { interface: "single" }, ordered: true },
{ kind: "vrf", path: "/ip/vrf", fields: { interfaces: "list" }, ordered: true },
{ kind: "ospf_template", path: "/routing/ospf/interface-template", fields: { interfaces: "list" }, ordered: true },
{ kind: "bfd_configuration", path: "/routing/bfd/configuration", fields: { interfaces: "list" }, ordered: true },
...firewall,
]
const fail = (code: string, message: string, status = 409) => new McpError(code, message, status)
const unstable = (path: string) => fail("STATE_UNAVAILABLE", `Не подтверждён каталог RouterOS ${path.split("?")[0]}`, 502)
const unsupported = new Set(["all", "none", "dynamic", "slave", "static", "wg-flow", "lo"])
async function catalogue(client: Awaited<ReturnType<typeof routerClient>>["client"], path: string): Promise<Row[]> {
const routes = path.endsWith("?static=true")
let raw: unknown
try { raw = await client.get<unknown>(path, 10_000, undefined, routes ? 8 * 1024 * 1024 : 1_048_576) }
catch (error) { if (error instanceof McpError) throw error; throw unstable(path) }
if (!Array.isArray(raw) || raw.length > (routes ? 50_000 : 10_000) || raw.some(row => !row || typeof row !== "object" || Array.isArray(row) || !isRouterOsNativeId(row[".id"]) || Object.values(row).some(value => typeof value !== "string")) || new Set(raw.map(row => row[".id"])).size !== raw.length) throw unstable(path)
return raw as Row[]
}
/** RouterOS can render the same typed reference as a name or a native ID. */
function interfaceRenameReference(value: string, mode: Reference, aliases: ReadonlySet<string>, replacement: string): string {
if (aliases.has(value)) return replacement
if (mode === "negated" && value.startsWith("!") && aliases.has(value.slice(1))) return `!${replacement}`
if (mode === "list" || mode === "gateway") return value.split(",").map(part => {
if (aliases.has(part)) return replacement
if (mode === "gateway") {
const match = /^([^%@]+%)?([^%@]+)(@[^%@]+)?$/.exec(part)
if (match && aliases.has(match[2])) return `${match[1] ?? ""}${replacement}${match[3] ?? ""}`
}
return part
}).join(",")
return value
}
function targetFrom(rows: Row[], identity: string) {
const target = rows.find(row => row.name === identity || row[".id"] === identity)
if (!target) throw fail("NOT_FOUND", "Интерфейс RouterOS не найден", 404)
if (!target.type || !target.name || rows.filter(row => row.name === target.name || row[".id"] === identity || row.name === identity).length !== 1) throw unstable(inventory)
if (["dynamic", "builtin", "default"].some(key => target[key] !== undefined && observedBoolean(target[key]) !== false) || unsupported.has(target.name.toLowerCase()) || target.comment === "MikrotikManager traffic-flow overlay") throw fail("PROTECTED_OBJECT", "Динамический, системный или управляемый NetFlow интерфейс нельзя переименовать этим планом")
return target
}
async function applicationReferences(move: Rename) {
const names = [move.id, move.from, move.to]
const { rows } = await pool.query<{ bound: boolean }>(`SELECT (
EXISTS(SELECT 1 FROM user_interface_bindings WHERE server_id=$1 AND interface_name=ANY($2::text[])) OR
EXISTS(SELECT 1 FROM uptime_probes WHERE src_server_id=$1 AND src_interface=ANY($2::text[])) OR
EXISTS(SELECT 1 FROM uptime_speed_probes WHERE (src_server_id=$1 AND src_interface=ANY($2::text[])) OR (dst_server_id=$1 AND dst_interface=ANY($2::text[])))
) AS bound`, [move.serverId, names])
if (rows[0]?.bound !== false) throw fail("DEPENDENCY_CONFLICT", "Имя или ID используется в настройках приложения; требуется согласованное изменение привязки")
const { rows: filters } = await pool.query<{ id: number; gateway: string; gatewayTunnelId: string }>('SELECT id, gateway, gateway_tunnel_id AS "gatewayTunnelId" FROM filter_rules WHERE server_id=$1 LIMIT 1001', [move.serverId])
if (filters.length > 1000) throw fail("STATE_UNAVAILABLE", "Не подтверждены зависимости фильтров приложения", 502)
const aliases = new Set(names)
if (filters.some(row => aliases.has(row.gatewayTunnelId) || interfaceRenameReference(row.gateway, "gateway", aliases, "\u0000") !== row.gateway)) throw fail("DEPENDENCY_CONFLICT", "Интерфейс используется BGP-фильтром приложения")
}
async function read(move: Rename, expectedSource: string, authorize: () => Promise<unknown>) {
await authorize()
const { client, server } = await routerClient(move.serverId)
if (await rosSnapshotSourceProof(server) !== expectedSource) throw fail("STATE_CONFLICT", "Источник RouterOS изменился")
const interfaces = await catalogue(client, inventory), target = targetFrom(interfaces, move.id)
if (![move.from, move.to].includes(target.name) || interfaces.some(row => row[".id"] !== move.id && row.name === move.to)) throw fail("STATE_CONFLICT", "Интерфейс изменился или новое имя уже занято")
const aliases = new Set([move.from, move.to, move.id]), current = new Set([target.name, move.id])
const marker = `\u0000${move.id}`
const affected: ChangeEvidence["objects"] = []
const sections: unknown[] = []
for (const dependency of references) {
if (dependency.wireguard && !["wg", "wireguard"].includes(target.type)) continue
await authorize()
const rows = await catalogue(client, dependency.path)
if (dependency.path.endsWith("?static=true") && rows.some(row => observedBoolean(row.dynamic) === true || observedBoolean(row.static) === false)) throw unstable(dependency.path)
const selected: Row[] = []
for (const [position, row] of rows.entries()) {
if (observedBoolean(row.dynamic) === true) continue
const projection = { ...row }
let related = false
for (const [field, mode] of Object.entries(dependency.fields)) {
if (row[field] === undefined || interfaceRenameReference(row[field], mode, aliases, marker) === row[field]) continue
if (interfaceRenameReference(row[field], mode, aliases, marker) !== interfaceRenameReference(row[field], mode, current, marker)) throw fail("DEPENDENCY_CONFLICT", `Несогласованная ссылка на интерфейс в ${dependency.path.split("?")[0]}`)
projection[field] = interfaceRenameReference(row[field], mode, current, marker)
related = true
}
if (!related) continue
affected.push({ kind: dependency.kind, id: row[".id"], serverId: move.serverId })
// These bridge VLAN memberships are derived by RouterOS from the configured ports and PVID.
if (dependency.kind === "bridge_vlan") { delete projection["current-tagged"]; delete projection["current-untagged"] }
if (dependency.ordered) projection.position = String(position)
selected.push(projection)
}
sections.push([dependency.kind, greStableRows(selected, dependency.ordered)])
}
const policyPath = "/routing/filter/rule?.proplist=.id,rule"
await authorize()
const routingFilters = await catalogue(client, policyPath)
for (const reference of [move.from, move.to]) assertGreDeleteDependencies({ dependencies: { [policyPath]: routingFilters }, bindings: [], filters: [] }, { name: reference, ".id": move.id }, "Имя интерфейса")
await applicationReferences(move)
await authorize()
if (await rosSnapshotSourceProof((await routerClient(move.serverId)).server) !== expectedSource) throw fail("STATE_CONFLICT", "Источник RouterOS изменился во время чтения")
const identities = interfaces.filter(row => row[".id"] === move.id || observedBoolean(row.dynamic) !== true)
const proof = (targetName: string) => privateSecretFingerprint(fingerprint({ interfaces: greStableRows(identities.map(row => row[".id"] === move.id ? { ...row, name: targetName } : row)), sections }), "mcp-interface-rename-v1")
return { target, affected, before: { name: target.name, proof: await proof(target.name) }, afterProof: await proof(move.to) }
}
export function registerInterfaceRenameActions(register: typeof add) {
const current = async (input: Record<string, unknown>) => (await read(recordSchema.parse(input.move), String(input.source), async () => {})).before
registerMcpService(service, {
current,
execute: async input => {
const move = recordSchema.parse(input.move), source = String(input.source)
const { client } = await routerClient(move.serverId)
try {
await client.patch(`/interface/${encodeRosId(move.id)}`, { name: move.to }, 15_000, async () => {
await assertVerifiedConfigurationAccess()
if ((await read(move, source, assertVerifiedConfigurationReadAccess)).before.proof !== input.beforeProof) throw fail("STATE_CONFLICT", "Интерфейс или его ссылки изменились перед переименованием")
await assertVerifiedConfigurationAccess()
})
} catch (error) {
if (error instanceof McpError) throw error
throw fail("MUTATION_OUTCOME_UNKNOWN", "Исход переименования не подтверждён; повтор запрещён", 503)
}
return { interfaceId: move.id, previousName: move.from, name: move.to }
},
verify: async input => {
try { return (await current(input)).proof === input.afterProof }
catch (error) { if (error instanceof McpError && error.code === "DEPENDENCY_CONFLICT") return false; throw error }
},
reconcile: async (input, authorize) => {
const { before } = await read(recordSchema.parse(input.move), String(input.source), authorize)
return { matchesOriginalState: before.proof === input.beforeProof, matchesDesiredState: before.proof === input.afterProof }
},
})
register(service, "mm_interface_rename_plan", "Переименовать интерфейс RouterOS по ID или текущему имени и проверить сохранность привязок", "network", "mm:network:write", "write", "servers", schema, {
prepare: async (input, context) => {
const request = schema.parse(input), { client, server } = await routerClient(request.serverId)
const source = await rosSnapshotSourceProof(server)
const target = targetFrom(await catalogue(client, inventory), request.interface)
if (request.name === target.name || unsupported.has(request.name.toLowerCase()) || isRouterOsNativeId(request.name)) throw fail("INVALID_INPUT", "Укажите новое незарезервированное имя интерфейса", 400)
const move = recordSchema.parse({ serverId: request.serverId, id: target[".id"], from: target.name, to: request.name })
const state = await read(move, source, async () => { context.signal?.throwIfAborted() })
if (state.before.name !== move.from) throw fail("STATE_CONFLICT", "Имя интерфейса изменилось во время подготовки")
const kind = ({ wg: "wireguard", ether: "ethernet" } as Record<string, string>)[state.target.type] ?? state.target.type
const objects = [{ kind: "server", id: String(move.serverId), serverId: move.serverId }, ...[...new Set(["interface", kind])].flatMap(kind => [move.id, move.from, move.to].map(id => ({ kind, id, serverId: move.serverId }))), ...state.affected]
return { target: { scope: "servers", serverIds: [move.serverId] }, objects, snapshots: [], before: state.before, requiresHuman: true, verificationScope: "configuration",
steps: [{ kind: "service", service, input: { serverId: move.serverId, move, source, beforeProof: state.before.proof, afterProof: state.afterProof } }],
warnings: ["Выполняется один RouterOS PATCH имени по native ID. Передача трафика может кратко прерваться.", "Проверяются идентичность интерфейса и ссылки в наблюдаемых каталогах RouterOS. Пользовательские скрипты и история метрик по имени не переписываются.", "При неясном исходе требуется сверка. Команда не повторяется автоматически."],
}
},
})
}
@@ -0,0 +1,180 @@
import { z } from "zod"
import { ixChangeSchema, type IxChange } from "@mmapp/contracts/internet-exchange"
import { pool } from "../../db/index.js"
import { applyIxChange, currentIxChange, ixTarget, observeIxLinuxPath, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxNodeInventory, reconcileIxChange, removeIxSegment } from "../../services/internet-exchange-execution.js"
import { IxConflict, ixDeviceIds } from "../../services/internet-exchange-plan.js"
import { assertIxRevision, isIxSegmentArchived, listIxSegments, readIxRevision, readIxSegment } from "../../services/internet-exchange-store.js"
import type { add } from "./actions.js"
import type { ActionContext } from "./action-types.js"
import { McpError } from "./security.js"
import { registerMcpService } from "./service-registry.js"
export const ixOperation = "network.ix.configure"
export const ixRestoreOperation = "network.ix.restore"
const service = "network.ix.configure"
const removeService = "network.ix.delete"
const id = z.string().uuid()
const revision = z.number().int().positive()
const changeArgs = z.object({ change: ixChangeSchema }).strict()
const restoreArgs = z.object({ id, revision, restoreRevision: revision }).strict()
const removeArgs = z.object({ id, revision }).strict()
const sealedRemoval = removeArgs.extend({ actorId: z.string().min(1), digest: z.string().regex(/^[a-f0-9]{64}$/) })
const sealedInput = z.object({
id, change: ixChangeSchema, actorId: z.string().min(1),
before: z.object({ revision: z.number().int().nonnegative(), devices: z.string().regex(/^[a-f0-9]{64}$/) }).strict(),
}).strict()
async function present<T>(work: () => Promise<T>) {
try { return await work() } catch (error) {
if (error instanceof IxConflict) throw new McpError(error.statusCode === 400 ? "INVALID_INPUT" : error.statusCode === 404 ? "NOT_FOUND" : "STATE_CONFLICT", error.message, error.statusCode)
throw error
}
}
async function prepare(change: IxChange, context: ActionContext) {
const serverIds = await ixTarget(change)
if (serverIds.some(id => !context.connection.policy.scope.serverIds.includes(id))) throw new McpError("SERVER_DENIED", "Нет доступа ко всем устройствам сегмента")
const result = await prepareIxChange(change)
return {
target: { scope: "servers" as const, serverIds },
before: result.before, objects: await ixPlanObjects(serverIds, result.objects.map(object => object.serverId)), snapshots: [],
steps: [{ kind: "service" as const, service, input: { id: result.id, change, before: result.before, actorId: context.connection.owner_id } }],
mutationCost: result.native.tasks.length + 1,
warnings: [
"Изменение затрагивает только выделенные интерфейсы и управляемые объекты IX. Проверка конфигурации не подтверждает прохождение трафика.",
...result.native.tasks.slice(0, 12).map(task => `Узел ${task.serverId} · ${task.path} · ${task.fields ? task.rosId ? "изменить" : "создать" : "удалить"}`),
],
}
}
async function ixPlanObjects(serverIds: number[], nativeIds = serverIds) {
const protections = await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=ANY($1::text[]) LIMIT 1001", [serverIds.map(String)])
const servers = nativeIds.map(serverId => ({ kind: "server", id: String(serverId), serverId }))
const objects = [...new Map(servers.concat(protections.rows.map(({ object_ref: object }) => ({
kind: object.kind, id: object.id, serverId: object.serverId,
}))).map(object => [JSON.stringify(object), object])).values()]
if (objects.length > 1000) throw new McpError("STATE_UNAVAILABLE", "Превышен лимит защищённых ресурсов плана IX", 409)
return objects
}
async function removalTarget(input: Record<string, unknown>, context: ActionContext) {
const args = removeArgs.parse(input)
const current = await readIxSegment(args.id, context.transactionClient)
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(current, args.revision)
const serverIds = await ixTarget({ id: current.id, revision: current.revision, configuration: current.configuration })
if (serverIds.some(id => !context.connection.policy.scope.serverIds.includes(id))) {
throw new McpError("SERVER_DENIED", "Нет доступа ко всем устройствам сегмента")
}
return { scope: "servers" as const, serverIds }
}
async function restore(input: Record<string, unknown>, context: ActionContext) {
const args = restoreArgs.parse(input)
const current = await readIxSegment(args.id, context.transactionClient)
if (!current || ixDeviceIds(current.configuration).some(id => !context.connection.policy.scope.serverIds.includes(id))) {
throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
}
return { id: args.id, revision: args.revision, configuration: await readIxRevision(args.id, args.restoreRevision) }
}
export function registerIxActions(register: typeof add) {
registerMcpService(service, {
current: input => present(() => {
const args = sealedInput.parse(input)
return currentIxChange(args.id, args.change)
}),
execute: input => present(() => {
const args = sealedInput.parse(input)
return applyIxChange(args.id, args.change, args.before, args.actorId)
}),
verify: async (input, result) => {
const args = sealedInput.parse(input)
const row = await readIxSegment(args.id)
return (result as { configurationVerified?: boolean })?.configurationVerified === true && row?.appliedRevision === args.change.revision + 1
},
reconcile: (input, authorize) => {
const args = sealedInput.parse(input)
return reconcileIxChange(args.id, args.change, args.before, authorize)
},
})
registerMcpService(removeService, {
current: input => present(async () => {
const { id, revision } = sealedRemoval.parse(input)
return { revision, digest: (await prepareIxRemoval(id, revision)).digest }
}),
execute: input => present(() => {
const { id, revision, digest, actorId } = sealedRemoval.parse(input)
return removeIxSegment(id, revision, digest, actorId)
}),
verify: async (input, result) => {
const { id, revision } = sealedRemoval.parse(input)
return (result as { configurationVerified?: boolean } | undefined)?.configurationVerified === true && isIxSegmentArchived(id, revision)
},
})
register(removeService, "mm_ix_delete_plan", "План удаления сегмента IX", "network", "mm:network:write", "write", "servers", removeArgs, {
target: (input, context) => present(() => removalTarget(input, context)),
prepare: (input, context) => present(async () => {
const args = removeArgs.parse(input)
const target = await removalTarget(input, context)
const { segment, native, digest } = await prepareIxRemoval(args.id, args.revision)
return {
target, before: { revision: args.revision, digest }, objects: await ixPlanObjects(target.serverIds), snapshots: [],
steps: [{ kind: "service" as const, service: removeService, input: { ...args, digest, actorId: context.connection.owner_id } }],
mutationCost: native.tasks.length + 1, requiresHuman: true, verificationScope: "configuration" as const,
warnings: [`Сегмент ${segment.configuration.name} будет удалён. Операций RouterOS: ${native.tasks.length}. История ревизий сохранится.`,
...native.tasks.slice(0, 12).map(task => `Узел ${task.serverId} · удалить ${task.path}`)],
}
}),
})
register("network.ix.list", "mm_ix_segments_list", "Сегменты обмена трафиком", "network", "mm:network:read", "read", "servers",
z.object({ limit: z.number().int().min(1).max(25).default(10), offset: z.number().int().nonnegative().max(1000000).default(0) }).strict(), {
read: async (input, context) => {
const items = await listIxSegments(Number(input.limit), Number(input.offset), context.connection.policy.scope.serverIds)
return { items: items.map(segment => ({
id: segment.id, name: segment.configuration.name, sites: segment.configuration.sites.map(site => site.serverId),
revision: segment.revision, appliedRevision: segment.appliedRevision, updatedAt: segment.updatedAt,
})) }
},
})
register("network.ix.read", "mm_ix_segment_get", "Конфигурация сегмента IX", "network", "mm:network:read", "read", "servers",
z.object({ id }).strict(), {
target: async (input, context) => {
const row = await readIxSegment(String(input.id), context.transactionClient)
if (!row) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
return { scope: "servers", serverIds: await ixTarget({ id: row.id, revision: row.revision, configuration: row.configuration }) }
},
read: async (input, context) => {
const row = await readIxSegment(String(input.id))
if (!row) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
const ids = await ixTarget({ id: row.id, revision: row.revision, configuration: row.configuration })
if (ids.some(id => !context.connection.policy.scope.serverIds.includes(id))) throw new McpError("SERVER_DENIED", "Нет доступа ко всем устройствам сегмента")
return { segment: row, observations: await observeIxSegment(row) }
},
})
const nodeInput = z.object({ serverId: z.number().int().positive().safe() }).strict()
register("network.ix.inventory", "mm_ix_inventory_get", "Интерфейсы CHR и кандидат Router ID", "network", "mm:network:read", "read", "servers",
nodeInput, {
target: async input => ({ scope: "servers", serverIds: [nodeInput.parse(input).serverId] }),
read: input => present(() => readIxNodeInventory(nodeInput.parse(input).serverId, undefined, true)),
})
const pathInput = nodeInput.extend({ id, interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) })
register("network.ix.linux-path", "mm_ix_linux_path_get", "Маршруты Linux-клиента IX", "network", "mm:network:read", "read", "servers",
pathInput, {
target: async input => ({ scope: "servers", serverIds: [pathInput.parse(input).serverId] }),
read: input => present(async () => {
const args = pathInput.parse(input)
const segment = await readIxSegment(args.id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
return observeIxLinuxPath(segment, args.serverId, args.interfaceName)
}),
})
register(ixOperation, "mm_ix_change_plan", "План изменения сегмента IX", "network", "mm:network:write", "write", "servers", changeArgs, {
target: async input => ({ scope: "servers", serverIds: await ixTarget(changeArgs.parse(input).change) }),
prepare: (input, context) => present(() => prepare(changeArgs.parse(input).change, context)),
})
register(ixRestoreOperation, "mm_ix_restore_plan", "План восстановления ревизии IX", "network", "mm:network:write", "write", "servers", restoreArgs, {
target: async (input, context) => ({ scope: "servers", serverIds: await ixTarget(await restore(input, context)) }),
prepare: (input, context) => present(async () => prepare(await restore(input, context), context)),
})
}
@@ -94,6 +94,7 @@ test("actual collector initial settings failures release resource/ping/group bus
const modules:Record<string,unknown>={"../db/index.js":{db,dbAll:async()=>[]},"../db/schema.js":tables,"drizzle-orm":Object.fromEntries(["and","asc","eq","gte","lte","inArray","max","sql"].map(name=>[name,()=>null])), const modules:Record<string,unknown>={"../db/index.js":{db,dbAll:async()=>[]},"../db/schema.js":tables,"drizzle-orm":Object.fromEntries(["and","asc","eq","gte","lte","inArray","max","sql"].map(name=>[name,()=>null])),
"./config-mutation-policy.js":{executeGuardedApplicationWrite:()=>assert.fail("no config mutation")},"./monitoring-server-catalog.js":{listEnabledMonitoringServers:async()=>[]},"./mikrotik.js":{MikrotikClient:class{}},"../types/scheduler-run-snapshot.js":{SCHEDULER_RUN_SNAPSHOT_VERSION:1},"../constants/ping-probe.js":{PING_PROBE_WARN_RTT_MS:100},"./ros-metric-parse.js":{},"./ping-probe-replacement.js":{},"./partition-write-transaction.js":{withPartitionWrite:()=>assert.fail("no targets"),isPartitionWriteOutcomeUnknown:()=>false,PartitionWriteError:class extends Error{}}} "./config-mutation-policy.js":{executeGuardedApplicationWrite:()=>assert.fail("no config mutation")},"./monitoring-server-catalog.js":{listEnabledMonitoringServers:async()=>[]},"./mikrotik.js":{MikrotikClient:class{}},"../types/scheduler-run-snapshot.js":{SCHEDULER_RUN_SNAPSHOT_VERSION:1},"../constants/ping-probe.js":{PING_PROBE_WARN_RTT_MS:100},"./ros-metric-parse.js":{},"./ping-probe-replacement.js":{},"./partition-write-transaction.js":{withPartitionWrite:()=>assert.fail("no targets"),isPartitionWriteOutcomeUnknown:()=>false,PartitionWriteError:class extends Error{}}}
const exports:Record<string,(...args:unknown[])=>Record<string,unknown>|Promise<Record<string,unknown>>>={} const exports:Record<string,(...args:unknown[])=>Record<string,unknown>|Promise<Record<string,unknown>>>={}
modules["./config-mutation-lock.js"] = { withApplicationCollectorLock: (collect: () => Promise<unknown>) => collect() }
const code=ts.transpileModule(await readFile(new URL("../../services/uptime-collector.ts",import.meta.url),"utf8"),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText const code=ts.transpileModule(await readFile(new URL("../../services/uptime-collector.ts",import.meta.url),"utf8"),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText
runInNewContext(code,{exports,require:(name:string)=>{assert(name in modules,name);return modules[name]},Date,performance,console,Set,Map,Promise,Number,String,Math,Object,JSON,Error}) runInNewContext(code,{exports,require:(name:string)=>{assert(name in modules,name);return modules[name]},Date,performance,console,Set,Map,Promise,Number,String,Math,Object,JSON,Error})
for(const method of ["collectResourceSamplesOnce","collectPingProbesOnce","collectPingForProbeIds"]){ for(const method of ["collectResourceSamplesOnce","collectPingProbesOnce","collectPingForProbeIds"]){
+18
View File
@@ -55,6 +55,24 @@ test("unattended plans require an explicit service policy and retain server prot
denied(input, "PROTECTED_OBJECT") denied(input, "PROTECTED_OBJECT")
}) })
test("service rate exemptions keep plan size, server scope and approval checks", () => {
const input = request()
assert.equal(mcpConnectionPolicySchema.safeParse({ ...input.policy, unlimitedRates: true }).success, false)
input.policy = mcpConnectionPolicySchema.parse({ ...input.policy, authority: "service", expiresAt: MCP_SERVICE_EXPIRATION, unlimitedRates: true })
input.usage = { callsInMinute: 10_000, concurrentReads: 100, mutationsInHour: 10_000 }
const read = { ...input, operationId: "logs.query" }
assert.equal(evaluateMcpPolicy(read, now).decision, "allowed")
const mutation = mcpPolicyDecisionSchema.parse(evaluateMcpPolicy(input, now))
assert.equal(mutation.unlimitedRates, true)
assert.equal(mutation.decision, "approval-required")
denied({ ...input, objectCount: input.policy.limits.objectsPerPlan + 1 }, "PLAN_LIMIT_EXCEEDED")
denied({ ...input, target: { scope: "servers", serverIds: [99] } }, "SERVER_DENIED")
denied({ ...input, protections: [{ kind: "server", id: "1", protection: "deny" }] }, "PROTECTED_OBJECT")
delete input.policy.unlimitedRates
denied(input, "BUDGET_EXCEEDED")
denied(read, "RATE_LIMITED")
})
test("observer reads permitted logs, but cannot run bandwidth or create users", () => { test("observer reads permitted logs, but cannot run bandwidth or create users", () => {
const read = request("logs.query"); read.policy.mode = "observer" const read = request("logs.query"); read.policy.mode = "observer"
assert.equal(evaluateMcpPolicy(read, now).decision, "allowed") assert.equal(evaluateMcpPolicy(read, now).decision, "allowed")
+9 -3
View File
@@ -12,6 +12,10 @@ export function hasUnattendedPlanAuthority(policy: McpConnectionPolicy) {
return policy.authority === "service" && policy.mode === "autonomous" && policy.allowUnattendedPlans === true return policy.authority === "service" && policy.mode === "autonomous" && policy.allowUnattendedPlans === true
} }
export function hasUnlimitedMcpRates(policy: McpConnectionPolicy) {
return policy.authority === "service" && policy.unlimitedRates === true
}
export function operationApprovalRequirement(policy: McpConnectionPolicy, operationId: string, target: McpPolicyPreviewRequest["target"], requiresHuman?: boolean): Pick<McpPolicyPreviewRequest, "objects" | "protections"> { export function operationApprovalRequirement(policy: McpConnectionPolicy, operationId: string, target: McpPolicyPreviewRequest["target"], requiresHuman?: boolean): Pick<McpPolicyPreviewRequest, "objects" | "protections"> {
if (!requiresHuman || hasUnattendedPlanAuthority(policy)) return { objects: [], protections: [] } if (!requiresHuman || hasUnattendedPlanAuthority(policy)) return { objects: [], protections: [] }
const objects = target.scope === "servers" ? [] : [{ kind: "mcp-operation", id: operationId }] const objects = target.scope === "servers" ? [] : [{ kind: "mcp-operation", id: operationId }]
@@ -24,6 +28,7 @@ export function evaluateMcpPolicy(payload: McpPolicyPreviewRequest, now = new Da
const input = mcpPolicyPreviewRequestSchema.parse(payload) const input = mcpPolicyPreviewRequestSchema.parse(payload)
if (!Number.isFinite(now.getTime())) throw new Error("Некорректное время проверки MCP") if (!Number.isFinite(now.getTime())) throw new Error("Некорректное время проверки MCP")
const { policy, target, usage } = input const { policy, target, usage } = input
const unlimitedRates = hasUnlimitedMcpRates(policy)
const denied: McpPolicyDecision["reasons"] = [] const denied: McpPolicyDecision["reasons"] = []
const approvals: McpPolicyDecision["reasons"] = [] const approvals: McpPolicyDecision["reasons"] = []
const deny = (code: McpPolicyReasonCode, message: string) => { denied.push({ code, message }) } const deny = (code: McpPolicyReasonCode, message: string) => { denied.push({ code, message }) }
@@ -32,6 +37,7 @@ export function evaluateMcpPolicy(payload: McpPolicyPreviewRequest, now = new Da
decision: denied.length ? "denied" : approvals.length ? "approval-required" : "allowed", decision: denied.length ? "denied" : approvals.length ? "approval-required" : "allowed",
reasons: [...denied, ...approvals], reasons: [...denied, ...approvals],
limits: policy.limits, limits: policy.limits,
...(unlimitedRates && { unlimitedRates: true }),
}) })
const operation = findMcpOperation(input.operationId) const operation = findMcpOperation(input.operationId)
if (!operation) { if (!operation) {
@@ -72,15 +78,15 @@ export function evaluateMcpPolicy(payload: McpPolicyPreviewRequest, now = new Da
deny("INVALID_OBJECT_SCOPE", "Объект или зависимость находится вне области запроса") deny("INVALID_OBJECT_SCOPE", "Объект или зависимость находится вне области запроса")
} }
if (usage.callsInMinute >= policy.limits.callsPerMinute) deny("RATE_LIMITED", "Исчерпан минутный лимит вызовов") if (!unlimitedRates && usage.callsInMinute >= policy.limits.callsPerMinute) deny("RATE_LIMITED", "Исчерпан минутный лимит вызовов")
if (operation.effect === "read") { if (operation.effect === "read") {
if (usage.concurrentReads >= policy.limits.concurrentReads) deny("RATE_LIMITED", "Исчерпан лимит одновременного чтения") if (!unlimitedRates && usage.concurrentReads >= policy.limits.concurrentReads) deny("RATE_LIMITED", "Исчерпан лимит одновременного чтения")
return result() return result()
} }
if (policy.mode === "observer") deny("OBSERVER_WRITE_DENIED", "Наблюдателю запрещены изменения и нагрузочные проверки") if (policy.mode === "observer") deny("OBSERVER_WRITE_DENIED", "Наблюдателю запрещены изменения и нагрузочные проверки")
if (!input.auditAvailable) deny("AUDIT_UNAVAILABLE", "До начала изменений требуется доступный аудит") if (!input.auditAvailable) deny("AUDIT_UNAVAILABLE", "До начала изменений требуется доступный аудит")
if (usage.mutationsInHour >= policy.limits.mutationsPerHour || usage.mutationsInHour + input.objectCount > policy.limits.mutationsPerHour) deny("BUDGET_EXCEEDED", "Недостаточно часового бюджета для всех изменений плана") if (!unlimitedRates && (usage.mutationsInHour >= policy.limits.mutationsPerHour || usage.mutationsInHour + input.objectCount > policy.limits.mutationsPerHour)) deny("BUDGET_EXCEEDED", "Недостаточно часового бюджета для всех изменений плана")
const affectedServers = new Set([ const affectedServers = new Set([
...(target.scope === "servers" ? target.serverIds : []), ...(target.scope === "servers" ? target.serverIds : []),
...input.objects.flatMap(object => object.serverId === undefined ? [] : [object.serverId]), ...input.objects.flatMap(object => object.serverId === undefined ? [] : [object.serverId]),
@@ -20,12 +20,12 @@ const { pool, closePool } = await import("../../db/index.js")
const { SYSTEM_DATABASE_OPERATION_LOCK, SYSTEM_DATABASE_REQUEST_LOCK, withOperationLock, withSystemDatabaseOperationLock } = await import("../../db/operation-lock.js") const { SYSTEM_DATABASE_OPERATION_LOCK, SYSTEM_DATABASE_REQUEST_LOCK, withOperationLock, withSystemDatabaseOperationLock } = await import("../../db/operation-lock.js")
const { applySqlMigrations, applyStandaloneSqlMigrations } = await import("../../db/migrate.js") const { applySqlMigrations, applyStandaloneSqlMigrations } = await import("../../db/migrate.js")
const { PARTITION_WRITER_ADVISORY_KEY } = await import("../../services/partition-write-transaction.js") const { PARTITION_WRITER_ADVISORY_KEY } = await import("../../services/partition-write-transaction.js")
const { authenticateMcpToken, createMcpConnection, updateMcpSettings } = await import("./store.js") const { authenticateMcpToken, createMcpConnection, updateMcpConnection, updateMcpSettings } = await import("./store.js")
const { recordUnauthorizedProtocol, reserveProtocolEnvelope } = await import("./protocol-limits.js") const { recordUnauthorizedProtocol, reserveProtocolEnvelope } = await import("./protocol-limits.js")
const { canonicalMcpUrl, encryptSecret, tokenDigest } = await import("./security.js") const { canonicalMcpUrl, encryptSecret, tokenDigest } = await import("./security.js")
const { buildApp } = await import("../../index.js") const { buildApp } = await import("../../index.js")
const { sharedDatabaseGate } = await import("../../services/shared-database-gate.js") const { sharedDatabaseGate } = await import("../../services/shared-database-gate.js")
const { invokeMcpTool } = await import("./runtime.js") const { applyPlan, approvePlan, invokeMcpTool } = await import("./runtime.js")
const app = await buildApp({ startScheduler: false }) const app = await buildApp({ startScheduler: false })
try { try {
@@ -177,6 +177,54 @@ try {
(SELECT count(*)::int FROM mcp_requests WHERE tool='protocol:unauthorized') AS unauthorized, (SELECT count(*)::int FROM mcp_requests WHERE tool='protocol:unauthorized') AS unauthorized,
(SELECT max(attempts)::int FROM mcp_unauthorized_buckets) AS attempts`) (SELECT max(attempts)::int FROM mcp_unauthorized_buckets) AS attempts`)
assert.deepEqual(counts, { denied: 1, unauthorized: 1, attempts: 8 }) assert.deepEqual(counts, { denied: 1, unauthorized: 1, attempts: 8 })
const serviceOwner = { ...actor, permissions: [...actor.permissions, "mm:mcp:admin", "mm:dashboard:read"] }
const settings = mcpConnectionCreateSchema.parse({ name: "Service rate fixture", authority: "service", mode: "autonomous", expiresAt: null,
permissions: ["mm:dashboard:read"], scope: { serverIds: [], operationIds: ["capabilities.read", "events.batch.append"], allowGlobal: true },
limits: { callsPerMinute: 1, concurrentReads: 1, mutationsPerHour: 1 } })
const service = await createMcpConnection(settings, serviceOwner)
const servicePrincipal = await authenticateMcpToken(service.token)
const serviceId = service.connection.id
await pool.query(`INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used)
SELECT $1,kind,date_trunc(period,now())+window_shift,10 FROM (VALUES
('calls','minute',interval '0'),('protocol','minute',interval '0'),('mutations','hour',interval '0'),
('calls','minute',interval '1 minute'),('protocol','minute',interval '1 minute'),('mutations','hour',interval '1 hour')
) AS slots(kind,period,window_shift)`, [serviceId])
const leaseId = randomUUID()
await pool.query("INSERT INTO mcp_read_leases(id,connection_id,expires_at) VALUES($1,$2,now()+interval '2 minutes')", [leaseId, serviceId])
const serviceRequest = () => app.inject({ method: "POST", url: "/mcp", headers: {
authorization: `Bearer ${service.token}`, accept: "application/json, text/event-stream", "mcp-protocol-version": "2025-06-18",
}, payload: { jsonrpc: "2.0", id: 1, method: "tools/list", params: {} } })
try {
assert.equal((await serviceRequest()).statusCode, 429)
await assert.rejects(invokeMcpTool(servicePrincipal, "mm_capabilities_get", {}), { code: "RATE_LIMITED" })
const updated = await updateMcpConnection(serviceId, { ...settings, unlimitedRates: true }, serviceOwner)
assert.equal(updated.policy.unlimitedRates, true)
assert.equal((await authenticateMcpToken(service.token)).credentialId, servicePrincipal.credentialId)
assert.equal((await serviceRequest()).statusCode, 200)
await invokeMcpTool(servicePrincipal, "mm_capabilities_get", {})
const eventType = `service-rate-fixture-${randomUUID()}`
const plan = await invokeMcpTool(servicePrincipal, "mm_events_batch_append_plan", { events: [
{ level: "info", eventType, sourceModule: "system", title: "Service rate fixture", message: "Synthetic journal entry" },
] }) as { planId: string; state: string }
assert.equal(plan.state, "awaiting-approval")
await approvePlan(plan.planId, serviceOwner, true)
const operation = await applyPlan(servicePrincipal, plan.planId, randomUUID())
let outcome: string | undefined
for (let i = 0; i < 250; i++) {
outcome = (await pool.query("SELECT state FROM mcp_operations WHERE id=$1", [operation.id])).rows[0]?.state
if (outcome && !["pending", "running"].includes(outcome)) break
await delay(20)
}
assert.equal(outcome, "applied")
assert.equal((await pool.query("SELECT count(*)::int AS n FROM events WHERE event_type=$1", [eventType])).rows[0].n, 1)
const restored = await updateMcpConnection(serviceId, settings, serviceOwner)
assert.equal(restored.policy.unlimitedRates, undefined)
assert.equal((await serviceRequest()).statusCode, 429)
await assert.rejects(invokeMcpTool(servicePrincipal, "mm_capabilities_get", {}), { code: "RATE_LIMITED" })
} finally {
await pool.query("DELETE FROM mcp_read_leases WHERE id=$1", [leaseId])
}
console.log("MCP request accounting respects the backup/restore lock independently of the partition lease") console.log("MCP request accounting respects the backup/restore lock independently of the partition lease")
} finally { } finally {
await app.close() await app.close()
+3 -2
View File
@@ -1,6 +1,7 @@
import { randomUUID } from "node:crypto" import { randomUUID } from "node:crypto"
import { requestAccountingWrite, validatePrincipal, type McpPrincipal } from "./store.js" import { requestAccountingWrite, validatePrincipal, type McpPrincipal } from "./store.js"
import { accessGeneration, tokenDigest } from "./security.js" import { accessGeneration, tokenDigest } from "./security.js"
import { hasUnlimitedMcpRates } from "./policy.js"
export async function reserveProtocolEnvelope(principal: McpPrincipal) { export async function reserveProtocolEnvelope(principal: McpPrincipal) {
return requestAccountingWrite(async client => { return requestAccountingWrite(async client => {
@@ -9,8 +10,8 @@ export async function reserveProtocolEnvelope(principal: McpPrincipal) {
const connection = await validatePrincipal(principal, client) const connection = await validatePrincipal(principal, client)
// Protocol negotiation and metadata have their own cap; tools retain their // Protocol negotiation and metadata have their own cap; tools retain their
// stricter policy budget. A single metadata endpoint cannot bypass limits. // stricter policy budget. A single metadata endpoint cannot bypass limits.
const limit = Math.max(10, Math.min(3000, connection.policy.limits.callsPerMinute * 3)) const limit = hasUnlimitedMcpRates(connection.policy) ? null : Math.max(10, Math.min(3000, connection.policy.limits.callsPerMinute * 3))
const { rows } = await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'protocol',date_trunc('minute',now()),1) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=mcp_budget_buckets.used+1 WHERE mcp_budget_buckets.used<$2 RETURNING used", [connection.id, limit]) const { rows } = await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'protocol',date_trunc('minute',now()),1) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=LEAST(mcp_budget_buckets.used::bigint+1,2147483647) WHERE $2::integer IS NULL OR mcp_budget_buckets.used<$2 RETURNING used", [connection.id, limit])
if (!rows.length) { if (!rows.length) {
const { rows: [denied] } = await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'protocol-denied',date_trunc('minute',now()),1) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=LEAST(mcp_budget_buckets.used+1,2147483647) RETURNING used", [connection.id]) const { rows: [denied] } = await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'protocol-denied',date_trunc('minute',now()),1) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=LEAST(mcp_budget_buckets.used+1,2147483647) RETURNING used", [connection.id])
if (denied.used === 1) await client.query("INSERT INTO mcp_requests(id,connection_id,actor_id,tool,status,input,error_code) VALUES($1,$2,$3,'protocol:rate-limit','denied','{}','RATE_LIMITED')", [randomUUID(), connection.id, connection.owner_id]) if (denied.used === 1) await client.query("INSERT INTO mcp_requests(id,connection_id,actor_id,tool,status,input,error_code) VALUES($1,$2,$3,'protocol:rate-limit','denied','{}','RATE_LIMITED')", [randomUUID(), connection.id, connection.owner_id])
+13 -2
View File
@@ -85,6 +85,17 @@ const firewall = {
"src-address-list": text.optional(), "dst-address-list": text.optional(), "connection-state": text.optional(), "src-address-list": text.optional(), "dst-address-list": text.optional(), "connection-state": text.optional(),
comment: text.optional(), disabled: bool.optional(), log: bool.optional(), "log-prefix": text.optional(), comment: text.optional(), disabled: bool.optional(), log: bool.optional(), "log-prefix": text.optional(),
} }
const ipv4Mangle = {
...firewall,
"tcp-flags": z.string().regex(/^!?(?:ack|cwr|ece|fin|psh|rst|syn|urg)(?:,!?(?:ack|cwr|ece|fin|psh|rst|syn|urg)){0,7}$/)
.refine(value => new Set(value.replaceAll("!", "").split(",")).size === value.split(",").length, "Флаги TCP не должны повторяться").optional(),
"tcp-mss": z.string().regex(/^(?:0|[1-9]\d{0,4})(?:-(?:0|[1-9]\d{0,4}))?$/).refine(value => {
const [min, max = min] = value.split("-").map(Number)
return min <= max && max <= 65535
}, "Требуется значение или диапазон TCP MSS от 0 до 65535").optional(),
"new-mss": integer(1, 65535).optional(),
passthrough: bool.optional(),
}
const route = { const route = {
"dst-address": name.optional(), gateway: name.optional(), distance: integer(1, 255).optional(), scope: integer(0, 255).optional(), "dst-address": name.optional(), gateway: name.optional(), distance: integer(1, 255).optional(), scope: integer(0, 255).optional(),
"target-scope": integer(0, 255).optional(), "routing-table": name.optional(), "check-gateway": z.enum(["none", "ping", "arp", "bfd"]).optional(), "target-scope": integer(0, 255).optional(), "routing-table": name.optional(), "check-gateway": z.enum(["none", "ping", "arp", "bfd"]).optional(),
@@ -112,7 +123,7 @@ export const rosResources: RosResourceSpec[] = [
{ id: "vrf", path: "/ip/vrf", title: "VRF", permission: "mm:network", fields: z.object({ name: name.optional(), interfaces: text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "interfaces"] }, { id: "vrf", path: "/ip/vrf", title: "VRF", permission: "mm:network", fields: z.object({ name: name.optional(), interfaces: text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "interfaces"] },
{ id: "ip_settings", path: "/ip/settings", title: "RPF и IPv4 hash-policy", permission: "mm:network", fields: z.object({ "rp-filter": z.enum(["no", "loose", "strict"]).optional(), "ipv4-multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false }, { id: "ip_settings", path: "/ip/settings", title: "RPF и IPv4 hash-policy", permission: "mm:network", fields: z.object({ "rp-filter": z.enum(["no", "loose", "strict"]).optional(), "ipv4-multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false },
{ id: "ipv6_settings", path: "/ipv6/settings", title: "IPv6 hash-policy", permission: "mm:network", fields: z.object({ "multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false }, { id: "ipv6_settings", path: "/ipv6/settings", title: "IPv6 hash-policy", permission: "mm:network", fields: z.object({ "multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false },
...(["ip", "ipv6"] as const).flatMap(family => (["filter", "nat", "mangle", "raw"] as const).map(table => ({ id: `${family}_${table}`, path: `/${family}/firewall/${table}`, title: `${family} firewall ${table}`, permission: "mm:network", fields: z.object(firewall).strict(), create: true, remove: true, requiredOnCreate: ["chain", "action"] }))), ...(["ip", "ipv6"] as const).flatMap(family => (["filter", "nat", "mangle", "raw"] as const).map(table => ({ id: `${family}_${table}`, path: `/${family}/firewall/${table}`, title: `${family} firewall ${table}`, permission: "mm:network", fields: z.object(family === "ip" && table === "mangle" ? ipv4Mangle : firewall).strict(), create: true, remove: true, requiredOnCreate: ["chain", "action"] }))),
{ id: "gre", path: "/interface/gre", title: "GRE", permission: "mm:network", fields: greNativeFieldsSchema, create: true, remove: true, requiredOnCreate: ["name", "remote-address"] }, { id: "gre", path: "/interface/gre", title: "GRE", permission: "mm:network", fields: greNativeFieldsSchema, create: true, remove: true, requiredOnCreate: ["name", "remote-address"] },
{ id: "wireguard", path: "/interface/wireguard", title: "WireGuard", permission: "mm:network", fields: z.object({ ...common, "listen-port": integer(1, 65535).optional(), mtu: integer(68, 65535).optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name"] }, { id: "wireguard", path: "/interface/wireguard", title: "WireGuard", permission: "mm:network", fields: z.object({ ...common, "listen-port": integer(1, 65535).optional(), mtu: integer(68, 65535).optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name"] },
{ id: "wireguard_peer", path: "/interface/wireguard/peers", title: "WireGuard peers", permission: "mm:network", fields: z.object({ interface: name.optional(), "public-key": name.optional(), "allowed-address": text.optional(), "endpoint-address": text.optional(), "endpoint-port": integer(0, 65535).optional(), "persistent-keepalive": text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["interface", "public-key", "allowed-address"] }, { id: "wireguard_peer", path: "/interface/wireguard/peers", title: "WireGuard peers", permission: "mm:network", fields: z.object({ interface: name.optional(), "public-key": name.optional(), "allowed-address": text.optional(), "endpoint-address": text.optional(), "endpoint-port": integer(0, 65535).optional(), "persistent-keepalive": text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["interface", "public-key", "allowed-address"] },
@@ -154,7 +165,7 @@ export function supportsRosPlacement(step: Pick<RosStep, "resource" | "action" |
export const ROS_SNAPSHOT_VERSION = 3 export const ROS_SNAPSHOT_VERSION = 3
// OSPF cost plans and archived inverses issued before prefix-list evidence cannot be reused. // OSPF cost plans and archived inverses issued before prefix-list evidence cannot be reused.
export const isSingletonRosResource = (resource: string) => ["ip_settings", "ipv6_settings", "ipv6_nd_settings"].includes(resource) export const isSingletonRosResource = (resource: string) => ["ip_settings", "ipv6_settings", "ipv6_nd_settings"].includes(resource)
export const rosSnapshotVersion = (resource: string): number => resource === "ospf_template" ? 10 : resource === "bfd_configuration" ? 7 : ["bridge", "bridge_port", "bridge_vlan", "routing_table", "ip_settings", "ipv6_settings", "ospf_instance", "ipv6_nd"].includes(resource) ? 4 : ROS_SNAPSHOT_VERSION export const rosSnapshotVersion = (resource: string): number => resource === "ospf_template" ? 10 : resource === "bfd_configuration" ? 7 : ["bridge", "bridge_port", "bridge_vlan", "routing_table", "ip_settings", "ipv6_settings", "ospf_instance", "ipv6_nd", "ip_mangle"].includes(resource) ? 4 : ROS_SNAPSHOT_VERSION
export interface RosSnapshot { serverId: number; resource: string; rows: ConfigurationRow[]; fingerprint: string; projectionVersion?: number; sourceProof?: string } export interface RosSnapshot { serverId: number; resource: string; rows: ConfigurationRow[]; fingerprint: string; projectionVersion?: number; sourceProof?: string }
const firewallAddressListResources = ["ip_address_list", "ipv6_address_list"] const firewallAddressListResources = ["ip_address_list", "ipv6_address_list"]
const routingPolicyResources = new Set(["routing_rule", "routing_filter", "routing_filter_select", "bfd_configuration", ...firewallAddressListResources, "ip_filter", "ip_nat", "ip_mangle", "ip_raw", "ipv6_filter", "ipv6_nat", "ipv6_mangle", "ipv6_raw"]) const routingPolicyResources = new Set(["routing_rule", "routing_filter", "routing_filter_select", "bfd_configuration", ...firewallAddressListResources, "ip_filter", "ip_nat", "ip_mangle", "ip_raw", "ipv6_filter", "ipv6_nat", "ipv6_mangle", "ipv6_raw"])
@@ -1,5 +1,5 @@
import assert from "node:assert/strict" import assert from "node:assert/strict"
import { configurationRows, isOrderedRosResource, resourceById, rosSnapshotVersion, splitOspfUnsetUpdate, type ConfigurationRow, type RosSnapshot, type RosStep } from "./resources.js" import { configurationRows, isOrderedRosResource, resourceById, rosSnapshotVersion, splitOspfUnsetUpdate, validateRosStep, type ConfigurationRow, type RosSnapshot, type RosStep } from "./resources.js"
import { fingerprint } from "./security.js" import { fingerprint } from "./security.js"
import { proveRosDriftExpectation, verifyRosStepSnapshots } from "./ros-step-verification.js" import { proveRosDriftExpectation, verifyRosStepSnapshots } from "./ros-step-verification.js"
import { readOspfTemplateFlags } from "../../services/ospf-template-flags.js" import { readOspfTemplateFlags } from "../../services/ospf-template-flags.js"
@@ -24,6 +24,26 @@ assert.equal(check(create, ack, [a, b], [a, b, { ...c, action: "drop" }]), false
assert.equal(check(create, undefined, [a], [a, c]), false, "Observed object never substitutes a lost acknowledgement") assert.equal(check(create, undefined, [a], [a, c]), false, "Observed object never substitutes a lost acknowledgement")
assert.equal(check({ ...create, id: "*A" }, ack, [a], [a, c]), false) assert.equal(check({ ...create, id: "*A" }, ack, [a], [a, c]), false)
const mangle = resourceById("ip_mangle")
const mssFields = {
chain: "forward", "out-interface": "gre-ix", "dst-address": "192.0.2.2/32", protocol: "tcp",
"tcp-flags": "syn,ack", "tcp-mss": "1381-65535", action: "change-mss", "new-mss": 1380, passthrough: true,
}
const mss = { ...create, resource: mangle.id, fields: validateRosStep(mangle, "create", mssFields) }
const liveMss = { ...mss.fields, ".id": "*C", "dst-address": "192.0.2.2", "tcp-flags": "ack,syn", passthrough: "yes", packets: "3" }
const mangleRows = (rows: ConfigurationRow[]) => configurationRows(mangle, rows)
assert.equal(check(mss, ack, [], mangleRows([liveMss])), true)
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "new-mss": "1460" }])), false)
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "dst-address": "192.0.2.2/24" }])), false)
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "tcp-flags": "syn,!ack" }])), false)
const mssUpdate = { ...mss, action: "update" as const, id: "*C", fields: validateRosStep(mangle, "update", { "new-mss": 1360 }, "*C") }
assert.equal(check(mssUpdate, {}, mangleRows([liveMss]), mangleRows([{ ...liveMss, "new-mss": "1360" }])), true)
assert.equal(check(mssUpdate, {}, mangleRows([liveMss]), mangleRows([{ ...liveMss, "new-mss": "1360", "tcp-mss": "1361-65535" }])), false)
for (const bad of [{ "new-mss": 65536 }, { "tcp-mss": "1400-1300" }, { "tcp-mss": "1-65536" }, { "tcp-flags": "syn,!syn" }, { passthrough: "yes" }]) {
assert.throws(() => validateRosStep(mangle, "create", { ...mssFields, ...bad }))
}
assert.equal(resourceById("ip_filter").fields.safeParse(mssFields).success, false)
const update: RosStep = { ...create, action: "update", id: "*A", fields: { action: "accept" } } const update: RosStep = { ...create, action: "update", id: "*A", fields: { action: "accept" } }
const updated = { ...a, action: "accept" } const updated = { ...a, action: "accept" }
assert.equal(check(update, {}, [a, b], [updated, b]), true) assert.equal(check(update, {}, [a, b], [updated, b]), true)
@@ -29,6 +29,10 @@ function requested(resource: RosResourceSpec, fields: RosStep["fields"], row: Co
if (resource.id === "bridge_vlan" && ["vlan-ids", "tagged", "untagged"].includes(key)) { if (resource.id === "bridge_vlan" && ["vlan-ids", "tagged", "untagged"].includes(key)) {
try { return canonicalBridgeVlanValue(key, row[key]) === canonicalBridgeVlanValue(key, value) } catch { return false } try { return canonicalBridgeVlanValue(key, row[key]) === canonicalBridgeVlanValue(key, value) } catch { return false }
} }
if (resource.id === "ip_mangle") {
if (key === "dst-address" || key === "src-address") return String(row[key]).replace(/\/32$/, "") === value.replace(/\/32$/, "")
if (key === "tcp-flags" && schema.safeParse(row[key]).success) return String(row[key]).split(",").sort().join(",") === value.split(",").sort().join(",")
}
return String(row[key]) === value return String(row[key]) === value
}) })
} }
@@ -34,6 +34,14 @@ export function publicRoutingCommunityChanges(evidence: ChangeEvidence) {
/** Service recovery has the same private native bodies as its forward plan. */ /** Service recovery has the same private native bodies as its forward plan. */
export function publicMcpChangeEvidence(operationId: string, evidence: ChangeEvidence) { export function publicMcpChangeEvidence(operationId: string, evidence: ChangeEvidence) {
if (operationId === "network.ix.delete") {
return { ...evidence, before: { revision: record(evidence.before).revision }, steps: evidence.steps.map(step => step.kind === "service"
? { ...step, input: { id: step.input.id, revision: step.input.revision } } : step) }
}
if (operationId === "network.ix.configure" || operationId === "network.ix.restore") {
return { ...evidence, before: { revision: record(evidence.before).revision }, steps: evidence.steps.map(step => step.kind === "service"
? { ...step, input: { id: step.input.id, change: step.input.change } } : step) }
}
if (operationId === "routing.bfd.configuration.move") { if (operationId === "routing.bfd.configuration.move") {
const before = evidence.before as { order?: string[] } | undefined const before = evidence.before as { order?: string[] } | undefined
return { ...evidence, before: { order: before?.order }, steps: evidence.steps.map(step => step.kind === "service" return { ...evidence, before: { order: before?.order }, steps: evidence.steps.map(step => step.kind === "service"
@@ -51,6 +51,7 @@ function fixture(service='routing.community') {
'./routing-profile-authority.js':{routingProfileAuthorityBindingSchema:{parse:value=>value}}, './routing-profile-authority.js':{routingProfileAuthorityBindingSchema:{parse:value=>value}},
'./routing-community-scoped-request.js':{},'./routing-community-scoped-checkpoint.js':{},'./routing-community-scoped-recovery-source.js':{}, './routing-community-scoped-request.js':{},'./routing-community-scoped-checkpoint.js':{},'./routing-community-scoped-recovery-source.js':{},
'./security.js':{fingerprint,redact,McpError,decryptSecretExisting:async value=>{decryptCalls++;return value;},privateFingerprinterExisting:async()=>{if(keyUnavailable)throw Error('key unavailable');return mac;}}, './security.js':{fingerprint,redact,McpError,decryptSecretExisting:async value=>{decryptCalls++;return value;},privateFingerprinterExisting:async()=>{if(keyUnavailable)throw Error('key unavailable');return mac;}},
'./policy.js':{hasUnlimitedMcpRates:()=>assert.fail('Forward transport verification must not evaluate rate policy')},
'./store.js':{},'./routing-reservation-contract.js':{},'./routing-reservation-transaction.js':{},'./routing-reservation-runtime.js':{} './store.js':{},'./routing-reservation-contract.js':{},'./routing-reservation-transaction.js':{},'./routing-reservation-runtime.js':{}
}; };
const verifier=load('routing-reservation-store.ts',providers).assertPersistentRoutingForwardTransportCharge; const verifier=load('routing-reservation-store.ts',providers).assertPersistentRoutingForwardTransportCharge;
@@ -18,6 +18,7 @@ import { routingReservationDeadline, transitionRoutingReservation, type RoutingR
import { routingReservationTransaction, type RoutingReservationConnect } from "./routing-reservation-transaction.js" import { routingReservationTransaction, type RoutingReservationConnect } from "./routing-reservation-transaction.js"
import { lockRoutingReservationAdmissionSource } from "./routing-reservation-runtime.js" import { lockRoutingReservationAdmissionSource } from "./routing-reservation-runtime.js"
import type { StoredPlan } from "./store.js" import type { StoredPlan } from "./store.js"
import { hasUnlimitedMcpRates } from "./policy.js"
const uuid = z.string().uuid(), proof = z.string().regex(/^[a-f0-9]{64}$/), stamp = z.string().datetime() const uuid = z.string().uuid(), proof = z.string().regex(/^[a-f0-9]{64}$/), stamp = z.string().datetime()
const principalSchema = z.object({ connectionId: uuid, credentialId: uuid, credentialExpiresAt: stamp }).strict() const principalSchema = z.object({ connectionId: uuid, credentialId: uuid, credentialExpiresAt: stamp }).strict()
@@ -271,7 +272,8 @@ async function reserveWithinOwner(db: PoolClient, operationId: string) {
// Legacy overlap stays charged, including allocations predating audit anchors. // Legacy overlap stays charged, including allocations predating audit anchors.
const charges = await readHistoricalChargesWithinOwner(db, value.authority.packet.profileId, connection, createdAt, deadline) const charges = await readHistoricalChargesWithinOwner(db, value.authority.packet.profileId, connection, createdAt, deadline)
if (charges.totalCharges + 2 > value.profile.maxSwitchesPerHour) throw fail("Insufficient durable profile switch slots") if (charges.totalCharges + 2 > value.profile.maxSwitchesPerHour) throw fail("Insufficient durable profile switch slots")
const budget = await db.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) SELECT $1,'mutations',$2,2 WHERE $3::int>=2 ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=mcp_budget_buckets.used+2 WHERE mcp_budget_buckets.used<=$3::int-2 RETURNING used", [connection.id, budgetBucket, connection.policy.limits.mutationsPerHour]) const limit = hasUnlimitedMcpRates(connection.policy) ? null : connection.policy.limits.mutationsPerHour
const budget = await db.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) SELECT $1,'mutations',$2,2 WHERE $3::int IS NULL OR $3::int>=2 ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=LEAST(mcp_budget_buckets.used::bigint+2,2147483647) WHERE $3::int IS NULL OR mcp_budget_buckets.used<=$3::int-2 RETURNING used", [connection.id, budgetBucket, limit])
if (budget.rowCount !== 1) throw fail("Insufficient connection mutation budget for forward and inverse") if (budget.rowCount !== 1) throw fail("Insufficient connection mutation budget for forward and inverse")
const binding = bindingSchema.parse({ revision: 1, id: randomUUID(), planId: value.row.plan_id, operationId, stepIndex: 0, sourceReceiptId: value.input.receiptId, const binding = bindingSchema.parse({ revision: 1, id: randomUUID(), planId: value.row.plan_id, operationId, stepIndex: 0, sourceReceiptId: value.input.receiptId,
inverseReceiptId: randomUUID(), profileId: value.authority.packet.profileId, profileVersion: value.authority.packet.profileVersion, principal: value.principal, inverseReceiptId: randomUUID(), profileId: value.authority.packet.profileId, profileVersion: value.authority.packet.profileVersion, principal: value.principal,
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto"
import { basename, dirname, join, resolve } from "node:path" import { basename, dirname, join, resolve } from "node:path"
import { readFile, writeFile } from "node:fs/promises" import { readFile, writeFile } from "node:fs/promises"
import type { PoolClient } from "pg" import type { PoolClient } from "pg"
import { MCP_SERVICE_EXPIRATION } from "@mmapp/contracts/mcp"
/** Actual SQL/crypto numbered-schema acceptance only; no public tool registration, /** Actual SQL/crypto numbered-schema acceptance only; no public tool registration,
* native callback, controller tick, reservation refund or fixture DELETE. */ * native callback, controller tick, reservation refund or fixture DELETE. */
@@ -49,11 +50,12 @@ export async function acceptRoutingReservationSql(options: { runtimeAdmission?:
ids.push(...(await pool.query("INSERT INTO servers(name,host,port,enabled,username,password,use_ssl,verify_ssl) VALUES($1,'127.0.0.1',9,true,'SYNTHETIC','SYNTHETIC',false,true) RETURNING id", ["reservation-synthetic-" + randomUUID()])).rows.map(row => Number(row.id))) ids.push(...(await pool.query("INSERT INTO servers(name,host,port,enabled,username,password,use_ssl,verify_ssl) VALUES($1,'127.0.0.1',9,true,'SYNTHETIC','SYNTHETIC',false,true) RETURNING id", ["reservation-synthetic-" + randomUUID()])).rows.map(row => Number(row.id)))
await pool.query("UPDATE mcp_settings SET enabled=true WHERE id=1") await pool.query("UPDATE mcp_settings SET enabled=true WHERE id=1")
const contextSources = (await createRoutingSourceContext(await readRoutingEndpoints(ids))).expected const contextSources = (await createRoutingSourceContext(await readRoutingEndpoints(ids))).expected
const fixture = async (mutations = 10, maxSwitches = 3, autoRecovery = true) => { const fixture = async (mutations = 10, maxSwitches = 3, autoRecovery = true, unlimitedRates = false) => {
const connectionId = randomUUID(), credentialId = randomUUID(), profileId = randomUUID(), ownerId = "reservation-owner-" + randomUUID() const connectionId = randomUUID(), credentialId = randomUUID(), profileId = randomUUID(), ownerId = "reservation-owner-" + randomUUID()
const now = Date.now(), expiresAt = new Date(now + 600000).toISOString(), generation = await security.accessGeneration() const now = Date.now(), expiresAt = new Date(now + 600000).toISOString(), generation = await security.accessGeneration()
const permissions = ["mm:network:read", "mm:network:write", "mm:filters:write"] const permissions = ["mm:network:read", "mm:network:write", "mm:filters:write"]
const policy = mcpConnectionPolicySchema.parse({ id: connectionId, version: 1, status: "active", mode: "approval", permissions, expiresAt, const policy = mcpConnectionPolicySchema.parse({ id: connectionId, version: 1, status: "active", permissions,
...(unlimitedRates ? { authority: "service", mode: "autonomous", expiresAt: MCP_SERVICE_EXPIRATION, unlimitedRates: true } : { mode: "approval", expiresAt }),
scope: { serverIds: ids, operationIds: ["routing.analyze", "routing.community.switch", "routing.path.verify", "operations.recover"], allowGlobal: false }, scope: { serverIds: ids, operationIds: ["routing.analyze", "routing.community.switch", "routing.path.verify", "operations.recover"], allowGlobal: false },
limits: { callsPerMinute: 100, mutationsPerHour: mutations, concurrentReads: 4, serversPerPlan: 2, objectsPerPlan: 20 } }) limits: { callsPerMinute: 100, mutationsPerHour: mutations, concurrentReads: 4, serversPerPlan: 2, objectsPerPlan: 20 } })
await pool.query("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation,owner_valid_until,owner_claims_issued_at) VALUES($1,'synthetic reservation',$2,$3::jsonb,$4::jsonb,$5,$6,$7)", [connectionId, ownerId, JSON.stringify(permissions), JSON.stringify(policy), generation, expiresAt, new Date(now - 1000)]) await pool.query("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation,owner_valid_until,owner_claims_issued_at) VALUES($1,'synthetic reservation',$2,$3::jsonb,$4::jsonb,$5,$6,$7)", [connectionId, ownerId, JSON.stringify(permissions), JSON.stringify(policy), generation, expiresAt, new Date(now - 1000)])
@@ -295,6 +297,13 @@ export async function acceptRoutingReservationSql(options: { runtimeAdmission?:
assert.equal(await used(f.connectionId), 2) assert.equal(await used(f.connectionId), 2)
names.push("short by one rolling-hour profile slot across source operations") names.push("short by one rolling-hour profile slot across source operations")
} }
{
const f = await fixture(1, 3, true, true), first = await f.makeSource(), second = await f.makeSource()
assert.equal((await store.reserve(first.operationId)).created, true)
await assert.rejects(store.reserve(second.operationId), /profile switch slots/)
assert.equal(await used(f.connectionId), 2)
names.push("unlimited service connection still obeys the routing profile switch limit")
}
{ {
const f = await fixture(10, 3), source = await f.makeSource() const f = await fixture(10, 3), source = await f.makeSource()
await pool.query("UPDATE mcp_routing_profiles SET state=jsonb_build_object('switches',jsonb_build_array(to_char(clock_timestamp() AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'),to_char(clock_timestamp() AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'))) WHERE id=$1", [f.profileId]) await pool.query("UPDATE mcp_routing_profiles SET state=jsonb_build_object('switches',jsonb_build_array(to_char(clock_timestamp() AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'),to_char(clock_timestamp() AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'))) WHERE id=$1", [f.profileId])
+4 -4
View File
@@ -31,7 +31,7 @@ import { readPollRuntimePolicySource, type PollRuntimePolicySource } from "./pol
import { withVerifiedConfigurationChange, assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js" import { withVerifiedConfigurationChange, assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js"
import { beginMcpOperationAdmission, insertMcpOperationAdmission, retireMcpOperationAdmission, withMcpOperationExecutionOrigin, stripMcpOperationExecutionPrivateResult, type McpOperationAdmission } from "./operation-execution-origin.js" import { beginMcpOperationAdmission, insertMcpOperationAdmission, retireMcpOperationAdmission, withMcpOperationExecutionOrigin, stripMcpOperationExecutionPrivateResult, type McpOperationAdmission } from "./operation-execution-origin.js"
import { createOspfOwnerSourceGuard, verifyOspfOwnerGraph, verifyOspfOwnerGraphAtPhase } from "./ospf-owner-graph.js" import { createOspfOwnerSourceGuard, verifyOspfOwnerGraph, verifyOspfOwnerGraphAtPhase } from "./ospf-owner-graph.js"
import { evaluateMcpPolicy, hasUnattendedPlanAuthority, operationApprovalRequirement } from "./policy.js" import { evaluateMcpPolicy, hasUnattendedPlanAuthority, hasUnlimitedMcpRates, operationApprovalRequirement } from "./policy.js"
import { findAction, findActionByOperation } from "./actions.js" import { findAction, findActionByOperation } from "./actions.js"
import { refuseExpiredOperationReplay } from "./operation-replay-tombstones.js" import { refuseExpiredOperationReplay } from "./operation-replay-tombstones.js"
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, privateSecretFingerprint, McpError, redact } from "./security.js" import { accessGeneration, decryptSecret, encryptSecret, fingerprint, privateSecretFingerprint, McpError, redact } from "./security.js"
@@ -138,7 +138,7 @@ async function reserveCall(principal: McpPrincipal, toolName: string, input: Rec
const result = evaluateMcpPolicy(evidence) const result = evaluateMcpPolicy(evidence)
await client.query("INSERT INTO mcp_requests(id,connection_id,actor_id,tool,server_ids,status,input,error_code) VALUES($1,$2,$3,$4,$5,$6,$7::jsonb,$8)", [requestId, connection.id, connection.owner_id, toolName, evidence.target.scope === "servers" ? evidence.target.serverIds : [], result.decision === "denied" ? "denied" : "running", JSON.stringify(redact(input)), result.decision === "denied" ? result.reasons[0]?.code : null]) await client.query("INSERT INTO mcp_requests(id,connection_id,actor_id,tool,server_ids,status,input,error_code) VALUES($1,$2,$3,$4,$5,$6,$7::jsonb,$8)", [requestId, connection.id, connection.owner_id, toolName, evidence.target.scope === "servers" ? evidence.target.serverIds : [], result.decision === "denied" ? "denied" : "running", JSON.stringify(redact(input)), result.decision === "denied" ? result.reasons[0]?.code : null])
if (result.decision !== "denied") { if (result.decision !== "denied") {
await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'calls',date_trunc('minute',now()),1) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=mcp_budget_buckets.used+1", [connection.id]) await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'calls',date_trunc('minute',now()),1) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=LEAST(mcp_budget_buckets.used::bigint+1,2147483647)", [connection.id])
if (action.operation.effect === "read") await client.query("INSERT INTO mcp_read_leases(id,connection_id,expires_at) VALUES($1,$2,now()+interval '2 minutes')", [requestId, connection.id]) if (action.operation.effect === "read") await client.query("INSERT INTO mcp_read_leases(id,connection_id,expires_at) VALUES($1,$2,now()+interval '2 minutes')", [requestId, connection.id])
await client.query("UPDATE mcp_connections SET last_used_at=now() WHERE id=$1", [connection.id]) await client.query("UPDATE mcp_connections SET last_used_at=now() WHERE id=$1", [connection.id])
} }
@@ -461,8 +461,8 @@ async function admitPlan(principal: McpPrincipal, planId: string, idempotencyKey
await assertOriginalMcpTemporaryGrant(client,connection.id,principal.credentialId,originalServiceGrant) await assertOriginalMcpTemporaryGrant(client,connection.id,principal.credentialId,originalServiceGrant)
} }
const mutationCost = reservedRouting ? 2 : changeMutationCost(evidence) + (evidence.recovery ? 1 : 0) const mutationCost = reservedRouting ? 2 : changeMutationCost(evidence) + (evidence.recovery ? 1 : 0)
if (input.usage.mutationsInHour + mutationCost > connection.policy.limits.mutationsPerHour) throw new McpError("BUDGET_EXCEEDED", "Недостаточно бюджета для всех шагов плана", 429) if (!hasUnlimitedMcpRates(connection.policy) && input.usage.mutationsInHour + mutationCost > connection.policy.limits.mutationsPerHour) throw new McpError("BUDGET_EXCEEDED", "Недостаточно бюджета для всех шагов плана", 429)
if (!reservedRouting) await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'mutations',date_trunc('hour',now()),$2) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=mcp_budget_buckets.used+EXCLUDED.used", [connection.id, mutationCost]) if (!reservedRouting) await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'mutations',date_trunc('hour',now()),$2) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=LEAST(mcp_budget_buckets.used::bigint+EXCLUDED.used,2147483647)", [connection.id, mutationCost])
if (delegated) { if (delegated) {
// Execution receipts use the delegating owner's ID. Object protections still require a human decision. // Execution receipts use the delegating owner's ID. Object protections still require a human decision.
plan.evidence.approvalSource = "connection-policy" plan.evidence.approvalSource = "connection-policy"
@@ -10,9 +10,8 @@ test("registration exposes one actual global write plan and fixed nondiagnostic
registerServerPollAction(((...args: Parameters<typeof add>) => { calls.push(args) }) as typeof add) registerServerPollAction(((...args: Parameters<typeof add>) => { calls.push(args) }) as typeof add)
assert.equal(calls.length, 1) assert.equal(calls.length, 1)
const [id, tool, description, section, permission, effect, scope, schema, handlers] = calls[0] const [id, tool, description, section, permission, effect, scope, schema, handlers] = calls[0]
assert.match(description, /8 на владельца, 128 на приложение/) assert.doesNotMatch(description, /8 на владельца|128 на приложение/)
assert.match(description, /Архивирование сохраняет аудит/) assert.match(description, /pollStorageUsage/)
assert.match(description, /pollStorageCapacity/)
assert.equal(mcpOperationDescriptorSchema.shape.title.safeParse(description).success, true) assert.equal(mcpOperationDescriptorSchema.shape.title.safeParse(description).success, true)
assert.equal(id, "servers.poll"); assert.equal(tool, "mm_server_poll_plan"); assert.equal(section, "servers") assert.equal(id, "servers.poll"); assert.equal(tool, "mm_server_poll_plan"); assert.equal(section, "servers")
assert.equal(permission, "mm:servers:write"); assert.equal(effect, "write"); assert.equal(scope, "global"); assert.equal(handlers.version, 1) assert.equal(permission, "mm:servers:write"); assert.equal(effect, "write"); assert.equal(scope, "global"); assert.equal(handlers.version, 1)
@@ -3,12 +3,11 @@ import { SERVER_POLL_OPERATION } from "../../services/server-poll-authority.js"
import { SERVER_POLL_MCP_OPERATION_VERSION } from "./server-poll-actions.js" import { SERVER_POLL_MCP_OPERATION_VERSION } from "./server-poll-actions.js"
import { createProductionServerPollMcpAdapter } from "./server-poll-production.js" import { createProductionServerPollMcpAdapter } from "./server-poll-production.js"
import { registerMcpService } from "./service-registry.js" import { registerMcpService } from "./service-registry.js"
import { SERVER_POLL_STORAGE_POLICY } from "../../services/server-poll-storage-model.js"
/** Normal startup enrolls quota-bound storage before public tools are served. */ /** Normal startup enrolls durable storage before public tools are served. */
export function registerServerPollAction(register: typeof add) { export function registerServerPollAction(register: typeof add) {
const adapter = createProductionServerPollMcpAdapter() const adapter = createProductionServerPollMcpAdapter()
registerMcpService(SERVER_POLL_OPERATION, adapter.service) registerMcpService(SERVER_POLL_OPERATION, adapter.service)
register(SERVER_POLL_OPERATION, "mm_server_poll_plan", `Полный опрос и история. Резерв: ${SERVER_POLL_STORAGE_POLICY.ownerAttempts} на владельца, ${SERVER_POLL_STORAGE_POLICY.globalAttempts} на приложение. Архивирование сохраняет аудит; остаток зависит от объёма истории. Статус: pollStorageCapacity в MCP overview.`, "servers", "mm:servers:write", "write", "global", adapter.schema, register(SERVER_POLL_OPERATION, "mm_server_poll_plan", "Полный опрос и история. Число журналов отображается в pollStorageUsage в MCP overview.", "servers", "mm:servers:write", "write", "global", adapter.schema,
{ version: SERVER_POLL_MCP_OPERATION_VERSION, target: adapter.target, prepare: adapter.prepare }) { version: SERVER_POLL_MCP_OPERATION_VERSION, target: adapter.target, prepare: adapter.prepare })
} }
@@ -64,6 +64,7 @@ export async function acceptServerProbeStorageHostSql() {
let raw = ""; for await (const chunk of request) raw += chunk let raw = ""; for await (const chunk of request) raw += chunk
const body = JSON.parse(raw) as Record<string, unknown> const body = JSON.parse(raw) as Record<string, unknown>
assert.equal(body.address, "127.0.0.1"); assert.equal(body.count, "1") assert.equal(body.address, "127.0.0.1"); assert.equal(body.count, "1")
assert.equal(Object.hasOwn(body, "src-address"), false)
if (requests === 2) { if (requests === 2) {
response.once("close", secondClosed) response.once("close", secondClosed)
secondValidated() secondValidated()
@@ -1,9 +1,8 @@
import { fingerprint, accessGeneration, McpError } from "./security.js" import { fingerprint, accessGeneration, McpError } from "./security.js"
import { pool } from "../../db/index.js" import { pool } from "../../db/index.js"
import { wireguardExportRequestSchema } from "../../services/wireguard-export.js"
import { effectiveMcpConnection } from "./store.js" import { effectiveMcpConnection } from "./store.js"
import { registerMcpService } from "./service-registry.js" import { registerMcpService } from "./service-registry.js"
import { wireguardExportAuthority, wireguardExportAuthoritySchema, createWireguardExportArtifact, readWireguardExportSource, verifyWireguardExportArtifact } from "./wireguard-export-artifact.js" import { wireguardExportAuthority, wireguardExportAuthoritySchema, createWireguardExportArtifact, mcpWireguardExportRequestSchema, readWireguardExportSource, verifyWireguardExportArtifact } from "./wireguard-export-artifact.js"
import type { add } from "./actions.js" import type { add } from "./actions.js"
export function registerWireguardExportActions(register: typeof add) { export function registerWireguardExportActions(register: typeof add) {
@@ -16,10 +15,10 @@ export function registerWireguardExportActions(register: typeof add) {
return receipt?.humanDownloadOnly===true && receipt.wireguardContentReturned===false && !!receipt.artifactId && await verifyWireguardExportArtifact(receipt.artifactId,authority(input),String(input.expectedProof)) return receipt?.humanDownloadOnly===true && receipt.wireguardContentReturned===false && !!receipt.artifactId && await verifyWireguardExportArtifact(receipt.artifactId,authority(input),String(input.expectedProof))
}, },
}) })
register("network.wireguard.export","mm_wireguard_export_plan","Подготовить WireGuard экспорт для скачивания владельцем после человеческого подтверждения","network","mm:network:write","write","servers",wireguardExportRequestSchema,{ register("network.wireguard.export","mm_wireguard_export_plan","Подготовить WireGuard экспорт или готовый .conf для Linux-клиента IX","network","mm:network:write","write","servers",mcpWireguardExportRequestSchema,{
target:input=>({scope:"servers",serverIds:[wireguardExportRequestSchema.parse(input).serverId]}), target:input=>({scope:"servers",serverIds:[mcpWireguardExportRequestSchema.parse(input).serverId]}),
prepare:async(input,context)=>{ prepare:async(input,context)=>{
const request=wireguardExportRequestSchema.parse(input) const request=mcpWireguardExportRequestSchema.parse(input)
const authorize=async()=>{ const authorize=async()=>{
if(context.signal?.aborted)throw new McpError("READ_CANCELLED","Экспорт WireGuard отменён",409) if(context.signal?.aborted)throw new McpError("READ_CANCELLED","Экспорт WireGuard отменён",409)
const fresh=await effectiveMcpConnection(context.principal) const fresh=await effectiveMcpConnection(context.principal)
@@ -33,7 +32,10 @@ export function registerWireguardExportActions(register: typeof add) {
await authorize() await authorize()
return {target:{scope:"servers",serverIds:[request.serverId]},objects:[{kind:"server",id:String(request.serverId),serverId:request.serverId},{kind:"wireguard-export",id:request.interfaceName,serverId:request.serverId},...protections.map(row=>row.object_ref)],snapshots:[],before:{proof:source.proof},requiresHuman:true,mutationCost:1, return {target:{scope:"servers",serverIds:[request.serverId]},objects:[{kind:"server",id:String(request.serverId),serverId:request.serverId},{kind:"wireguard-export",id:request.interfaceName,serverId:request.serverId},...protections.map(row=>row.object_ref)],snapshots:[],before:{proof:source.proof},requiresHuman:true,mutationCost:1,
steps:[{kind:"service",service:"network.wireguard.export",input:{authority:access,expectedProof:source.proof,beforeFingerprint:fingerprint({proof:source.proof})}}], steps:[{kind:"service",service:"network.wireguard.export",input:{authority:access,expectedProof:source.proof,beforeFingerprint:fingerprint({proof:source.proof})}}],
warnings:[request.includePrivateKey && request.format!=="peer-conf" ? "Этот пакет включает приватный ключ интерфейса WireGuard. Скачивание разрешено только вошедшему владельцу на 15 минут." : "Приватные ключи в этот пакет не включаются. Файл доступен только вошедшему владельцу на 15 минут.","Модель получает только квитанцию и ссылку; содержимое, native ключи и комментарии в MCP не возвращаются. Предел файла — 1 МиБ, чтения — 45 секунд.","Изменение источника, прав, подключений или защит блокирует выдачу. Формат conf не воспроизводит отключённые интерфейсы/пиры; peer-conf не раскрывает ключи клиента.",request.format==="conf"?"Формат conf переносит параметры туннеля; имя интерфейса, имена пиров и клиентские подсказки RouterOS в нём не восстанавливаются.":request.format==="peer-conf"?"peer-conf — шаблон клиента: приватный ключ и AllowedIPs заполняются человеком; готовность клиентского подключения не подтверждается.":"RSC сохраняет поддержанные native поля и отключённые состояния; фактический путь проверяется отдельно."]} warnings: request.ixSegmentId ? [
"Готовый конфиг IX содержит приватный ключ Linux-клиента. Скачивание доступно вошедшему владельцу на 15 минут.",
"MCP возвращает только квитанцию и ссылку. Изменение применённой ревизии, прав или защит блокирует выдачу.",
] : [request.includePrivateKey && request.format!=="peer-conf" ? "Этот пакет включает приватный ключ интерфейса WireGuard. Скачивание разрешено только вошедшему владельцу на 15 минут." : "Приватные ключи в этот пакет не включаются. Файл доступен только вошедшему владельцу на 15 минут.","Модель получает только квитанцию и ссылку; содержимое, native ключи и комментарии в MCP не возвращаются. Предел файла — 1 МиБ, чтения — 45 секунд.","Изменение источника, прав, подключений или защит блокирует выдачу. Формат conf не воспроизводит отключённые интерфейсы/пиры; peer-conf не раскрывает ключи клиента.",request.format==="conf"?"Формат conf переносит параметры туннеля; имя интерфейса, имена пиров и клиентские подсказки RouterOS в нём не восстанавливаются.":request.format==="peer-conf"?"peer-conf — шаблон клиента: приватный ключ и AllowedIPs заполняются человеком; готовность клиентского подключения не подтверждается.":"RSC сохраняет поддержанные native поля и отключённые состояния; фактический путь проверяется отдельно."]}
}, },
}) })
} }
@@ -4,6 +4,9 @@ import type { PoolClient } from "pg"
import { pool } from "../../db/index.js" import { pool } from "../../db/index.js"
import { hasPermission, type AuthUser } from "../../lib/permissions.js" import { hasPermission, type AuthUser } from "../../lib/permissions.js"
import { readWireguardExport, wireguardExportRequestSchema } from "../../services/wireguard-export.js" import { readWireguardExport, wireguardExportRequestSchema } from "../../services/wireguard-export.js"
import { readIxLinuxClient } from "../../services/internet-exchange-execution.js"
import { IxConflict } from "../../services/internet-exchange-plan.js"
import { readIxSegment } from "../../services/internet-exchange-store.js"
import { assertVerifiedConfigurationAccess, executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js" import { assertVerifiedConfigurationAccess, executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js"
import { assertLogArtifactBudget } from "./log-artifacts.js" import { assertLogArtifactBudget } from "./log-artifacts.js"
import { assertPortalClaimsCurrent } from "./portal-revocation.js" import { assertPortalClaimsCurrent } from "./portal-revocation.js"
@@ -13,7 +16,11 @@ import { accessGeneration, decryptSecret, encryptSecret, fingerprint, McpError,
const MAX_BYTES = 1048576, MAX_CIPHER = 2 * 1048576 const MAX_BYTES = 1048576, MAX_CIPHER = 2 * 1048576
const digest = z.string().regex(/^[a-f0-9]{64}$/) const digest = z.string().regex(/^[a-f0-9]{64}$/)
const principalSchema = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.iso.datetime() }).strict() const principalSchema = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.iso.datetime() }).strict()
export const wireguardExportAuthoritySchema = z.object({ principal: principalSchema, ownerId: z.string().min(1).max(200), policyProof: digest, generation: digest, request: wireguardExportRequestSchema }).strict() export const mcpWireguardExportRequestSchema = wireguardExportRequestSchema.extend({
ixSegmentId: z.string().uuid().optional().describe("Для готового конфига Linux из IX укажите ID сегмента и формат peer-conf"),
}).refine(request => !request.ixSegmentId || request.format === "peer-conf" && !request.peerId && !request.includePrivateKey,
"Для клиента IX укажите peer-conf и имя интерфейса клиента. Его управляемый ключ будет включён в файл.")
export const wireguardExportAuthoritySchema = z.object({ principal: principalSchema, ownerId: z.string().min(1).max(200), policyProof: digest, generation: digest, request: mcpWireguardExportRequestSchema }).strict()
export type WireguardExportAuthority = z.infer<typeof wireguardExportAuthoritySchema> export type WireguardExportAuthority = z.infer<typeof wireguardExportAuthoritySchema>
const scopeSchema = z.object({ version: z.literal(1), kind: z.literal("wireguard-export"), authority: wireguardExportAuthoritySchema, sourceProof: digest, const scopeSchema = z.object({ version: z.literal(1), kind: z.literal("wireguard-export"), authority: wireguardExportAuthoritySchema, sourceProof: digest,
bytes: z.number().int().min(0).max(MAX_BYTES), sha256: digest, encryptedSha256: digest, proof: digest }).strict() bytes: z.number().int().min(0).max(MAX_BYTES), sha256: digest, encryptedSha256: digest, proof: digest }).strict()
@@ -41,10 +48,25 @@ async function protectionProof(authority: WireguardExportAuthority, client: Pick
export async function readWireguardExportSource(authority: WireguardExportAuthority, authorize: () => Promise<unknown> = async()=>{}, signal?: AbortSignal) { export async function readWireguardExportSource(authority: WireguardExportAuthority, authorize: () => Promise<unknown> = async()=>{}, signal?: AbortSignal) {
await authorize(); await assertWireguardExportAccess(authority) await authorize(); await assertWireguardExportAccess(authority)
const protections=await protectionProof(authority) const protections=await protectionProof(authority)
const source=await readWireguardExport(authority.request, { signal, authorize: async()=>{ const check = async () => {
signal?.throwIfAborted()
await authorize(); await assertWireguardExportAccess(authority) await authorize(); await assertWireguardExportAccess(authority)
if (await protectionProof(authority)!==protections) throw fail("Защиты экспорта изменились", "STATE_CONFLICT") if (await protectionProof(authority)!==protections) throw fail("Защиты экспорта изменились", "STATE_CONFLICT")
} }) }
const { ixSegmentId, ...request } = authority.request
if (ixSegmentId) {
await check()
const segment = await readIxSegment(ixSegmentId)
if (!segment) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
const access = await readIxLinuxClient(segment, request.serverId, request.interfaceName, "wireguard").catch(error => {
if (error instanceof IxConflict) throw new McpError(error.statusCode === 404 ? "NOT_FOUND" : "STATE_CONFLICT", error.message, error.statusCode)
throw error
})
await check()
const proof = await sign({ protections, ixSegmentId, request, access })
return { filename: access.filename, content: Buffer.from(access.template), protectionProof: protections, proof }
}
const source=await readWireguardExport(request, { signal, authorize: check })
return {...source,protectionProof:protections,proof:await sign({nativeSource:source.proof,protections})} return {...source,protectionProof:protections,proof:await sign({nativeSource:source.proof,protections})}
} }
+2 -1
View File
@@ -276,7 +276,8 @@ export async function requireAuth(
/** Gate the matched route, including encoded static segments in the raw URL. */ /** Gate the matched route, including encoded static segments in the raw URL. */
export async function requireApiAuth(request: FastifyRequest, reply: FastifyReply): Promise<void> { export async function requireApiAuth(request: FastifyRequest, reply: FastifyReply): Promise<void> {
const pathname = request.routeOptions.url ?? request.url.split("?")[0] ?? request.url const pathname = request.routeOptions.url ?? request.url.split("?")[0] ?? request.url
if (!pathname.startsWith("/api/") || pathname === "/api/auth/config") return if (!pathname.startsWith("/api/") || pathname === "/api/auth/config" ||
request.method === "POST" && pathname === "/api/ix/import") return
await requireAuth(request, reply) await requireAuth(request, reply)
} }
+1 -1
View File
@@ -23,7 +23,7 @@ export function installDatabaseRequestGate(app: FastifyInstance, admit = withDat
const run = async () => withConfigurationActor(request.authUser?.id ?? "system", async () => await original.call(this, request, reply)) const run = async () => withConfigurationActor(request.authUser?.id ?? "system", async () => await original.call(this, request, reply))
// The service owns exclusivity, including calls that do not originate in HTTP. // The service owns exclusivity, including calls that do not originate in HTTP.
if (operation) return run() if (operation) return run()
if (!stream) return gate.request(() => admit(run)) if (!stream) return gate.request(() => admit(run, !["GET", "HEAD", "OPTIONS"].includes(request.method)))
const state = { cancelled: false, abort: undefined as (() => void) | undefined } const state = { cancelled: false, abort: undefined as (() => void) | undefined }
streams.set(request, state) streams.set(request, state)
try { try {
+22 -12
View File
@@ -1,3 +1,4 @@
import { coalesceCatalogReads, observationIsCurrent, readCatalogWithObservedCache, withCatalogWriteLock } from "../services/routing-catalog-observation.js"
import { and, asc, eq, inArray } from "drizzle-orm" import { and, asc, eq, inArray } from "drizzle-orm"
import { z } from "zod" import { z } from "zod"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod" import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
@@ -8,7 +9,6 @@ import { pollGreCatalog } from "../services/gre-catalog-poll.js"
import { parseKeepalive } from "../services/gre-live.js" import { parseKeepalive } from "../services/gre-live.js"
import { parseDbServerId } from "../utils/server-id.js" import { parseDbServerId } from "../utils/server-id.js"
import { observeBgpFilterRules } from "../services/filter-rules-observed.js" import { observeBgpFilterRules } from "../services/filter-rules-observed.js"
import { withApplicationMutationLock, withConfigMutationLock } from "../services/config-mutation-lock.js"
import { appendEvent } from "../modules/events/service/events-service.js" import { appendEvent } from "../modules/events/service/events-service.js"
import { managedComment, hasManagedCommentPrefix } from "../managed-markers.js" import { managedComment, hasManagedCommentPrefix } from "../managed-markers.js"
import { compileManagedFilterRules, filterRuleBranches, filterRuleDescriptions, filterRuleToken, validatedFilterRules } from "../services/filter-rules-write-model.js" import { compileManagedFilterRules, filterRuleBranches, filterRuleDescriptions, filterRuleToken, validatedFilterRules } from "../services/filter-rules-write-model.js"
@@ -282,6 +282,8 @@ export async function fetchServerFilters(server: ServerRow) {
} }
} }
const readWebFilters = coalesceCatalogReads(fetchServerFilters)
async function toApiRulesets(serverRows: ServerRow[]) { async function toApiRulesets(serverRows: ServerRow[]) {
const dbRules = serverRows.length ? await db.select().from(filterRules).where(inArray(filterRules.serverId, serverRows.map(server => server.id))).orderBy(asc(filterRules.serverId), asc(filterRules.sortOrder), asc(filterRules.id)) : [] const dbRules = serverRows.length ? await db.select().from(filterRules).where(inArray(filterRules.serverId, serverRows.map(server => server.id))).orderBy(asc(filterRules.serverId), asc(filterRules.sortOrder), asc(filterRules.id)) : []
return serverRows.map(s => ({ return serverRows.map(s => ({
@@ -381,20 +383,26 @@ export async function readFilterRulesCatalog(selected: ServerRow[], options: { s
const rulesets = await toApiRulesets(selected) const rulesets = await toApiRulesets(selected)
return rulesets.map(ruleset => ({ ...ruleset, greTunnels: [] as LiveGreTunnel[], nativeRules: null as ReturnType<typeof observeBgpFilterRules> | null, live: false, stale: false, source: "cache" as const, error: null as string | null })) return rulesets.map(ruleset => ({ ...ruleset, greTunnels: [] as LiveGreTunnel[], nativeRules: null as ReturnType<typeof observeBgpFilterRules> | null, live: false, stale: false, source: "cache" as const, error: null as string | null }))
} }
const readSelected = () => Promise.all(selected.map(async server => { return Promise.all(selected.map(async server => {
try { try {
const remote = await fetchServerFilters(server) const read = async (fresh: boolean) => {
if (options.persistObserved) { const remote = await (fresh || !options.persistObserved ? fetchServerFilters : readWebFilters)(server)
if (!options.persistObserved) return { remote, rules: remote.rules, current: true }
const rules = await cacheRulesetsForServer(server.id)
const current = await observationIsCurrent(server.id, "filters", canonicalFilterRules(remote.rules), canonicalFilterRules(rules))
return { remote, rules, current }
}
const { remote, rules } = await readCatalogWithObservedCache(server, read, async ({ remote }) => {
await replaceDbRules(server.id, remote.rules) await replaceDbRules(server.id, remote.rules)
await appendRevisionIfChanged({ serverId: server.id, section: "filters", source: "observed", payload: canonicalFilterRules(remote.rules) }) await appendRevisionIfChanged({ serverId: server.id, section: "filters", source: "observed", payload: canonicalFilterRules(remote.rules) })
} return { remote, rules: await cacheRulesetsForServer(server.id), current: true }
return { serverId: String(server.id), rules: options.persistObserved ? await cacheRulesetsForServer(server.id) : remote.rules, greTunnels: remote.tunnels, nativeRules: remote.nativeRules, live: true, stale: false, source: "device" as const, error: null as string | null } })
} catch { return { serverId: String(server.id), rules, greTunnels: remote.tunnels, nativeRules: remote.nativeRules, live: true, stale: false, source: "device" as const, error: null as string | null }
} catch (error) {
if (error instanceof McpError && error.statusCode === 409) throw error
return { serverId: String(server.id), rules: await cacheRulesetsForServer(server.id), greTunnels: [] as LiveGreTunnel[], nativeRules: null, live: false, stale: true, source: "cache" as const, error: server.enabled ? "Не подтверждено чтение фильтров выбранного сервера" : "Сервер выключен. Опрос фильтров недоступен." } return { serverId: String(server.id), rules: await cacheRulesetsForServer(server.id), greTunnels: [] as LiveGreTunnel[], nativeRules: null, live: false, stale: true, source: "cache" as const, error: server.enabled ? "Не подтверждено чтение фильтров выбранного сервера" : "Сервер выключен. Опрос фильтров недоступен." }
} }
})) }))
return options.persistObserved
? withApplicationMutationLock(() => withConfigMutationLock(selected.map(server => server.id), readSelected)) : readSelected()
} }
export async function applyFiltersToServer( export async function applyFiltersToServer(
@@ -406,7 +414,7 @@ export async function applyFiltersToServer(
if (!server.enabled) throw new McpError("DEVICE_UNAVAILABLE", "Сервер выключен; изменение фильтров запрещено", 409) if (!server.enabled) throw new McpError("DEVICE_UNAVAILABLE", "Сервер выключен; изменение фильтров запрещено", 409)
if (options.managedRuleComment !== undefined && !hasManagedCommentPrefix(options.managedRuleComment)) throw new McpError("PROTECTED_OBJECT", "Сохранённый comment фильтра не принадлежит приложению", 409) if (options.managedRuleComment !== undefined && !hasManagedCommentPrefix(options.managedRuleComment)) throw new McpError("PROTECTED_OBJECT", "Сохранённый comment фильтра не принадлежит приложению", 409)
rules = validatedFilterRules(rules) rules = validatedFilterRules(rules)
return executeGuardedApplicationWrite({ kind: "filters", id: "managed-bgp-in" }, [server.id], () => withConfigMutationLock([server.id], async () => { return withCatalogWriteLock(server, "filters", () => executeGuardedApplicationWrite({ kind: "filters", id: "managed-bgp-in" }, [server.id], async () => {
const client = MikrotikClient.fromServer(server) const client = MikrotikClient.fromServer(server)
const interfaces = rules.some(rule => rule.action !== "blackhole" && rule.gatewayTunnelId && !rule.gatewayTunnelId.startsWith("rec:")) ? nativeBgpRows(await client.get("/interface/gre")) : [] const interfaces = rules.some(rule => rule.action !== "blackhole" && rule.gatewayTunnelId && !rule.gatewayTunnelId.startsWith("rec:")) ? nativeBgpRows(await client.get("/interface/gre")) : []
const ruleBody = await toRouterRuleBody(server.id, rules, interfaces) const ruleBody = await toRouterRuleBody(server.id, rules, interfaces)
@@ -442,7 +450,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
const server = enabledServers.find(s => s.id === sid) const server = enabledServers.find(s => s.id === sid)
if (!server) return reply.status(404).send({ error: "Server not found" }) if (!server) return reply.status(404).send({ error: "Server not found" })
try { try {
const remote = await fetchServerFilters(server) const remote = await readWebFilters(server)
return reply.send({ tunnels: remote.tunnels }) return reply.send({ tunnels: remote.tunnels })
} catch (error) { } catch (error) {
app.log.warn({ serverId: sid, err: String(error) }, "filters GRE catalog unavailable") app.log.warn({ serverId: sid, err: String(error) }, "filters GRE catalog unavailable")
@@ -450,7 +458,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
} }
} }
return reply.send(await pollGreCatalog(enabledServers, fetchServerFilters)) return reply.send(await pollGreCatalog(enabledServers, readWebFilters))
}) })
/** Без serverId — cache для дашборда. С serverId — live с CHR, cache fallback. */ /** Без serverId — cache для дашборда. С serverId — live с CHR, cache fallback. */
@@ -523,6 +531,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
rules: cached, rules: cached,
}) })
} catch (err) { } catch (err) {
if (err instanceof McpError && err.statusCode === 409) throw err
app.log.error({ serverId, err: String(err) }, "filters apply failed") app.log.error({ serverId, err: String(err) }, "filters apply failed")
await appendEvent({ await appendEvent({
level: "critical", level: "critical",
@@ -588,6 +597,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
}) })
return reply.send({ ok: true, rules: cached, pushedRules: result.pushed }) return reply.send({ ok: true, rules: cached, pushedRules: result.pushed })
} catch (err) { } catch (err) {
if (err instanceof McpError) throw err
app.log.error({ serverId: server.id, err: String(err) }, "filters restore failed") app.log.error({ serverId: server.id, err: String(err) }, "filters restore failed")
return reply.status(500).send({ error: String(err) }) return reply.status(500).send({ error: String(err) })
} }
+324
View File
@@ -0,0 +1,324 @@
import { randomUUID } from "node:crypto"
import type { FastifyPluginAsync } from "fastify"
import { z } from "zod"
import { ixBondEditSchema, ixChangeSchema, ixLinuxClientRequest, ixTransitRequest, type IxWebPlan } from "@mmapp/contracts/internet-exchange"
import { fingerprint, McpError } from "../modules/mcp/security.js"
import { audit } from "../modules/mcp/store.js"
import { pool } from "../db/index.js"
import { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError, type VerifiedRestRequestAuthority } from "../plugins/auth.js"
import { assertPortalClaimsCurrent } from "../modules/mcp/portal-revocation.js"
import { createIxImportLinks } from "../services/ix-import-links.js"
import { withApplicationCollectorLock, withApplicationMutationLock } from "../services/config-mutation-lock.js"
import { withConfigurationActor } from "../services/config-mutation-policy.js"
import { applyIxChange, assignIxRouterIds, configureIxLinuxClient, configureIxTransit, listIxLinuxClients, observeIxLinuxPath, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxLinuxClient, readIxNodeInventory, removeIxSegment } from "../services/internet-exchange-execution.js"
import { compileIxConfiguration, IxConflict } from "../services/internet-exchange-plan.js"
import { assertIxRevision, listIxSegments, readIxSegment, writeIxRevision } from "../services/internet-exchange-store.js"
import { changeIxBond, exportIxBond, inspectIxBondImports, ixBondCatalog } from "../services/internet-exchange-bonds.js"
const paging = z.object({
limit: z.coerce.number().int().min(1).max(100).default(25),
offset: z.coerce.number().int().min(0).max(1000000).default(0),
}).strict()
const segmentParams = z.object({ id: z.string().uuid() })
const planRequest = z.object({ revision: z.number().int().positive() }).strict()
const applyRequest = planRequest.extend({ digest: z.string().regex(/^[a-f0-9]{64}$/) })
const clientKey = z.object({ serverId: z.number().int().positive().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) })
const safeFields = (fields: Record<string, string>) => Object.fromEntries(Object.entries(fields).filter(([key]) => key !== "secret" && key !== "private-key"))
async function prepareSavedRevision(id: string, revision: number, resume = false) {
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(segment, revision)
if (segment.appliedRevision === revision) throw new IxConflict("Эта ревизия IX уже применена")
return prepareIxChange({ id, revision, configuration: segment.configuration }, resume)
}
function reviewDigest(prepared: Awaited<ReturnType<typeof prepareSavedRevision>>, actorId: string, resume: boolean) {
return fingerprint({ operation: "ix.web.apply", actorId, change: prepared.change, before: prepared.before, tasks: prepared.native.tasks, resume })
}
function removalDigest(id: string, revision: number, actorId: string, nativeDigest: string) {
return fingerprint({ operation: "ix.web.delete", id, revision, actorId, nativeDigest })
}
function summarizeTasks(tasks: Awaited<ReturnType<typeof prepareIxChange>>["native"]["tasks"]): IxWebPlan["changes"] {
return tasks.map(task => ({
serverId: task.serverId, path: task.path,
action: task.fields ? task.rosId ? "update" : "create" : "delete",
target: task.before?.name ?? task.before?.comment ?? task.fields?.name ?? task.fields?.comment ?? task.rosId,
placeBefore: task.placeBefore,
fields: task.fields ? safeFields(task.fields) : Object.fromEntries(Object.entries(task.before ?? {}).filter(([key]) => ["name", "comment", "dst-address", "chain"].includes(key))),
}))
}
const importLinkLifetime = 5 * 60_000
function importLinkOwner(authority: VerifiedRestRequestAuthority) {
const { ownerId, issuedAt, authentication, expiresAt } = authority
return async () => {
if (Date.now() >= expiresAt) throw new IxConflict("Ссылка истекла", 410)
if (authentication === "jwt") await assertPortalClaimsCurrent({ id: ownerId, issuedAt })
}
}
const ixRoutes: FastifyPluginAsync = async app => {
const links = createIxImportLinks()
app.post("/ix/import", { bodyLimit: 256 }, async (request, reply) => {
reply.header("Cache-Control", "private, no-store")
const { code } = z.object({ code: z.string().regex(/^[A-Za-z0-9_-]{32}$/) }).strict().parse(request.body)
return links.redeem(code)
})
app.setErrorHandler((error, request, reply) => {
if (error instanceof z.ZodError) return reply.code(400).send({ error: "Некорректные параметры IX", details: error.issues })
if (error instanceof IxConflict) return reply.code(error.statusCode).send({ error: error.message })
if (error instanceof McpError) return reply.code(error.statusCode).send({ error: error.message, code: error.code })
if (error instanceof RestRequestProvenanceError) return reply.code(403).send({ error: "Нет действующего права изменения IX" })
request.log.error({ error: error instanceof Error ? error.name : "unknown" }, "IX request failed")
const errorMessage = request.method === "DELETE" ? "Удаление сегмента IX не подтверждено. Обновите данные и проверьте план."
: request.routeOptions.url?.endsWith("/apply")
? "Результат применения IX не подтверждён"
: "Не удалось получить данные для операции IX"
return reply.code(503).send({ error: errorMessage })
})
app.get("/ix/segments", async request => {
const input = paging.parse(request.query)
return { items: await listIxSegments(input.limit, input.offset) }
})
app.get("/ix/linux-bonds", async () => ixBondCatalog())
app.post("/ix/segments/:id/linux-bonds", async request => {
const { id } = segmentParams.parse(request.params)
const edit = ixBondEditSchema.parse(request.body)
await inspectIxBondImports(id, edit)
return withApplicationMutationLock(() => changeIxBond(id, edit, request.authUser?.id ?? "local-operator"), { waitMs: 5000 })
})
app.delete("/ix/segments/:id/linux-bonds/:bondId", async (request, reply) => {
const { id, bondId } = segmentParams.extend({ bondId: z.uuid() }).parse(request.params)
const { revision } = planRequest.parse(request.body)
await withApplicationMutationLock(() => changeIxBond(id, { id: bondId, revision }, request.authUser?.id ?? "local-operator"), { waitMs: 5000 })
return reply.code(204).send()
})
app.post("/ix/segments/:id/linux-bonds/:bondId/export", async (request, reply) => {
const { id, bondId } = segmentParams.extend({ bondId: z.uuid() }).parse(request.params)
const { revision, importLink } = planRequest.extend({ importLink: z.boolean().optional() }).parse(request.body)
const scope = { deadlineAt: Date.now() + (importLink ? importLinkLifetime : 90_000) }
const token = await captureVerifiedRestRequest(request, scope)
const authorize = () => inspectVerifiedRestRequest(token, scope, "mm:network:write")
const authority = await authorize()
const { ownerId } = authority
if (importLink) {
const authorizeOwner = importLinkOwner(authority)
await audit(pool, ownerId, "ix.bond.import_link_issued", null, { segmentId: id, bondId, revision })
await authorize()
reply.header("Cache-Control", "private, no-store")
return { code: links.issue(authority.monotonicDeadline, () => withApplicationCollectorLock(async () => {
await authorizeOwner()
const bond = await exportIxBond(id, bondId, revision, authorizeOwner)
await audit(pool, ownerId, "ix.bond.exported", null, { segmentId: id, bondId, revision })
await authorizeOwner()
return { version: 1, kind: "bond", bond }
})) }
}
return withApplicationCollectorLock(async () => {
const bundle = await exportIxBond(id, bondId, revision, authorize)
await audit(pool, ownerId, "ix.bond.exported", null, { segmentId: id, bondId, revision })
await authorize()
reply.header("Cache-Control", "no-store")
return bundle
})
})
app.get("/ix/nodes", async () => {
const [nodes, peers] = await Promise.all([
pool.query("SELECT id,name,site,country,enabled FROM servers WHERE type='ix-node' ORDER BY name,id LIMIT 500"),
pool.query("SELECT id,name,site,country,enabled,type FROM servers ORDER BY name,id LIMIT 1000"),
])
return { items: nodes.rows, peers: peers.rows }
})
app.get("/ix/nodes/:serverId/inventory", async request => {
const { serverId } = z.object({ serverId: z.coerce.number().int().positive().safe() }).parse(request.params)
const { segmentId } = z.object({ segmentId: z.string().uuid().optional() }).strict().parse(request.query)
const segment = segmentId ? await readIxSegment(segmentId) : null
if (segmentId && !segment) throw new IxConflict("Сегмент IX не найден", 404)
return readIxNodeInventory(serverId, segment ?? undefined, true)
})
app.get("/ix/topology", async () => {
const segments = await listIxSegments(100, 0)
const links = segments.filter(segment => segment.appliedRevision === segment.revision).flatMap(({ configuration }) =>
configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.peerServerId === undefined
? []
: [{ from: site.serverId, to: binding.peerServerId, segment: configuration.name }])))
return { links }
})
app.get("/ix/segments/:id/status", async request => {
const { id } = z.object({ id: z.string().uuid() }).parse(request.params)
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
return { sites: await observeIxSegment(segment) }
})
app.get("/ix/segments/:id/linux", async request => {
const { id } = z.object({ id: z.string().uuid() }).parse(request.params)
const query = z.union([
z.object({ serverId: z.coerce.number().positive().int().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/), transportOnly: z.literal("true").optional() }).strict(),
z.object({}).strict(),
]).parse(request.query)
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
return "serverId" in query ? readIxLinuxClient(segment, query.serverId, query.interfaceName, false, query.transportOnly === "true") : listIxLinuxClients(segment)
})
app.post("/ix/segments/:id/linux", async request => {
const { id } = segmentParams.parse(request.params)
const input = ixLinuxClientRequest.parse(request.body)
return withApplicationMutationLock(async () => {
const current = await readIxSegment(id)
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(current, input.revision)
const base = input.transit ? { ...current, configuration: await configureIxTransit(current, {
...input.transit, revision: input.revision, serverId: input.serverId,
}) } : current
const { configuration, interfaceName } = await configureIxLinuxClient(base, {
...input, exit: input.transit?.name ?? input.exit,
})
const segment = await writeIxRevision(id, current.revision, configuration, request.authUser?.id ?? "system", false)
return { segment, interfaceName }
}, { waitMs: 5000 })
})
app.get("/ix/segments/:id/linux/path", async request => {
const { id } = segmentParams.parse(request.params)
const { serverId, interfaceName } = clientKey.extend({ serverId: z.coerce.number().int().positive().safe() }).strict().parse(request.query)
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
return observeIxLinuxPath(segment, serverId, interfaceName)
})
app.post("/ix/segments/:id/linux/credential", async (request, reply) => {
const { id } = segmentParams.parse(request.params)
const { serverId, interfaceName, transportOnly, importLink } = clientKey.extend({
transportOnly: z.boolean().optional(), importLink: z.boolean().optional(),
}).parse(request.body)
const scope = { deadlineAt: Date.now() + (importLink ? importLinkLifetime : 60_000) }
const token = await captureVerifiedRestRequest(request, scope)
const authority = await inspectVerifiedRestRequest(token, scope, "mm:network:write")
const { ownerId } = authority
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
if (importLink) {
const revision = segment.appliedRevision
if (revision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
const authorizeOwner = importLinkOwner(authority)
await audit(pool, ownerId, "ix.linux.import_link_issued", null, { segmentId: id, serverId, interfaceName, revision })
await inspectVerifiedRestRequest(token, scope, "mm:network:write")
reply.header("Cache-Control", "private, no-store")
return { code: links.issue(authority.monotonicDeadline, async () => {
await authorizeOwner()
const current = await readIxSegment(id)
if (!current || current.appliedRevision !== revision) throw new IxConflict("Ревизия IX изменилась; получите новую ссылку", 410)
const access = await readIxLinuxClient(current, serverId, interfaceName, true, true, true)
if ((await readIxSegment(id))?.appliedRevision !== revision) throw new IxConflict("Ревизия IX изменилась; получите новую ссылку", 410)
await audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision })
await authorizeOwner()
const name = access.filename.replace(/\.conf$/, "")
if (access.kind === "wireguard") return { version: 1, kind: "wireguard", name, config: access.template }
if (!access.greImport) throw new IxConflict("Нет параметров управляемого GRE/IPsec")
return { version: 1, kind: "gre-ipsec", name, gre: access.greImport }
}) }
}
const access = await readIxLinuxClient(segment, serverId, interfaceName, true, transportOnly)
await inspectVerifiedRestRequest(token, scope, "mm:network:write")
await audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision: access.revision })
reply.header("Cache-Control", "no-store")
return access
})
app.post("/ix/segments/:id/linux/revoke", async request => {
const { id } = segmentParams.parse(request.params)
const { serverId, interfaceName, revision } = clientKey.extend(planRequest.shape).strict().parse(request.body)
return withApplicationMutationLock(async () => {
const current = await readIxSegment(id)
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(current, revision)
const site = current.configuration.sites.find(item => item.serverId === serverId)
if (!site?.interfaces.some(item => item.name === interfaceName && item.linux)) throw new IxConflict("Управляемый клиент не найден", 404)
const configuration = { ...current.configuration, sites: current.configuration.sites.map(item => item !== site ? item : {
...item, interfaces: item.interfaces.filter(binding => binding.name !== interfaceName),
neighbors: item.neighbors.filter(neighbor => neighbor.binding !== interfaceName),
}) }
compileIxConfiguration(id, configuration)
return { segment: await writeIxRevision(id, revision, configuration, request.authUser?.id ?? "system", false) }
}, { waitMs: 5000 })
})
app.post("/ix/segments/:id/transit", async request => {
const { id } = segmentParams.parse(request.params)
const input = ixTransitRequest.parse(request.body)
return withApplicationMutationLock(async () => {
const current = await readIxSegment(id)
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(current, input.revision)
const configuration = await configureIxTransit(current, input)
return { segment: await writeIxRevision(id, current.revision, configuration, request.authUser?.id ?? "system", false) }
}, { waitMs: 5000 })
})
app.post("/ix/segments", async request => {
const input = ixChangeSchema.parse(request.body)
const id = input.id ?? randomUUID()
return withApplicationMutationLock(async () => {
const current = input.id ? await readIxSegment(id) : null
assertIxRevision(current, input.revision)
const configuration = await assignIxRouterIds(id, input.configuration, current)
compileIxConfiguration(id, configuration)
const segment = await writeIxRevision(id, input.revision, configuration, request.authUser?.id ?? "system", false)
return { segment }
}, { waitMs: 5000 })
})
app.post("/ix/preview", async request => {
const input = ixChangeSchema.parse(request.body)
const id = input.id ?? randomUUID()
assertIxRevision(input.id ? await readIxSegment(id) : null, input.revision)
return { id, objects: compileIxConfiguration(id, input.configuration).map(object => ({ ...object, fields: safeFields(object.fields) })) }
})
app.post("/ix/segments/:id/plan", async (request): Promise<IxWebPlan> => {
const { id } = segmentParams.parse(request.params)
const { revision, resume = false } = planRequest.extend({ resume: z.boolean().optional() }).parse(request.body)
const prepared = await prepareSavedRevision(id, revision, resume)
return {
revision, digest: reviewDigest(prepared, request.authUser?.id ?? "local-operator", resume), ...(resume && { resume }),
changes: summarizeTasks(prepared.native.tasks),
}
})
app.post("/ix/segments/:id/apply", async request => {
const { id } = segmentParams.parse(request.params)
const { revision, digest, resume = false } = applyRequest.extend({ resume: z.boolean().optional() }).parse(request.body)
const scope = { deadlineAt: Date.now() + 180_000 }
const token = await captureVerifiedRestRequest(request, scope)
const inspect = () => inspectVerifiedRestRequest(token, scope, "mm:network:write")
const { ownerId } = await inspect()
const prepared = await prepareSavedRevision(id, revision, resume)
if (digest !== reviewDigest(prepared, ownerId, resume)) throw new IxConflict("План IX устарел. Постройте новый предпросмотр")
const result = await withConfigurationActor(ownerId, () => applyIxChange(id, prepared.change, prepared.before, ownerId,
async () => { await inspect() }, { resume }))
return { segment: await readIxSegment(result.segmentId), result }
})
app.post("/ix/segments/:id/removal-plan", async (request): Promise<IxWebPlan> => {
const { id } = segmentParams.parse(request.params)
const { revision } = planRequest.parse(request.body)
const prepared = await prepareIxRemoval(id, revision)
return { revision, digest: removalDigest(id, revision, request.authUser?.id ?? "local-operator", prepared.digest),
changes: summarizeTasks(prepared.native.tasks) }
})
app.delete("/ix/segments/:id", async (request, reply) => {
const { id } = segmentParams.parse(request.params)
const { revision, digest } = applyRequest.parse(request.body)
const scope = { deadlineAt: Date.now() + 180_000 }
const token = await captureVerifiedRestRequest(request, scope)
const inspect = () => inspectVerifiedRestRequest(token, scope, "mm:network:write")
const { ownerId } = await inspect()
const prepared = await prepareIxRemoval(id, revision)
if (digest !== removalDigest(id, revision, ownerId, prepared.digest)) {
throw new IxConflict("План удаления IX устарел. Подготовьте новый план")
}
await withConfigurationActor(ownerId, () => removeIxSegment(id, revision, prepared.digest, ownerId, async () => { await inspect() }))
return reply.code(204).send()
})
}
export default ixRoutes
+18 -4
View File
@@ -19,6 +19,8 @@ import { accessGeneration, decryptSecret, encryptSecret, McpError, randomToken,
import { createMcpConnection, listMcpConnections, getMcpSettings, updateMcpSettings, getConnection, assertConnectionVisible, rotateConnectionToken, setConnectionStatus, updateMcpConnection, connectionWrite, requestAccountingWrite, audit } from "../modules/mcp/store.js" import { createMcpConnection, listMcpConnections, getMcpSettings, updateMcpSettings, getConnection, assertConnectionVisible, rotateConnectionToken, setConnectionStatus, updateMcpConnection, connectionWrite, requestAccountingWrite, audit } from "../modules/mcp/store.js"
import { approvePlan, loadPlan, publicPlan, readMcpPolicyPreviewInput } from "../modules/mcp/runtime.js" import { approvePlan, loadPlan, publicPlan, readMcpPolicyPreviewInput } from "../modules/mcp/runtime.js"
import { applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js" import { applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js"
import { ixChangeSchema } from "@mmapp/contracts/internet-exchange"
import { ixOperation, ixRestoreOperation } from "../modules/mcp/internet-exchange-actions.js"
import { findOwnerPlanReplayTombstone } from "../modules/mcp/operation-replay-tombstones.js" import { findOwnerPlanReplayTombstone } from "../modules/mcp/operation-replay-tombstones.js"
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing" import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
import { revalidateMcpOwner } from "../modules/mcp/store.js" import { revalidateMcpOwner } from "../modules/mcp/store.js"
@@ -37,7 +39,7 @@ import { humanWireguardExportMetadata, readHumanWireguardExportArtifact } from "
import { humanArtifactReceipts } from "../modules/mcp/human-artifact-receipts.js" import { humanArtifactReceipts } from "../modules/mcp/human-artifact-receipts.js"
import { readHumanHostFilesArtifact } from "../modules/mcp/host-files-artifact.js" import { readHumanHostFilesArtifact } from "../modules/mcp/host-files-artifact.js"
import { loadLogExportArtifactMetadata } from "../modules/mcp/log-artifacts.js" import { loadLogExportArtifactMetadata } from "../modules/mcp/log-artifacts.js"
import { readServerPollCapacity } from "../services/server-poll-capacity.js" import { readServerPollUsage } from "../services/server-poll-capacity.js"
import { connectProbeStorage } from "../services/server-probe-storage-connection.js" import { connectProbeStorage } from "../services/server-probe-storage-connection.js"
const uuid = z.string().uuid() const uuid = z.string().uuid()
@@ -54,12 +56,12 @@ export function mcpDevicePlanArguments(serverId: number, input: z.infer<typeof m
} }
const idOf = (params: unknown) => z.object({ id: uuid }).parse(params).id const idOf = (params: unknown) => z.object({ id: uuid }).parse(params).id
const actorOf = (actor?: AuthUser) => { if (!actor) throw new McpError("UNAUTHORIZED", "Требуется вход", 401); return actor } const actorOf = (actor?: AuthUser) => { if (!actor) throw new McpError("UNAUTHORIZED", "Требуется вход", 401); return actor }
async function pollCapacityForPortal(ownerId:string,admin:boolean){ async function pollUsageForPortal(ownerId:string,admin:boolean){
const options={deadlineAt:Date.now()+3000} const options={deadlineAt:Date.now()+3000}
let connection:Awaited<ReturnType<typeof connectProbeStorage>>|undefined let connection:Awaited<ReturnType<typeof connectProbeStorage>>|undefined
try{ try{
connection=await connectProbeStorage(options) connection=await connectProbeStorage(options)
return await readServerPollCapacity({query:(text,values)=>connection!.query(text,values,{timeoutMs:Math.max(1,options.deadlineAt-Date.now())})},ownerId,admin) return await readServerPollUsage({query:(text,values)=>connection!.query(text,values,{timeoutMs:Math.max(1,options.deadlineAt-Date.now())})},ownerId,admin)
}catch{return {status:"unavailable" as const}} }catch{return {status:"unavailable" as const}}
finally{connection?.release()} finally{connection?.release()}
} }
@@ -252,7 +254,7 @@ export function createMcpRoutes(checkClaims: typeof assertPortalClaimsCurrent =
(SELECT count(*)::int FROM mcp_requests r JOIN mcp_connections c ON c.id=r.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND r.created_at>now()-interval '24 hours' AND r.status IN ('error','denied')) AS errors, (SELECT count(*)::int FROM mcp_requests r JOIN mcp_connections c ON c.id=r.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND r.created_at>now()-interval '24 hours' AND r.status IN ('error','denied')) AS errors,
(SELECT count(*)::int FROM mcp_plans p JOIN mcp_connections c ON c.id=p.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND p.state='awaiting-approval' AND p.expires_at>now()) AS approvals, (SELECT count(*)::int FROM mcp_plans p JOIN mcp_connections c ON c.id=p.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND p.state='awaiting-approval' AND p.expires_at>now()) AS approvals,
(SELECT count(*)::int FROM mcp_operations o JOIN mcp_connections c ON c.id=o.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND o.state IN ('running','pending')) AS running`, [admin, actor.id]) (SELECT count(*)::int FROM mcp_operations o JOIN mcp_connections c ON c.id=o.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND o.state IN ('running','pending')) AS running`, [admin, actor.id])
return { ...summary, pollStorageCapacity:await pollCapacityForPortal(actor.id,admin), enabled: (await getMcpSettings()).enabled, observedAt: new Date().toISOString() } return { ...summary, pollStorageUsage:await pollUsageForPortal(actor.id,admin), enabled: (await getMcpSettings()).enabled, observedAt: new Date().toISOString() }
}) })
for (const table of ["requests", "plans", "operations", "audit", "drift"] as const) { for (const table of ["requests", "plans", "operations", "audit", "drift"] as const) {
app.get(`/mcp/${table}`, async request => { app.get(`/mcp/${table}`, async request => {
@@ -411,6 +413,18 @@ export function createMcpRoutes(checkClaims: typeof assertPortalClaimsCurrent =
await auditOwnerRequest(actor.id, "controller.web.plan", input.connectionId, { profileId: input.profileId ?? null }) await auditOwnerRequest(actor.id, "controller.web.plan", input.connectionId, { profileId: input.profileId ?? null })
return ownerDelegate(async () => invokeMcpTool(principal, "mm_route_profile_save_plan", payload)) return ownerDelegate(async () => invokeMcpTool(principal, "mm_route_profile_save_plan", payload))
}) })
app.post("/mcp/ix/plan", async request => {
const { connectionId, change } = z.object({ connectionId: uuid, change: ixChangeSchema }).strict().parse(request.body)
const actor = actorOf(request.authUser), principal = await ownerPrincipal(connectionId, actor, ixOperation)
await auditOwnerRequest(actor.id, "ix.web.plan", connectionId, { segmentId: change.id ?? null })
return ownerDelegate(() => invokeMcpTool(principal, "mm_ix_change_plan", { change }))
})
app.post("/mcp/ix/restore", async request => {
const { connectionId, ...input } = z.object({ connectionId: uuid, id: uuid, revision: z.number().int().positive(), restoreRevision: z.number().int().positive() }).strict().parse(request.body)
const actor = actorOf(request.authUser), principal = await ownerPrincipal(connectionId, actor, ixRestoreOperation)
await auditOwnerRequest(actor.id, "ix.web.restore", connectionId, { segmentId: input.id, revision: input.restoreRevision })
return ownerDelegate(() => invokeMcpTool(principal, "mm_ix_restore_plan", input))
})
app.post("/mcp/secrets", async request => { app.post("/mcp/secrets", async request => {
const input = z.object({ purpose: z.string().min(1).max(512), serverId: z.number().int().positive().optional(), value: z.string().min(1).max(1000000) }).strict().parse(request.body), id = randomUUID(), actor = actorOf(request.authUser) const input = z.object({ purpose: z.string().min(1).max(512), serverId: z.number().int().positive().optional(), value: z.string().min(1).max(1000000) }).strict().parse(request.body), id = randomUUID(), actor = actorOf(request.authUser)
await connectionWrite(async client => { await client.query("INSERT INTO mcp_secrets(id,purpose,server_id,ciphertext,created_by) VALUES($1,$2,$3,$4,$5)", [id, input.purpose, input.serverId ?? null, await encryptSecret(input.value), actor.id]); await audit(client, actor.id, "secret.create", null, { secretRef: id, purpose: input.purpose, serverId: input.serverId }) }) await connectionWrite(async client => { await client.query("INSERT INTO mcp_secrets(id,purpose,server_id,ciphertext,created_by) VALUES($1,$2,$3,$4,$5)", [id, input.purpose, input.serverId ?? null, await encryptSecret(input.value), actor.id]); await audit(client, actor.id, "secret.create", null, { secretRef: id, purpose: input.purpose, serverId: input.serverId }) })
+41 -25
View File
@@ -1,9 +1,10 @@
import { coalesceCatalogReads, observationIsCurrent, readCatalogWithObservedCache, withCatalogWriteLock } from "../services/routing-catalog-observation.js"
import { recursiveApplyBodySchema, recursiveTargetSchema, recursiveInputRowsSchema } from '../services/recursive-route-validation.js' import { recursiveApplyBodySchema, recursiveTargetSchema, recursiveInputRowsSchema } from '../services/recursive-route-validation.js'
import { parseRecursiveCatalog, parseRecursiveGatewayCatalog, readRecursiveEffectiveProperties, type RecursiveObservedProperty } from "../services/recursive-route-catalog.js" import { parseRecursiveCatalog, parseRecursiveGatewayCatalog, readRecursiveEffectiveProperties, type RecursiveObservedProperty } from "../services/recursive-route-catalog.js"
import { executeRecursiveApply, RecursiveApplyError } from "../services/recursive-apply.js" import { executeRecursiveApply, RecursiveApplyError } from "../services/recursive-apply.js"
import { storeRecursiveRoutes } from "../services/recursive-route-store.js" import { storeRecursiveRoutes } from "../services/recursive-route-store.js"
import { planRecursiveIdentities } from "../services/recursive-route-identity.js" import { planRecursiveIdentities } from "../services/recursive-route-identity.js"
import { withApplicationMutationLock, withConfigMutationLock } from "../services/config-mutation-lock.js" import { McpError } from "../modules/mcp/security.js"
import { asc, eq } from "drizzle-orm" import { asc, eq } from "drizzle-orm"
import { z } from "zod" import { z } from "zod"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod" import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
@@ -100,7 +101,7 @@ export async function applyRecursiveToServer(
source: ConfigRevisionSource, source: ConfigRevisionSource,
validateExisting?: (rows: ReturnType<typeof parseRecursiveCatalog>) => void | Promise<void>, validateExisting?: (rows: ReturnType<typeof parseRecursiveCatalog>) => void | Promise<void>,
): Promise<{ pushed: number; deleted: number }> { ): Promise<{ pushed: number; deleted: number }> {
return withApplicationMutationLock(() => withConfigMutationLock([server.id], async () => { return withCatalogWriteLock(server, "recursive-routes", async () => {
await storeRecursiveRoutes(server.id, routes, source, true) await storeRecursiveRoutes(server.id, routes, source, true)
const client = MikrotikClient.fromServer(server) const client = MikrotikClient.fromServer(server)
return executeRecursiveApply(client, routes.map(toRouterPayload), async () => { return executeRecursiveApply(client, routes.map(toRouterPayload), async () => {
@@ -116,7 +117,7 @@ export async function applyRecursiveToServer(
await validateExisting?.(parseRecursiveCatalog(observed)) await validateExisting?.(parseRecursiveCatalog(observed))
return observed return observed
}, () => readRecursiveNativeRowsForServer(server)) }, () => readRecursiveNativeRowsForServer(server))
})) })
} }
const RevisionIdParamSchema = z.object({ id: z.string().min(1) }) const RevisionIdParamSchema = z.object({ id: z.string().min(1) })
@@ -158,16 +159,32 @@ const recursiveDefaults: RecursiveRouteDependencies = {
/** Strict observation shared by both transports. REST can persist metadata; /** Strict observation shared by both transports. REST can persist metadata;
* observers opt out. An unavailable source always fails this catalog read. */ * observers opt out. An unavailable source always fails this catalog read. */
export async function readRecursiveCatalogForServer(server: ServerRow, deps: Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved"> = recursiveDefaults, options: { persistObserved?: boolean } = {}) { type RecursiveReadDependencies = Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved">
const read = async () => {
const readWebRecursiveRows = coalesceCatalogReads(readRecursiveNativeRowsForServer)
async function observeRecursiveRoutes(server: ServerRow, deps: RecursiveReadDependencies, persist: boolean) {
const read = async (fresh: boolean) => {
if (!server.enabled) throw new Error("Устройство отключено: каталог маршрутов недоступен") if (!server.enabled) throw new Error("Устройство отключено: каталог маршрутов недоступен")
const observed = await readRecursiveEffectiveProperties(await deps.readRaw(server), (id, property) => deps.readProperty(server, id, property)) const observed = !fresh && persist && deps === recursiveDefaults ? await readWebRecursiveRows(server)
const routes = mergeCachedCountry(parseRecursiveCatalog(observed), await deps.getRoutes(server.id)) : await readRecursiveEffectiveProperties(await deps.readRaw(server), (id, property) => deps.readProperty(server, id, property))
if (options.persistObserved !== false) await deps.saveObserved(server.id, routes) const cached = await deps.getRoutes(server.id)
return { serverId: server.id, routes, live: true, stale: false } const routes = mergeCachedCountry(parseRecursiveCatalog(observed), cached)
const current = !persist || deps === recursiveDefaults && await observationIsCurrent(server.id, "recursive-routes", canonicalRecursiveRoutes(routes), canonicalRecursiveRoutes(cached))
return { routes, cached, current }
} }
return deps === recursiveDefaults && options.persistObserved !== false const save = async (snapshot: Awaited<ReturnType<typeof read>>) => {
? withApplicationMutationLock(() => withConfigMutationLock([server.id], read)) : read() await deps.saveObserved(server.id, snapshot.routes)
return { ...snapshot, cached: await deps.getRoutes(server.id), current: true }
}
if (deps === recursiveDefaults) return readCatalogWithObservedCache(server, read, save)
const snapshot = await read(true)
return snapshot.current ? snapshot : save(snapshot)
}
export async function readRecursiveCatalogForServer(server: ServerRow, deps: RecursiveReadDependencies = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
const { routes } = await observeRecursiveRoutes(server, deps, options.persistObserved !== false)
return { serverId: server.id, routes, live: true, stale: false }
} }
export async function readRecursiveNativeRowsForServer(server: ServerRow) { export async function readRecursiveNativeRowsForServer(server: ServerRow) {
@@ -187,22 +204,18 @@ export async function readRecursiveGatewaysForServer(server: ServerRow, deps: Pi
/** Legacy application read, including its explicit stale fallback. MCP observers /** Legacy application read, including its explicit stale fallback. MCP observers
* share the source/parser while leaving cache and revision history untouched. */ * share the source/parser while leaving cache and revision history untouched. */
export async function readRecursiveRoutesForServer(server: ServerRow, deps: Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved"> = recursiveDefaults, options: { persistObserved?: boolean } = {}) { export async function readRecursiveRoutesForServer(server: ServerRow, deps: RecursiveReadDependencies = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
if (!server.enabled) throw new Error("Устройство отключено: опрос маршрутов недоступен") if (!server.enabled) throw new Error("Устройство отключено: опрос маршрутов недоступен")
const read = async () => { try {
const cached = await deps.getRoutes(server.id) const observed = await observeRecursiveRoutes(server, deps, options.persistObserved !== false)
try { const routes = options.persistObserved === false
const result = await readRecursiveCatalogForServer(server, deps, options) ? planRecursiveIdentities(observed.cached, observed.routes, new Set(), "observed").rows.map((row, index) => ({ ...row, id: row.id || observed.routes[index].id }))
const routes = options.persistObserved === false : observed.cached
? planRecursiveIdentities(cached, result.routes, new Set(), "observed").rows.map((row, index) => ({ ...row, id: row.id || result.routes[index].id })) return { serverId: server.id, routes, live: true, stale: false }
: await deps.getRoutes(server.id) } catch (error) {
return { ...result, routes } if (error instanceof McpError && (error.code === "CONFIGURATION_BUSY" || error.code === "STATE_CONFLICT")) throw error
} catch { return { serverId: server.id, routes: await deps.getRoutes(server.id), live: false, stale: true, error: "Не удалось подтвердить живой каталог; возвращена сохранённая конфигурация" }
return { serverId: server.id, routes: cached, live: false, stale: true, error: "Не удалось подтвердить живой каталог; возвращена сохранённая конфигурация" }
}
} }
return deps === recursiveDefaults && options.persistObserved !== false
? withApplicationMutationLock(() => withConfigMutationLock([server.id], read)) : read()
} }
export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependencies> = {}): FastifyPluginAsyncZod { export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependencies> = {}): FastifyPluginAsyncZod {
@@ -218,6 +231,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
try { try {
return reply.send(await readRecursiveCatalogForServer(server, deps)) return reply.send(await readRecursiveCatalogForServer(server, deps))
} catch (error) { } catch (error) {
if (error instanceof McpError) throw error
return reply.status(503).send({ error: error instanceof Error ? error.message : "Не удалось прочитать каталог маршрутов" }) return reply.status(503).send({ error: error instanceof Error ? error.message : "Не удалось прочитать каталог маршрутов" })
} }
}) })
@@ -276,6 +290,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
return reply.send({ ok: true, serverId, routes: stored, pushedRoutes: result.pushed }) return reply.send({ ok: true, serverId, routes: stored, pushedRoutes: result.pushed })
} catch (err) { } catch (err) {
const receipt = recursiveFailureReceipt(err, result) const receipt = recursiveFailureReceipt(err, result)
if (!receipt && err instanceof McpError) throw err
return reply.status(receipt ? 502 : 500).send({ error: String(err), serverId, ...receipt }) return reply.status(receipt ? 502 : 500).send({ error: String(err), serverId, ...receipt })
} }
}) })
@@ -313,6 +328,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
return reply.send({ ok: true, serverId: server.id, routes: stored, pushedRoutes: result.pushed }) return reply.send({ ok: true, serverId: server.id, routes: stored, pushedRoutes: result.pushed })
} catch (err) { } catch (err) {
const receipt = recursiveFailureReceipt(err, result) const receipt = recursiveFailureReceipt(err, result)
if (!receipt && err instanceof McpError) throw err
return reply.status(receipt ? 502 : 500).send({ error: String(err), serverId: server.id, ...receipt }) return reply.status(receipt ? 502 : 500).send({ error: String(err), serverId: server.id, ...receipt })
} }
}) })
+11
View File
@@ -5,6 +5,7 @@ import { createSchedulerRoutes } from "./scheduler.js"
import type { SchedulerRunReceipt } from "../services/scheduler-recorded-run.js" import type { SchedulerRunReceipt } from "../services/scheduler-recorded-run.js"
import { pauseSchedulerJobsAndWait, resumeSchedulerJobs } from "../services/scheduler-running.js" import { pauseSchedulerJobsAndWait, resumeSchedulerJobs } from "../services/scheduler-running.js"
import { runSchedulerJobNow } from "../services/scheduler.js" import { runSchedulerJobNow } from "../services/scheduler.js"
import { ConfigurationBusyError } from "../services/config-mutation-lock.js"
const receipt: SchedulerRunReceipt = { status: "ok", error: null, result: { v: 1, job: "backups", sampledAt: "2026-10-01T00:00:00Z", due: true, created: 1, failures: 0, pruned: 0 } } const receipt: SchedulerRunReceipt = { status: "ok", error: null, result: { v: 1, job: "backups", sampledAt: "2026-10-01T00:00:00Z", due: true, created: 1, failures: 0, pruned: 0 } }
async function setup(patch: Partial<Parameters<typeof createSchedulerRoutes>[0]> = {}) { async function setup(patch: Partial<Parameters<typeof createSchedulerRoutes>[0]> = {}) {
const app = Fastify(); let calls = 0 const app = Fastify(); let calls = 0
@@ -39,3 +40,13 @@ test("collector or journal rejection remains explicit without a fabricated recei
const { app } = await setup({ run: async () => { throw Error("journal not confirmed; retry may repeat operations") } }) const { app } = await setup({ run: async () => { throw Error("journal not confirmed; retry may repeat operations") } })
try { const response = await app.inject({ method: "POST", url: "/scheduler/jobs/backups/run-now" }); assert.equal(response.statusCode, 500); assert.match(response.json().error, /retry may repeat/); assert.equal(response.json().result, undefined) } finally { await app.close() } try { const response = await app.inject({ method: "POST", url: "/scheduler/jobs/backups/run-now" }); assert.equal(response.statusCode, 500); assert.match(response.json().error, /retry may repeat/); assert.equal(response.json().result, undefined) } finally { await app.close() }
}) })
test("configuration contention is distinguishable from an already running job", async () => {
const busy = new ConfigurationBusyError("server")
const { app } = await setup({ run: async () => { throw busy } })
try {
const response = await app.inject({ method: "POST", url: "/scheduler/jobs/uptime_ping/run-now" })
assert.equal(response.statusCode, 409)
assert.deepEqual(response.json(), { code: "CONFIGURATION_BUSY", error: busy.message })
} finally { await app.close() }
})
+4 -4
View File
@@ -51,11 +51,11 @@ return async (app) => {
return reply.send({ ok: result.status === "ok", result, status, ...(statusError ? { statusError } : {}) }) return reply.send({ ok: result.status === "ok", result, status, ...(statusError ? { statusError } : {}) })
} catch (e) { } catch (e) {
const statusCode = (e as Error & { statusCode?: number }).statusCode const statusCode = (e as Error & { statusCode?: number }).statusCode
if (statusCode === 409) {
const paused = (e as Error & { code?: string }).code === "SCHEDULER_PAUSED"
return reply.status(409).send({ error: paused ? "Планировщик приостановлен для операции с базой" : "Задача уже выполняется" })
}
const msg = e instanceof Error ? e.message : String(e) const msg = e instanceof Error ? e.message : String(e)
if (statusCode === 409) {
const code = (e as Error & { code?: string }).code
return reply.status(409).send({ error: msg, ...(code ? { code } : {}) })
}
return reply.status(500).send({ error: msg }) return reply.status(500).send({ error: msg })
} }
}) })
+25 -9
View File
@@ -106,7 +106,11 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
}) })
app.get("/traffic/servers/:id/live", async (req, reply) => { app.get("/traffic/servers/:id/live", async (req, reply) => {
const p = req.params as { id?: string | number } const p = req.params as { id?: string | number }
const q = req.query as { iface?: string } const q = req.query as { iface?: string; once?: string }
if (q.once === "1" && (typeof q.iface !== "string" || !q.iface.trim() ||
q.iface.length > 128 || q.iface === "__all__" || /[,\x00-\x1f\x7f]/.test(q.iface))) {
return reply.code(400).send({ error: "Укажите один интерфейс для live-измерения" })
}
const readServer = (id: string | number, signal?: AbortSignal) => withDatabaseApiRequest(async () => { const readServer = (id: string | number, signal?: AbortSignal) => withDatabaseApiRequest(async () => {
signal?.throwIfAborted() signal?.throwIfAborted()
const row = await getEnabledServerById(id) const row = await getEnabledServerById(id)
@@ -117,11 +121,30 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
if (!server || !server.enabled) return reply.status(404).send({ error: "Server not found" }) if (!server || !server.enabled) return reply.status(404).send({ error: "Server not found" })
const onlyInterface = q.iface && q.iface !== "__all__" ? q.iface : undefined const onlyInterface = q.iface && q.iface !== "__all__" ? q.iface : undefined
const client = MikrotikClient.fromServer(server)
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
const readSample = (signal: AbortSignal) => readTrafficLiveSample(client, onlyInterface, cache, signal, async () => {
const current = await readServer(server.id, signal)
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Переподключите live-поток")
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
})
const abort = new AbortController() const abort = new AbortController()
const onClose = () => abort.abort() const onClose = () => abort.abort()
registerDatabaseStreamAbort(req, onClose) registerDatabaseStreamAbort(req, onClose)
if (abort.signal.aborted) return reply.code(503).send({ error: "Выполняется операция с базой приложения" }) if (abort.signal.aborted) return reply.code(503).send({ error: "Выполняется операция с базой приложения" })
if (reply.raw.destroyed) return if (reply.raw.destroyed) return
if (q.once === "1") {
reply.raw.once("close", onClose)
try {
const sample = await readSample(abort.signal)
return reply.header("Cache-Control", "no-store").send(sample)
} catch {
if (!reply.raw.destroyed) return reply.code(503).send({ error: "Live-измерение интерфейса недоступно" })
return
} finally {
reply.raw.off("close", onClose)
}
}
reply.raw.on("close", onClose) reply.raw.on("close", onClose)
reply.hijack() reply.hijack()
@@ -144,17 +167,10 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
reply.raw.writeHead(200, sseHeaders) reply.raw.writeHead(200, sseHeaders)
reply.raw.write(":\n\n") reply.raw.write(":\n\n")
const client = MikrotikClient.fromServer(server)
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
try { try {
while (!abort.signal.aborted) { while (!abort.signal.aborted) {
try { try {
const sample = await readTrafficLiveSample(client, onlyInterface, cache, abort.signal, async () => { const sample = await readSample(abort.signal)
const current = await readServer(server.id, abort.signal)
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Live-поток остановлен")
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
})
if (abort.signal.aborted) break if (abort.signal.aborted) break
writeSse(reply.raw, "sample", sample) writeSse(reply.raw, "sample", sample)
} catch (error) { } catch (error) {
+25 -6
View File
@@ -14,10 +14,10 @@ const held = new AsyncLocalStorage<ServerLockCompletion>()
const applicationLease = new AsyncLocalStorage<LockCompletion>() const applicationLease = new AsyncLocalStorage<LockCompletion>()
const collectorLease = new AsyncLocalStorage<LockCompletion>() const collectorLease = new AsyncLocalStorage<LockCompletion>()
const applicationLockKey = "hashtextextended('mm-config:application',0)" const applicationLockKey = "hashtextextended('mm-config:application',0)"
/** Another mutation holds the global configuration lock, or collectors hold it shared while they read routers.
* Same message and 409 as before; the code lets MCP report it instead of a generic device failure. */
export class ConfigurationBusyError extends McpError { export class ConfigurationBusyError extends McpError {
constructor() { super("CONFIGURATION_BUSY", "Глобальная конфигурация изменяется другой операцией", 409) } constructor(scope: "application" | "server" = "application") {
super("CONFIGURATION_BUSY", scope === "server" ? "Конфигурация сервера временно занята другой операцией" : "Глобальная конфигурация временно занята другой операцией", 409)
}
} }
export async function acquireApplicationMutationTransactionLock(client: Pick<PoolClient, "query">): Promise<void> { export async function acquireApplicationMutationTransactionLock(client: Pick<PoolClient, "query">): Promise<void> {
@@ -80,17 +80,36 @@ export async function withApplicationMutationLock<T>(work: () => Promise<T>, opt
/** Collectors coexist with each other but exclude configuration mutation for /** Collectors coexist with each other but exclude configuration mutation for
* the complete native/sample/status operation. This lock grants no authority. * the complete native/sample/status operation. This lock grants no authority.
* Verified operations retain their original exact exclusive client protocol. */ * Verified operations retain their original exact exclusive client protocol. */
export async function withApplicationCollectorLock<T>(work: () => Promise<T>): Promise<T> { export async function withApplicationCollectorLock<T>(work: () => Promise<T>, { waitMs = 5000 }: { waitMs?: number } = {}): Promise<T> {
assertOperationConfigurationLockScope() assertOperationConfigurationLockScope()
if (applicationLease.getStore()?.active || captureOperationConfigurationLockHandoff()) return withApplicationMutationLock(work) if (applicationLease.getStore()?.active || captureOperationConfigurationLockHandoff()) return withApplicationMutationLock(work)
if (collectorLease.getStore()?.active) return work() if (collectorLease.getStore()?.active) return work()
const deadline = performance.now() + waitMs
for (;;) {
let admitted = false
try {
return await tryApplicationCollectorLock(() => {
admitted = true
return work()
})
} catch (error) {
const remaining = deadline - performance.now()
if (admitted || !(error instanceof ConfigurationBusyError) || remaining <= 0) throw error
// Release the failed attempt's connection before waiting for the writer.
await delay(Math.min(250, remaining))
if (performance.now() >= deadline) throw error
}
}
}
async function tryApplicationCollectorLock<T>(work: () => Promise<T>): Promise<T> {
let complete!: () => void let complete!: () => void
const completed = new Promise<void>(resolve => { complete = resolve }) const completed = new Promise<void>(resolve => { complete = resolve })
const client = await pool.connect(), context = { active: true, completed } const client = await pool.connect(), context = { active: true, completed }
let acquired = false, unsafe = false let acquired = false, unsafe = false
try { try {
acquired = (await client.query(`SELECT pg_try_advisory_lock_shared(${applicationLockKey}) AS acquired`)).rows[0].acquired acquired = (await client.query(`SELECT pg_try_advisory_lock_shared(${applicationLockKey}) AS acquired`)).rows[0].acquired
if (!acquired) throw Object.assign(new Error("Глобальная конфигурация изменяется другой операцией"), { statusCode: 409 }) if (!acquired) throw new ConfigurationBusyError()
return await collectorLease.run(context, work) return await collectorLease.run(context, work)
} finally { } finally {
context.active = false context.active = false
@@ -159,7 +178,7 @@ async function runConfigMutationLock<T>(serverIds: number[], work: () => Promise
} }
for (const id of requested) { for (const id of requested) {
const { rows: [row] } = await client.query<{ acquired: boolean }>("SELECT pg_try_advisory_lock(hashtextextended($1,0)) AS acquired", ["mm-config:" + id]) const { rows: [row] } = await client.query<{ acquired: boolean }>("SELECT pg_try_advisory_lock(hashtextextended($1,0)) AS acquired", ["mm-config:" + id])
if (!row.acquired) throw Object.assign(new Error("Конфигурация сервера изменяется другой операцией"), { statusCode: 409 }) if (!row.acquired) throw new ConfigurationBusyError("server")
acquired.push(id) acquired.push(id)
signal.throwIfAborted() signal.throwIfAborted()
} }
@@ -0,0 +1,55 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import type { IxBondCandidate, IxBondEdit, IxSavedBond } from "@mmapp/contracts/internet-exchange"
import { ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
import { bondCandidates, resolveBondMembers } from "./internet-exchange-bonds.js"
const owner = "a213a2c7-53cd-4325-8e43-e2d953cd761b"
const other = "5c1364bd-6147-46ea-b726-273a7e933302"
const client = "5a7fa65a-f94f-475a-96cd-a2ece0ed77ce"
const primary: IxBondCandidate = { segmentId: owner, appliedRevision: 3, serverId: 5, segmentName: "eu",
interfaceName: "wg-vps", name: "alpha", kind: "wireguard", probe: "10.255.0.1", address: "10.255.0.2", endpoint: "192.0.2.1", destinations: ["0.0.0.0/0"] }
const backup: IxBondCandidate = { ...primary, segmentId: other, segmentName: "asia", clientId: client,
serverId: 6, kind: "gre-ipsec", interfaceName: "gre-vps", probe: "10.255.0.5", address: "10.255.0.6" }
const edit: IxBondEdit = { name: "vps", mode: "weighted", directCidrs: [], revision: 0,
members: [primary, backup].map(({ segmentId, appliedRevision, serverId, interfaceName }, i) =>
({ segmentId, appliedRevision, serverId, interfaceName, weight: i ? 1 : 3 })) }
test("cross-segment members retain order, declared VPS identity and revision", () => {
const { members, clientId } = resolveBondMembers(edit, [backup, primary], [], owner)
assert.deepEqual(members, [primary, backup])
assert.equal(clientId, client)
const saved: IxSavedBond = { ...edit, id: other, ownerSegmentId: owner, revision: 1, clientId }
assert.throws(() => resolveBondMembers(edit, [primary, backup], [saved], owner), /уже входит/)
assert.equal(resolveBondMembers(saved, [primary, backup], [saved], owner, saved).clientId, client)
})
test("reject stale, revoked, foreign-client and conflicting routing paths", () => {
const invalid: Array<[IxBondCandidate, RegExp]> = [
[{ ...backup, appliedRevision: 4 }, /изменилось/],
[{ ...backup, destinations: ["198.51.100.0/24"] }, /назначения/],
[{ ...backup, address: primary.probe }, /внутренние адреса/],
]
for (const [candidate, reason] of invalid) {
assert.throws(() => resolveBondMembers(edit, [primary, candidate], [], owner), reason)
}
assert.throws(() => resolveBondMembers(edit, [primary], [], owner), /недоступно/)
assert.throws(() => resolveBondMembers(edit, [{ ...primary, clientId: owner }, backup], [], owner), /разными VPS/)
assert.throws(() => resolveBondMembers(edit, [primary, backup], [], client), /текущего сегмента/)
})
test("existing static WireGuard exports keep their applied prefixes; external GRE and BGP remain independent", () => {
const config = ixSegmentConfigurationSchema.parse({ name: "legacy", sites: [{ serverId: 5, autonomousSystem: 64512,
routerId: "192.0.2.1", interfaces: [
{ kind: "wireguard", name: "wg-static", provisionWireguard: { listenPort: 31820, hubEndpoint: primary.endpoint,
localAddress: primary.probe + "/30", peerAddress: primary.address, peerPublicKey: Buffer.alloc(32, 3).toString("base64") } },
{ kind: "gre-ipsec", name: "gre-manual", localEndpoint: primary.endpoint, endpoint: "198.51.100.8", prefixes: ["10.7.0.0/24"] },
] }] })
const [candidate] = bondCandidates(owner, 7, config)
assert.deepEqual(bondCandidates(owner, 7, config).map(c => c.interfaceName), ["wg-static"])
assert.deepEqual(candidate.destinations, ["10.7.0.0/24"])
assert.equal(candidate.clientId, undefined)
config.sites[0].neighbors.push({ id: "bgp", binding: "wg-static", type: "member", remoteAs: 64513,
address: primary.address, localAddress: primary.probe, prefixes: [], exportPrefixes: [], rules: [], limit: 10 })
assert.deepEqual(bondCandidates(owner, 7, config), [])
})
@@ -0,0 +1,176 @@
import { randomUUID } from "node:crypto"
import { isIP } from "node:net"
import type { PoolClient } from "pg"
import {
ixBondBundleSchema, ixSavedBondSchema, ixSegmentConfigurationSchema, type IxBondCandidate,
type IxBondEdit, type IxSavedBond, type IxConfiguration, type IxBondBundle,
} from "@mmapp/contracts/internet-exchange"
import { pool } from "../db/index.js"
import { audit } from "../modules/mcp/store.js"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
import { ixLegacyWireguardRoutes, ixLinuxBindingKind, ixLinuxInterfaceName } from "./internet-exchange-client.js"
import { readIxLinuxClient, verifyIxExistingTransport } from "./internet-exchange-execution.js"
import { IxConflict } from "./internet-exchange-plan.js"
import { ixReservedTunnelBindings, readIxSegment } from "./internet-exchange-store.js"
import { admitPartitionWriter } from "./partition-write-transaction.js"
type Query = Pick<PoolClient, "query">
type MemberRef = IxBondEdit["members"][number]
const visible = "(s.configuration->>'deleted') IS DISTINCT FROM 'true'"
const key = (m: Pick<MemberRef, "segmentId" | "serverId" | "interfaceName">) => [m.segmentId, m.serverId, m.interfaceName].join("/")
export function bondCandidates(segmentId: string, appliedRevision: number, config: IxConfiguration): IxBondCandidate[] {
return config.sites.flatMap(site => site.interfaces.flatMap(binding => {
const kind = ixLinuxBindingKind(binding)
const linux = binding.linux
const tunnel = binding.provisionWireguard ?? binding.provisionGre
if (!kind || linux?.enabled === false || !tunnel || binding.peerServerId) return []
if (!linux && (kind !== "wireguard" || site.neighbors.some(peer => peer.binding === binding.name))) return []
const family = isIP(tunnel.peerAddress)
const routes = linux ? linux.destinations : ixLegacyWireguardRoutes(config, binding)
const destinations = linux?.exit ? [family === 6 ? "::/0" : "0.0.0.0/0"]
: [...new Set(routes.map(canonicalBgpPolicyPrefix))].sort()
if (!linux && (!destinations.length || destinations.length > 64 || destinations.some(cidr => isIP(cidr.split("/")[0]) !== family))) return []
return [{
segmentId, appliedRevision, segmentName: config.name, serverId: site.serverId, interfaceName: binding.name,
name: linux?.name ?? binding.name, clientId: linux?.clientId, kind, address: tunnel.peerAddress, probe: tunnel.localAddress.split("/")[0],
endpoint: (binding.provisionWireguard?.hubEndpoint ?? binding.localEndpoint)!,
destinations,
}]
}))
}
async function candidates(sql: Query, ids?: string[], refs: MemberRef[] = []) {
const { rows } = await sql.query(`SELECT s.id,s.applied_revision,r.configuration FROM ix_segments s
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
WHERE ${visible} AND ($1::uuid[] IS NULL OR s.id=ANY($1)) ORDER BY s.name,s.id`, [ids ?? null])
return rows.flatMap(row => {
const config = ixSegmentConfigurationSchema.parse(row.configuration)
const result = bondCandidates(row.id, row.applied_revision, config)
for (const ref of refs) {
const path = ref.existing
if (!path || ref.segmentId !== row.id) continue
const site = config.sites.find(s => s.serverId === ref.serverId)
const binding = site?.interfaces.find(b => b.name === ref.interfaceName)
if (!site || binding && (binding.peerServerId || binding.provisionTransit || binding.provisionWireguard || binding.provisionGre || binding.linux ||
binding.kind !== path.kind) || result.some(c => key(c) === key(ref)) || site.neighbors.some(p => p.binding === ref.interfaceName)) {
throw new IxConflict("Интерфейс занят клиентом, BGP либо принадлежит другому узлу: " + ref.interfaceName)
}
result.push({ ...ref, ...path, segmentName: config.name, appliedRevision: row.applied_revision, name: path.linuxInterface,
destinations: [...new Set(path.destinations.map(canonicalBgpPolicyPrefix))].sort() })
}
return result
})
}
export async function inspectIxBondImports(ownerId: string, edit: IxBondEdit) {
if (!edit.members.some(m => m.existing)) return
const [available, groups] = await Promise.all([candidates(pool, [...new Set(edit.members.map(m => m.segmentId))], edit.members), savedGroups(pool)])
resolveBondMembers(edit, available, groups, ownerId, groups.find(g => g.id === edit.id && g.ownerSegmentId === ownerId))
for (const m of edit.members) if (m.existing) await verifyIxExistingTransport(m.segmentId, m.serverId, m.interfaceName, m.existing)
}
async function savedGroups(sql: Query, ownerId?: string): Promise<IxSavedBond[]> {
const { rows } = await sql.query(`SELECT item FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') item
WHERE ${visible} AND ($1::uuid IS NULL OR s.id=$1) ORDER BY s.id`, [ownerId ?? null])
return rows.map(row => ixSavedBondSchema.parse(row.item))
}
export async function ixBondCatalog() {
const [groups, available] = await Promise.all([savedGroups(pool), candidates(pool)])
return { groups, candidates: available }
}
export function resolveBondMembers(edit: IxBondEdit, available: IxBondCandidate[], groups: IxSavedBond[], ownerId: string, previous?: IxSavedBond) {
const routerInterface = (m: MemberRef) => m.serverId + "/" + m.interfaceName
const occupied = new Set(groups.filter(g => g.id !== previous?.id).flatMap(g => g.members.map(routerInterface)))
const owned = new Map(available.map(m => [key(m), m]))
const addresses = new Set<string>()
const linuxNames = new Set<string>()
const members = edit.members.map(member => {
const label = member.interfaceName
const found = owned.get(key(member))
if (!found || found.appliedRevision !== member.appliedRevision) throw new IxConflict("Подключение изменилось или недоступно: " + label)
if (occupied.has(routerInterface(member))) throw new IxConflict("Интерфейс уже входит в группу: " + label)
occupied.add(routerInterface(member))
const linuxName = found.existing?.linuxInterface ?? ixLinuxInterfaceName(found.kind === "wireguard" ? "ixw" : "ixg", found.serverId, { name: found.interfaceName })
if (linuxNames.has(linuxName)) throw new IxConflict("Имя интерфейса на VPS повторяется: " + linuxName)
linuxNames.add(linuxName)
for (const address of [found.address, found.probe]) {
const host = canonicalBgpPolicyPrefix(address + (isIP(address) === 6 ? "/128" : "/32"))
if (addresses.has(host)) throw new IxConflict("Назначьте разные внутренние адреса участникам группы: " + address)
addresses.add(host)
}
return found
})
const first = members[0]
if (!members.some(m => m.segmentId === ownerId)) throw new IxConflict("Выберите подключение из текущего сегмента")
if (!first?.destinations.length || members.some(m => isIP(m.address) !== isIP(first.address) ||
JSON.stringify(m.destinations) !== JSON.stringify(first.destinations))) {
throw new IxConflict("Участникам нужны одинаковые непустые назначения и одно семейство адресов")
}
const identities = new Set(members.flatMap(m => m.clientId ? [m.clientId] : []))
if (previous) identities.add(previous.clientId)
if (identities.size > 1) throw new IxConflict("Выбранные подключения зарегистрированы за разными VPS")
return { members, clientId: [...identities][0] ?? randomUUID() }
}
export async function changeIxBond(ownerId: string, edit: IxBondEdit | { id: string; revision: number }, actor: string) {
const sql = await pool.connect()
try {
await sql.query("BEGIN")
await admitPartitionWriter(sql)
// A member can belong to only one group, including groups owned by another segment.
await sql.query("SELECT pg_advisory_xact_lock(hashtextextended('ix-linux-bonds',0))")
if (!await readIxSegment(ownerId, sql)) throw new IxConflict("Сегмент IX не найден", 404)
const groups = await savedGroups(sql)
const previous = groups.find(group => group.ownerSegmentId === ownerId && group.id === edit.id)
if (edit.id && !previous) throw new IxConflict("Группа не найдена", 404)
if ((previous?.revision ?? 0) !== edit.revision) throw new IxConflict("Группа изменилась. Обновите данные")
let next: IxSavedBond | null = null
if ("members" in edit) {
const available = await candidates(sql, [...new Set(edit.members.map(m => m.segmentId))], edit.members)
const { clientId } = resolveBondMembers(edit, available, groups, ownerId, previous)
for (const m of edit.members) if (m.existing && (await ixReservedTunnelBindings(m.serverId, m.segmentId, sql)).some(b => b.name === m.interfaceName)) {
throw new IxConflict("Интерфейс уже закреплён за другим сегментом: " + m.interfaceName)
}
next = ixSavedBondSchema.parse({ ...edit, id: previous?.id ?? randomUUID(), ownerSegmentId: ownerId, clientId,
revision: edit.revision + 1, directCidrs: [...new Set(edit.directCidrs.map(canonicalBgpPolicyPrefix))] })
}
const owned = groups.filter(group => group.ownerSegmentId === ownerId && group.id !== edit.id)
if (next) owned.push(next)
const result = await sql.query(`UPDATE ix_segments s SET configuration=jsonb_set(configuration,'{linuxBonds}',$2::jsonb)
WHERE s.id=$1 AND ${visible}`, [ownerId, JSON.stringify(owned)])
if (result.rowCount !== 1) throw new IxConflict("Сегмент IX недоступен")
await audit(sql, actor, next ? "ix.bond.saved" : "ix.bond.removed", null, { ownerId, id: next?.id ?? edit.id, revision: next?.revision ?? edit.revision })
await sql.query("COMMIT")
return next
} catch (error) {
await sql.query("ROLLBACK").catch(() => {})
throw error
} finally { sql.release() }
}
export async function exportIxBond(ownerId: string, id: string, revision: number, authorize: () => Promise<unknown>): Promise<IxBondBundle> {
const group = (await savedGroups(pool, ownerId)).find(g => g.id === id)
if (!group || group.revision !== revision) throw new IxConflict("Группа отсутствует или её ревизия изменилась")
const segments = [...new Set(group.members.map(m => m.segmentId))]
const { members } = resolveBondMembers(group, await candidates(pool, segments, group.members), [], ownerId, group)
const result = []
for (const [index, m] of members.entries()) {
await authorize()
const segment = await readIxSegment(m.segmentId)
if (!segment || segment.appliedRevision !== m.appliedRevision) throw new IxConflict("Изменилась площадка " + m.segmentName)
const access = m.existing ? { filename: m.existing.linuxInterface,
hubPublicKey: await verifyIxExistingTransport(m.segmentId, m.serverId, m.interfaceName, m.existing) }
: await readIxLinuxClient(segment, m.serverId, m.interfaceName)
result.push({ kind: m.kind, interfaceName: m.existing ? m.existing.linuxInterface : access.filename.replace(/\.conf$/, ""), address: m.address, probe: m.probe,
endpoint: m.endpoint, weight: group.mode === "weighted" ? group.members[index].weight : 1,
...(m.kind === "wireguard" && { peerPublicKey: access.hubPublicKey }) })
}
const bundle = ixBondBundleSchema.parse({ version: 1, id, revision, name: group.name, clientId: group.clientId, mode: group.mode,
destinations: members[0].destinations, directCidrs: group.directCidrs, members: result })
await authorize()
return bundle
}
@@ -0,0 +1,171 @@
import { createHash } from "node:crypto"
import { isIP } from "node:net"
import type { IxConfiguration, IxSite } from "@mmapp/contracts/internet-exchange"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
import { IxConflict } from "./internet-exchange-plan.js"
type Binding = IxSite["interfaces"][number]
export function ixLinuxBindingKind(binding: Binding) {
if (binding.kind === "wireguard" && binding.provisionWireguard?.hubEndpoint) return "wireguard"
if (binding.kind === "gre-ipsec" && binding.localEndpoint && binding.endpoint) return "gre-ipsec"
return null
}
export function ixLegacyWireguardRoutes(configuration: IxConfiguration, binding: Binding) {
return configuration.sites.flatMap(site => site.interfaces
.filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes))
}
export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, binding: Pick<Binding, "name">) {
return prefix + createHash("sha256").update(JSON.stringify([serverId, binding.name])).digest("hex").slice(0, 12)
}
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[], privateKey = "<локальный_приватный_ключ>", transportOnly = false) {
const config = binding.provisionWireguard
if (binding.kind !== "wireguard" || !config?.hubEndpoint || !/^[A-Za-z0-9+/]{43}=$/.test(hubPublicKey)) {
throw new IxConflict("Для Linux нужны публичный ключ узла и заданный внешний адрес IX")
}
const serverAddress = config.localAddress.split("/")[0]
const family = isIP(serverAddress)
const address = (value: string) => value + (family === 4 ? "/32" : "/128")
const endpoint = isIP(config.hubEndpoint) === 6 ? "[" + config.hubEndpoint + "]" : config.hubEndpoint
return [
"[Interface]",
"Address = " + address(config.peerAddress),
"PrivateKey = " + privateKey,
binding.linux && !transportOnly ? "Table = auto" : "Table = off",
...(!transportOnly && binding.linux?.exit && binding.linux.peerEndpoint && isIP(binding.linux.peerEndpoint) === family ? [
"PostUp = ip -" + family + " rule add pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main",
"PreDown = ip -" + family + " rule del pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main",
] : []),
"",
"[Peer]",
"PublicKey = " + hubPublicKey,
"Endpoint = " + endpoint + ":" + config.listenPort,
"AllowedIPs = " + [...new Set([address(serverAddress), ...routes.map(canonicalBgpPolicyPrefix)])].join(", "),
"PersistentKeepalive = 25",
"",
].join("\n")
}
export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }, credential?: string, transportOnly = false) {
const hub = binding.localEndpoint
const client = binding.endpoint
if (binding.kind !== "gre-ipsec" || !hub || !client || isIP(hub) !== 4 || isIP(client) !== 4 || hub === client) {
throw new IxConflict("Для Linux GRE/IPsec нужны два разных внешних IPv4-адреса")
}
const id = ixLinuxInterfaceName("ixg", serverId, binding)
const hostMask = bgp && isIP(bgp.address) === 6 ? "/128" : "/32"
const tunnel = binding.provisionGre
const family = tunnel ? isIP(tunnel.peerAddress) : 4
const protocol = "ip -" + family
const table = 30000 + parseInt(id.slice(-4), 16)
const management = 12000 + 2 * parseInt(id.slice(-3), 16)
const managementRules = [
["ip -4", "to " + hub + "/32 lookup main"],
["ip -4", "from " + client + "/32 lookup main"],
...(family === 6 && binding.linux?.exit ? [["ip -6", "ipproto tcp sport 22 lookup main"]] : []),
]
const greParameters = id + " mode gre local " + client + " remote " + hub
const common = [
"swanctl --load-all",
"swanctl --initiate --child " + id + " --timeout 20",
"ip tunnel add " + greParameters,
]
const addressCommand = tunnel && "ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id
const transportSetup = transportOnly && tunnel && [
'conf="$(dirname -- "$0")/' + id + '.conf"',
'unit=/etc/systemd/system/ix-gre-' + id + '.service',
'profile=/etc/swanctl/conf.d/' + id + '.conf',
'if [ ! -r "$conf" ]; then echo "Положите ' + id + '.conf рядом со скриптом."; exit 1; fi',
'candidate=$(mktemp)',
'trap \'rm -f "$candidate"\' EXIT',
'cat >"$candidate" <<\'IX_GRE_UNIT\'',
"[Unit]", "Description=IX Client GRE/IPsec " + id, "Wants=network-online.target", "After=network-online.target strongswan.service",
"Requires=strongswan.service", "[Service]", "Type=oneshot", "RemainAfterExit=yes",
"ExecStartPre=/usr/sbin/swanctl --load-all",
"ExecStart=/bin/sh -ec '/usr/sbin/ip tunnel add " + greParameters + '; trap "/usr/sbin/ip link del dev ' + id +
'" EXIT; /usr/sbin/' + addressCommand + "; /usr/sbin/ip link set " + id + " up; trap - EXIT'",
"ExecStop=/usr/sbin/ip link del dev " + id,
"[Install]", "WantedBy=multi-user.target", "IX_GRE_UNIT",
'if [ -e "$unit" ] && ! cmp -s "$candidate" "$unit"; then echo "Служба уже принадлежит другой конфигурации."; exit 1; fi',
'if [ -e "$profile" ] && ! cmp -s "$conf" "$profile"; then echo "Профиль strongSwan отличается от существующего."; exit 1; fi',
'if [ ! -e "$unit" ] && ip link show dev ' + id + ' >/dev/null 2>&1; then echo "Интерфейс уже существует."; exit 1; fi',
'install -d -m 0700 /etc/swanctl/conf.d',
'if [ ! -e "$profile" ]; then install -m 0600 "$conf" "$profile"; fi',
'install -m 0644 "$candidate" "$unit"',
"systemctl daemon-reload", "systemctl enable --now ix-gre-" + id + ".service",
].join("\n")
return {
filename: id + ".conf",
template: [
...(tunnel ? [] : ["# Сверьте предложения и идентификаторы IKE с профилем узла IX."]),
"connections {",
" " + id + " {",
" version = 2",
" local_addrs = " + client,
" remote_addrs = " + hub,
" proposals = aes256-sha256-modp2048",
" mobike = no",
" local {",
" auth = psk",
" id = " + client,
" }",
" remote {",
" auth = psk",
" id = " + hub,
" }",
" children {",
" " + id + " {",
" local_ts = " + client + "/32[47]",
" remote_ts = " + hub + "/32[47]",
" mode = transport",
" esp_proposals = aes256-sha256-modp2048",
" start_action = trap",
" }",
" }",
" }",
"}",
"secrets {",
" ike-" + id + " {",
" id-1 = " + client,
" id-2 = " + hub,
' secret = "' + (credential ?? "<PSK этого клиента>") + '"',
" }",
"}",
"",
].join("\n"),
setup: transportSetup || (tunnel ? [
'conf="$(dirname -- "$0")/' + id + '.conf"',
'if [ ! -r "$conf" ]; then echo "Положите файл ' + id + '.conf рядом со скриптом" >&2; exit 1; fi',
'if ip link show dev ' + id + ' >/dev/null 2>&1; then echo "GRE уже поднят" >&2; exit 1; fi',
'install -d -m 0700 /etc/swanctl/conf.d',
'install -m 0600 "$conf" /etc/swanctl/conf.d/' + id + '.conf',
"cleanup() {",
" " + protocol + " rule del pref " + (management + 1) + " lookup " + table + " 2>/dev/null || :",
" ip link del dev " + id + " 2>/dev/null || :",
...managementRules.map(([ip, selector]) => " " + ip + " rule del pref " + management + " " + selector + " 2>/dev/null || :"),
" swanctl --terminate --ike " + id + " --timeout 5 >/dev/null 2>&1 || :",
"}",
"trap cleanup 0",
...managementRules.map(([ip, selector]) => ip + " rule add pref " + management + " " + selector),
...common,
addressCommand!,
"ip link set " + id + " up",
...[...new Set([
tunnel.localAddress.split("/")[0] + (family === 4 ? "/32" : "/128"),
...(binding.linux?.destinations ?? []).map(canonicalBgpPolicyPrefix),
...(bgp && isIP(bgp.localAddress) === family ? [bgp.localAddress + hostMask] : []),
...(binding.linux?.exit ? ["default"] : []),
])].map(prefix => protocol + " route replace " + prefix + " dev " + id + " src " + tunnel.peerAddress + " table " + table),
protocol + " rule add pref " + (management + 1) + " lookup " + table,
"trap - 0",
] : [
...common,
bgp ? "ip address add " + bgp.address + hostMask + " dev " + id : "# Назначьте согласованный адрес Linux внутри туннеля.",
"ip link set " + id + " up",
...(bgp ? ["ip route add " + bgp.localAddress + hostMask + " dev " + id + " src " + bgp.address] : []),
]).join("\n"),
}
}
@@ -0,0 +1,125 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import type { IxRouterObject } from "@mmapp/contracts/internet-exchange"
import { planIxNative } from "./internet-exchange-execution.js"
import { ixNamespace } from "./internet-exchange-plan.js"
const id = "aaaaaaaa-1111-4222-8333-123456789abc"
const name = ixNamespace(id)
const vrf: IxRouterObject = {
serverId: 17, path: "/ip/vrf", fields: { name, comment: name + ":vrf", interfaces: "wg-ix" },
}
const route: IxRouterObject = {
serverId: 17, path: "/ip/route", fields: { comment: name + ":exit-4-0", "routing-table": name, "dst-address": "0.0.0.0/0", gateway: "192.0.2.1@" + name },
}
const device = (rows: Record<string, Array<Record<string, string>>>) => [{ serverId: 17, source: "", rows }]
test("managed MSS rules are backfilled and removed without adopting a hand-written rule", () => {
const path = "/ip/firewall/mangle"
const from = { serverId: 17, path, fields: { comment: name + ":linux-mss-from-il-wg", action: "change-mss",
chain: "prerouting", "in-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
const to = { serverId: 17, path, fields: { comment: name + ":linux-mss-to-il-wg", action: "change-mss",
chain: "postrouting", "out-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
const manual = { ...to.fields, comment: "manual MSS", ".id": "*A" }
const fromRow = { ...from.fields, ".id": "*B" }
const toRow = { ...to.fields, ".id": "*C" }
const desired = [from, to]
const live = (rows: Array<Record<string, string>>) => device({ [path]: rows })
assert.deepEqual(planIxNative(id, desired, desired, live([manual])).map(task => [task.fields, task.placeBefore]),
[[from.fields, "*A"], [to.fields, "*A"]])
assert.deepEqual(planIxNative(id, desired, desired, live([fromRow, manual])).map(task => task.fields), [to.fields])
assert.deepEqual(planIxNative(id, desired, desired, live([fromRow, toRow, manual])), [])
assert.deepEqual(planIxNative(id, [], desired, live([fromRow, toRow, manual])).map(task => task.rosId), ["*C", "*B"])
assert.throws(() => planIxNative(id, desired, [], live([fromRow, manual])), /незавершённой операции/)
assert.throws(() => planIxNative(id, desired, desired, live([{ ...fromRow, "new-mss": "1460" }, toRow])), /изменён вне операции/)
})
test("a new VRF is inserted before main and no foreign route is altered", () => {
const changes = planIxNative(id, [vrf, route], [], device({
"/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }],
"/ip/route": [{ ".id": "*B", "routing-table": "main", "dst-address": "0.0.0.0/0", gateway: "203.0.113.1" }],
}))
assert.deepEqual(changes.map(task => ({ path: task.path, position: task.placeBefore, id: task.rosId })),
[{ path: "/ip/vrf", position: "*A", id: undefined }, { path: "/ip/route", position: undefined, id: undefined }])
})
test("managed changes update one exact ID and never adopt unknown objects after an interrupted job", () => {
const state = device({ "/ip/route": [{ ".id": "*B", ...route.fields }] })
const next = { ...route, fields: { ...route.fields, gateway: "192.0.2.2@" + name } }
const [task] = planIxNative(id, [next], [route], state)
assert.equal(task.rosId, "*B")
assert.deepEqual(task.fields, { gateway: "192.0.2.2@" + name })
assert.throws(() => planIxNative(id, [next], [], state), /незавершённой операции/)
assert.throws(() => planIxNative(id, [next], [route], device({ "/ip/route": [{ ".id": "*B", ...next.fields }] })), /изменён вне операции/)
const resumed = planIxNative(id, [next, vrf], [route], device({
"/ip/route": [{ ".id": "*B", ...next.fields }],
"/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }],
}), true)
assert.deepEqual(resumed.map(task => task.path), ["/ip/vrf"])
})
test("revocation disables the owned client tunnel before withdrawing rules and deleting its native object", () => {
const tunnel = { serverId: 17, path: "/interface/gre", fields: {
name: "il-client", comment: name + ":gre-il-client", disabled: "false",
} }
const changes = planIxNative(id, [], [tunnel, route], device({
[tunnel.path]: [{ ".id": "*A", ...tunnel.fields }],
[route.path]: [{ ".id": "*B", ...route.fields }],
}))
assert.deepEqual(changes.map(task => [task.rosId, task.fields, task.before?.disabled]), [
["*A", { disabled: "true" }, "false"],
["*B", undefined, undefined],
["*A", undefined, "true"],
])
})
test("a foreign route in the IX table and implicit native field removal are refused", () => {
assert.throws(() => planIxNative(id, [route], [], device({
"/ip/route": [{ ".id": "*B", "routing-table": name, "dst-address": "192.0.2.0/24" }],
})), /пересекается с существующей/)
const { gateway: _gateway, ...fields } = route.fields
assert.throws(() => planIxNative(id, [{ ...route, fields }], [route], device({ "/ip/route": [{ ".id": "*B", ...route.fields }] })), /неявно сбросить/)
})
test("IX does not take a main-table service address from another route", () => {
const resolver = { ...route, fields: { ...route.fields, comment: name + ":bgp-resolve-test", "routing-table": "main", "dst-address": "198.18.0.101/32" } }
const occupied = { ".id": "*B", "routing-table": "main", "dst-address": "198.18.0.101/32", dynamic: "true" }
assert.throws(() => planIxNative(id, [resolver], [], device({ "/ip/route": [occupied] })), /уже занят/)
})
test("RouterOS REST host matches allow only the equivalent explicit host length", () => {
for (const [address, hostLength, wider] of [["192.0.2.1", "32", "24"], ["2001:db8::1", "128", "64"]]) {
const rule = { ...route, path: "/ip/firewall/filter", fields: { comment: name + ":host", "src-address": address + "/" + hostLength } }
const rows = (source: string) => device({ [rule.path]: [{ ".id": "*B", ...rule.fields, "src-address": source }] })
assert.deepEqual(planIxNative(id, [rule], [rule], rows(address)), [])
assert.throws(() => planIxNative(id, [rule], [rule], rows(address + "/" + wider)), /изменён вне операции/)
}
})
test("RouterOS REST encodes an enabled blackhole route as a present empty flag", () => {
const fields = { comment: name + ":default-discard-4", "routing-table": name, "dst-address": "0.0.0.0/0", blackhole: "yes" }
const discard = { ...route, fields }
const { blackhole: _blackhole, ...unflagged } = fields
const observed = (fields: Record<string, string>) => device({ "/ip/route": [{ ".id": "*B", ...fields }] })
assert.deepEqual(planIxNative(id, [discard], [discard], observed({ ...fields, blackhole: "" })), [])
assert.throws(() => planIxNative(id, [discard], [discard], observed(unflagged)), /изменён вне операции/)
assert.throws(() => planIxNative(id, [discard], [discard], observed({ ...fields, blackhole: "false" })), /изменён вне операции/)
})
test("the complete member filter can be added to a legacy applied segment", () => {
const path = "/ip/firewall/filter"
const object = (suffix: string, fields: Record<string, string>) => ({
serverId: 17, path, fields: { comment: name + ":" + suffix, chain: "forward", ...fields },
})
const boundary = object("deny-outside-4", { action: "drop", "in-interface": name })
const allow = object("egress-allow-4", { action: "accept", "in-interface": name, "out-interface-list": name })
const deny = object("egress-deny-4", { action: "drop", "out-interface-list": name })
const objects = [allow, boundary, deny]
const legacy = { ".id": "*B", ...boundary.fields }
assert.deepEqual(planIxNative(id, objects, objects, device({ [path]: [legacy] })).map(task => [task.fields, task.placeBefore]),
[[allow.fields, "*B"], [deny.fields, "*B"]])
assert.throws(() => planIxNative(id, objects, objects, device({ [path]: [{ ".id": "*C", ...allow.fields }, legacy] })),
/предыдущей ревизии IX исчез/)
})
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,180 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { ixSegmentConfigurationSchema, type IxConfiguration } from "@mmapp/contracts/internet-exchange"
import { compileIxConfiguration, ixClientRoutingTable, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
const id = "aaaaaaaa-1111-4222-8333-123456789abc"
const table = ixNamespace(id)
const fixture = (): IxConfiguration => ixSegmentConfigurationSchema.parse({
name: "compute",
sites: [{
serverId: 17, autonomousSystem: 64512, routerId: "192.0.2.17",
interfaces: [{ name: "wg-eu", kind: "wireguard" }, { name: "wg-arn", kind: "wireguard", peerServerId: 1 },
{ name: "uplink", kind: "uplink", natIpv4: true }, { name: "wg-feed", kind: "wireguard" }],
groups: [
{ id: "eu", gateway: "198.18.0.1", primary: { interface: "wg-eu", nextHop: "10.0.1.2", probe: "192.0.2.101" },
backup: { interface: "wg-arn", nextHop: "10.0.2.2", probe: "192.0.2.102" } },
{ id: "exit", gateway: "198.18.0.2", primary: { interface: "uplink", nextHop: "10.0.3.2", probe: "192.0.2.103" } },
],
exits: ["exit"],
neighbors: [{ id: "evo", type: "public-feed", binding: "wg-feed", address: "10.0.4.2", localAddress: "10.0.4.1", remoteAs: 64513,
rules: [{ community: "65000:120", group: "eu" }] }],
}],
})
test("managed clients get their own return path and fail closed if both exit probes are lost", () => {
const value = fixture(), site = value.sites[0]
site.groups.push({ id: "direct", gateway: "198.18.0.10", onFailure: "block",
primary: { interface: "ether1", nextHop: "192.0.2.1", probe: "203.0.113.101", viaMain: true },
backup: { interface: "ether2", nextHop: "192.0.2.2", probe: "203.0.113.102", viaMain: true } })
site.interfaces.push({ name: "linux-wg", kind: "wireguard", prefixes: [],
linux: { name: "vps", enabled: true, exit: "direct", destinations: ["10.80.0.0/16"] },
provisionWireguard: { peerPublicKey: "A".repeat(43) + "=", listenPort: 51900,
localAddress: "10.254.1.1/30", peerAddress: "10.254.1.2", hubEndpoint: "192.0.2.10" } })
const objects = compileIxConfiguration(id, value)
const clamp = objects.findIndex(object => object.fields.comment === table + ":linux-mss-from-linux-wg")
assert.ok(clamp >= 0 && clamp < objects.findIndex(object => object.fields.comment === table + ":linux-linux-wg-route"))
const clientTable = ixClientRoutingTable(table, "linux-wg")
const defaults = objects.filter(object => object.fields["routing-table"] === clientTable)
assert.deepEqual(defaults.map(object => object.fields.distance), ["10", "11", "254"])
assert.equal(defaults.at(-1)?.fields.blackhole, "yes")
assert.ok(objects.some(object => object.path === "/ip/firewall/raw" && object.fields["in-interface"] === "linux-wg" &&
object.fields["src-address-list"] === "!" + clientTable + "-src"))
assert.ok(objects.some(object => object.fields["routing-table"] === "main" &&
object.fields["dst-address"] === "10.254.1.2/32" && object.fields.gateway === "10.254.1.2%linux-wg@" + table))
assert.ok(objects.some(object => object.fields["routing-table"] === table &&
object.fields["dst-address"] === "10.80.0.0/16" && object.fields.blackhole === "yes"))
assert.ok(objects.every(object => object.path !== "/ip/vrf" || !object.fields.interfaces.includes("ether1")))
})
test("managed Linux tunnels clamp TCP SYN in both directions before routing marks can end prerouting", () => {
const value = fixture(), site = value.sites[0]
site.interfaces.push(
{ name: "linux-wg", kind: "wireguard", prefixes: [], linux: { name: "vps", enabled: true, destinations: [] },
provisionWireguard: { localAddress: "10.254.0.1/30", peerAddress: "10.254.0.2", listenPort: 51820, peerPublicKey: "A".repeat(43) + "=" } },
{ name: "linux-gre", kind: "gre-ipsec", prefixes: [], endpoint: "192.0.2.90", localEndpoint: "192.0.2.17",
linux: { name: "vps", enabled: false, destinations: [] },
provisionGre: { localAddress: "10.254.0.5/30", peerAddress: "10.254.0.6", credentialId: id } },
{ name: "linux-wg6", kind: "wireguard", prefixes: [],
linux: { name: "vps6", enabled: true, destinations: [], tunnelMtu: 1360 },
provisionWireguard: { localAddress: "fd00:254::1/126", peerAddress: "fd00:254::2", listenPort: 51821, peerPublicKey: "B".repeat(43) + "=" } },
)
const rules = compileIxConfiguration(id, ixSegmentConfigurationSchema.parse(value)).filter(object => object.fields.action === "change-mss")
assert.equal(rules.length, 6)
for (const [binding, family, mss, disabled] of [
["linux-wg", "ip", 1380, "false"], ["linux-gre", "ip", 1380, "true"], ["linux-wg6", "ipv6", 1300, "false"],
] as const) {
const list = ixClientRoutingTable(table, binding) + "-src"
const shared = { protocol: "tcp", "tcp-flags": "syn", "tcp-mss": (mss + 1) + "-65535",
action: "change-mss", "new-mss": String(mss), passthrough: "true", disabled }
assert.deepEqual(rules.filter(object => object.fields.comment.endsWith("-" + binding)), [
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
fields: { ...shared, chain: "prerouting", "in-interface": binding, "src-address-list": list, comment: table + ":linux-mss-from-" + binding } },
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
fields: { ...shared, chain: "postrouting", "out-interface": binding, "dst-address-list": list, comment: table + ":linux-mss-to-" + binding } },
])
}
})
test("a managed remote exit prepares both CHRs and returns only prefixes of users assigned to it", () => {
const value = fixture(), site = value.sites[0]
site.interfaces.push({ name: "it-abc", kind: "wireguard", prefixes: [], peerServerId: 99,
provisionTransit: { localEndpoint: "192.0.2.44", remoteEndpoint: "192.0.2.45", localAddress: "10.253.0.1/30", remoteAddress: "10.253.0.2",
localPort: 52000, remotePort: 52001, credentialId: id, remoteWan: { interface: "ether1", nextHop: "192.0.2.1", probe: "192.0.2.1", viaMain: true } } })
site.groups.push({ id: "other-ix", gateway: "198.18.0.99", onFailure: "block",
primary: { interface: "it-abc", nextHop: "10.253.0.2", probe: "10.253.0.2" } })
site.interfaces.push({ name: "linux-gre", kind: "gre-ipsec", endpoint: "192.0.2.90", localEndpoint: "192.0.2.44", prefixes: ["10.73.0.0/16"],
linux: { name: "server", enabled: true, exit: "other-ix", destinations: [] },
provisionGre: { localAddress: "10.254.2.1/30", peerAddress: "10.254.2.2", credentialId: id } })
const objects = compileIxConfiguration(id, value)
assert.ok(objects.some(object => object.serverId === 99 && object.path === "/ip/firewall/nat" &&
object.fields["out-interface"] === "ether1" && object.fields["src-address-list"]))
assert.ok(objects.some(object => object.serverId === 99 && object.fields["routing-table"] === "main" && object.fields["dst-address"] === "10.73.0.0/16"))
assert.ok(objects.some(object => object.serverId === 17 && object.path === "/ip/ipsec/identity" && object.fields.secret === "ix-credential:" + id))
assert.ok(objects.some(object => object.serverId === 17 && object.fields["ipsec-policy"] === "in,none" && object.fields.action === "drop"))
})
test("forwarding permits the VRF to exit through its own members before isolation drops", () => {
const objects = compileIxConfiguration(id, fixture())
const egress = ixEgressList(id)
const members = objects.filter(object => object.path === "/interface/list/member")
assert.deepEqual(members.map(object => [object.fields.list, object.fields.interface]),
["wg-eu", "wg-arn", "uplink", "wg-feed"].map(member => [egress, member]))
for (const [family, path] of [[4, "/ip/firewall/filter"], [6, "/ipv6/firewall/filter"]] as const) {
const forward = objects.filter(object => object.path === path && object.fields.chain === "forward")
const boundary = forward.findIndex(object => object.fields.comment === table + ":deny-outside-" + family)
assert.deepEqual(forward.slice(0, boundary).map(object => [object.fields["in-interface"], object.fields["out-interface"] ?? object.fields["out-interface-list"]]),
[[table, table], [table, egress]])
assert.equal(forward[boundary - 1].fields["out-interface-list"], egress)
assert.equal(forward[boundary].fields.action, "drop")
assert.equal(forward.at(-1)?.fields.action, "drop")
assert.equal(forward.at(-1)?.fields["out-interface-list"], egress)
}
})
test("a BGP community uses a stable recursive next hop with independent probes and a final discard", () => {
const objects = compileIxConfiguration(id, fixture())
const policy = objects.find(object => object.fields.comment.endsWith(":bgp-in-evo"))!.fields.rule
assert.match(policy, /if \(dst == 0\.0\.0\.0\/0\) \{ reject; \}/)
assert.match(policy, /bgp-communities includes 65000:120\) \{ set gw 198\.18\.0\.1; set scope-target 23; accept;/)
assert.match(policy, /reject;$/)
const group = objects.filter(object => object.fields["dst-address"] === "198.18.0.1/32" && object.fields["routing-table"] === table)
assert.deepEqual(group.map(object => object.fields.distance), ["10", "11", "254"])
assert.deepEqual(group.slice(0, 2).map(object => object.fields.gateway), ["192.0.2.101@" + table, "192.0.2.102@" + table])
assert.ok(group[2].fields.gateway.endsWith("%" + ixDiscardInterface(id) + "@" + table))
assert.ok(!ixDiscardInterface(id).startsWith(table))
assert.ok(objects.some(object => object.fields["src-port"] === "179" && object.fields["connection-state"] === "established" &&
object.fields["src-address"] === "10.0.4.2/32" && object.fields["in-interface"] === table))
assert.deepEqual(objects.filter(object => object.fields["routing-table"] === "main").map(object => object.fields), [{
"routing-table": "main", "dst-address": "198.18.0.1/32", gateway: "198.18.0.1@" + table, scope: "22", "target-scope": "21", comment: table + ":bgp-resolve-eu",
}])
assert.ok(objects.some(object => object.path === "/ip/firewall/nat" && object.fields["out-interface"] === "uplink"))
})
test("ordinary exit is used for the prefix only when its group explicitly enables fallback", () => {
const value = fixture()
value.sites[0].groups[0].onFailure = "segment-exit"
const group = compileIxConfiguration(id, value).filter(object => object.fields["dst-address"] === "198.18.0.1/32" && object.fields["routing-table"] === table)
assert.equal(group.length, 4)
assert.equal(group[2].fields.gateway, "192.0.2.103@" + table)
assert.equal(group[3].fields.distance, "254")
})
test("a BGP resolver cannot claim an ordinary address in main", () => {
const value = fixture()
value.sites[0].groups[0].gateway = "8.8.8.8"
assert.throws(() => compileIxConfiguration(id, value), /служебный next hop BGP/)
})
test("a probe cannot silently select another interface or recursively follow its own group", () => {
const value = fixture()
value.sites[0].groups[0].backup!.probe = value.sites[0].groups[0].primary.probe
assert.throws(() => compileIxConfiguration(id, value), /закреплён за несколькими путями/)
value.sites[0].groups[0].backup!.probe = value.sites[0].groups[0].gateway
assert.throws(() => compileIxConfiguration(id, value), /не может быть целью пробы/)
})
test("private announcements are restricted to their binding and retain a discard route on withdrawal", () => {
const value = fixture(), site = value.sites[0]
site.interfaces[0].prefixes = ["10.70.0.0/16"]
const peer = site.neighbors[0]
peer.type = "member"
peer.rules = []
peer.binding = "wg-eu"
peer.group = "eu"
peer.prefixes = ["10.70.0.0/16"]
assert.ok(compileIxConfiguration(id, value).some(object => object.fields["dst-address"] === "10.70.0.0/16" && object.fields.blackhole === "yes"))
peer.prefixes = ["10.71.0.0/16"]
assert.throws(() => compileIxConfiguration(id, value), /только диапазоны подключения/)
})
test("GRE/IPsec binds its plaintext drops to the two fixed outer endpoints", () => {
const value = fixture()
const binding = value.sites[0].interfaces[0]
binding.kind = "gre-ipsec"
assert.throws(() => compileIxConfiguration(id, value), /фиксированных внешних/)
binding.localEndpoint = "192.0.2.44"
binding.endpoint = "192.0.2.45"
const drop = compileIxConfiguration(id, value).find(object => object.fields["ipsec-policy"] === "in,none")!
assert.deepEqual([drop.fields["src-address"], drop.fields["dst-address"]], ["192.0.2.45/32", "192.0.2.44/32"])
})
@@ -0,0 +1,445 @@
import { BlockList, isIP } from "node:net"
import { createHash } from "node:crypto"
import type { IxConfiguration, IxRouterObject, IxSite } from "@mmapp/contracts/internet-exchange"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
import { compileIxTransit, ixTransitSourceObjects } from "./internet-exchange-transit.js"
export class IxConflict extends Error {
constructor(message: string, readonly statusCode = 409) { super(message) }
}
const families = [4, 6] as const
type Family = typeof families[number]
const familyOf = (address: string) => isIP(address.split("/")[0])
const host = (address: string) => canonicalBgpPolicyPrefix(address + (isIP(address) === 4 ? "/32" : "/128"))
const routePath = (family: number) => family === 4 ? "/ip/route" : "/ipv6/route"
const familyName = (family: number) => family === 4 ? "ip" : "ipv6"
const prefixIdentifier = (value: string) => createHash("sha256").update(value).digest("hex").slice(0, 12)
const sink = {
4: { local: "169.254.255.249/30", neighbor: "169.254.255.250" },
6: { local: "fd00:ffff:ffff::1/126", neighbor: "fd00:ffff:ffff::2" },
}
const defaultRoute = { 4: "0.0.0.0/0", 6: "::/0" }
const bgpGatewayRange = { 4: "198.18.0.0/15", 6: "fd00:198:18::/48" }
const forbiddenPublic = {
4: ["0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.168.0.0/16", "198.18.0.0/15", "224.0.0.0/3"],
6: ["::/96", "::ffff:0:0/96", "fc00::/7", "fe80::/10", "ff00::/8"],
}
export function ixNamespace(id: string) { return "ix-" + id.replace(/-/g, "").slice(0, 18) }
// RouterOS accepts unambiguous prefixes for interface names before the VRF interface appears.
export function ixDiscardInterface(id: string) { return "ix-drop-" + ixNamespace(id).slice(3) }
export function ixEgressList(id: string) { return "ix-out-" + ixNamespace(id).slice(3) }
export function ixDeviceIds(configuration: IxConfiguration) {
return [...new Set(configuration.sites.flatMap(site => [site.serverId, ...site.interfaces.flatMap(binding => binding.peerServerId === undefined ? [] : [binding.peerServerId])]))].sort((a, b) => a - b)
}
function requireIx(condition: unknown, message: string): asserts condition {
if (!condition) throw new IxConflict(message, 400)
}
function unique(values: string[], label: string) {
requireIx(new Set(values).size === values.length, "Повторяется " + label)
}
export function inIxNetwork(cidr: string, value: string) {
const [network, length] = cidr.split("/")
const [candidate, candidateLength] = value.split("/")
const family = isIP(network)
if (family !== isIP(candidate) || (candidateLength !== undefined && Number(candidateLength) < Number(length))) return false
const familyName = family === 4 ? "ipv4" : "ipv6"
const block = new BlockList()
block.addSubnet(network, Number(length), familyName)
return block.check(candidate, familyName)
}
const inNetwork = inIxNetwork
function groupPaths(group: IxSite["groups"][number]) {
return group.backup ? [group.primary, group.backup] : [group.primary]
}
function checkedIxHop(path: IxSite["groups"][number]["primary"], namespace: string) {
if (path.viaMain && path.probe === path.nextHop) {
return { gateway: path.nextHop + "%" + path.interface + "@main", "target-scope": "10", "check-gateway": "ping" }
}
return { gateway: path.probe + "@" + (path.viaMain ? "main" : namespace), "target-scope": "11", "check-gateway": "ping" }
}
export function ixClientRoutingTable(namespace: string, binding: string) {
return namespace + "-p-" + createHash("sha256").update(binding).digest("hex").slice(0, 8)
}
function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["interfaces"][number],
add: (path: string, key: string, fields: Record<string, string>) => void) {
const policy = binding.linux!
const tunnel = (binding.provisionWireguard ?? binding.provisionGre)!
const family = familyOf(tunnel.localAddress) as Family
const ip = "/" + familyName(family)
const raw = ip + "/firewall/raw"
const filter = ip + "/firewall/filter"
const key = "linux-" + binding.name
const privateTable = ixClientRoutingTable(namespace, binding.name)
const sources = privateTable + "-src"
const permitted = privateTable + "-dst"
const sourcesCidr = [...new Set([host(tunnel.peerAddress), ...binding.prefixes.map(canonicalBgpPolicyPrefix)])]
const destinations = [...new Set([host(tunnel.localAddress.split("/")[0]), ...policy.destinations.map(canonicalBgpPolicyPrefix)])]
// Use the WireGuard default as a conservative ceiling for both managed tunnel types.
const mss = (policy.tunnelMtu ?? 1420) - (family === 4 ? 40 : 60)
const clamp = { protocol: "tcp", "tcp-flags": "syn", "tcp-mss": (mss + 1) + "-65535",
action: "change-mss", "new-mss": String(mss), passthrough: "true", disabled: String(!policy.enabled) }
const mangle = ip + "/firewall/mangle"
const ingress = { chain: "prerouting", "in-interface": binding.name }
const exit = site.groups.find(group => group.id === policy.exit)
const paths = exit ? groupPaths(exit) : []
for (const address of sourcesCidr) add(ip + "/firewall/address-list", key + "-src-" + prefixIdentifier(address), { address, list: sources })
for (const address of destinations) add(ip + "/firewall/address-list", key + "-dst-" + prefixIdentifier(address), { address, list: permitted })
add(raw, key + "-disabled", { ...ingress, action: "drop", disabled: String(policy.enabled) })
add(raw, key + "-spoof", { ...ingress, "src-address-list": "!" + sources, action: "drop" })
add(raw, key + "-destinations", { ...ingress, "dst-address-list": "!" + permitted, action: "drop", disabled: String(!!exit) })
add("/" + familyName(family === 4 ? 6 : 4) + "/firewall/raw", key + "-other-family", { ...ingress, action: "drop" })
if (binding.provisionWireguard) {
const transportFamily = familyOf(binding.provisionWireguard.hubEndpoint ?? tunnel.localAddress) as Family
add("/" + familyName(transportFamily) + "/firewall/filter", key + "-wg-listen", {
chain: "input", protocol: "udp", "dst-port": String(binding.provisionWireguard.listenPort), action: "accept",
...(binding.provisionWireguard.hubEndpoint && { "dst-address": host(binding.provisionWireguard.hubEndpoint) }),
disabled: String(!policy.enabled),
})
}
if (binding.provisionGre) {
const transport = { chain: "input", "src-address": host(binding.endpoint!), "dst-address": host(binding.localEndpoint!),
action: "accept", disabled: String(!policy.enabled) }
add(filter, key + "-ike", { ...transport, protocol: "udp", "dst-port": "500,4500" })
add(filter, key + "-esp", { ...transport, protocol: "ipsec-esp" })
add(filter, key + "-encrypted-gre", { ...transport, protocol: "gre", "ipsec-policy": "in,ipsec" })
}
const outbound = { chain: "forward", "src-address-list": sources, action: "accept", disabled: String(!policy.enabled) }
const inbound = { chain: "forward", "dst-address-list": sources }
add(filter, key + "-established", { ...inbound, "connection-state": "established,related", action: "accept", disabled: String(!policy.enabled) })
add(filter, key + "-allow-inbound", { ...inbound, "src-address-list": permitted, "in-interface": namespace,
action: "accept", disabled: String(!policy.enabled) })
add(filter, key + "-deny-inbound", { ...inbound, action: "drop" })
// The real VRF member is visible before routing and after routing, respectively.
add(mangle, "linux-mss-from-" + binding.name, {
...clamp, ...ingress, "src-address-list": sources,
})
add(mangle, "linux-mss-to-" + binding.name, {
...clamp, chain: "postrouting", "out-interface": binding.name, "dst-address-list": sources,
})
if (!exit) return
add("/routing/table", key + "-table", { name: privateTable, fib: "true" })
for (const [index, path] of paths.entries()) {
add(routePath(family), key + "-default-" + index, {
"routing-table": privateTable, "dst-address": defaultRoute[family], ...checkedIxHop(path, namespace), distance: String(10 + index),
})
}
add(routePath(family), key + "-default-drop", { "routing-table": privateTable, "dst-address": defaultRoute[family], blackhole: "yes", distance: "254" })
add(mangle, key + "-route", { ...ingress, "src-address-list": sources, "dst-address-list": "!" + permitted,
action: "mark-routing", "new-routing-mark": privateTable, passthrough: "false", disabled: String(!policy.enabled) })
const mainPaths = paths.filter(path => path.viaMain)
for (const [index, path] of mainPaths.entries()) {
add(filter, key + "-wan-" + index, { ...outbound, "out-interface": path.interface })
if (family === 4) add("/ip/firewall/nat", key + "-nat-" + index, { chain: "srcnat", "src-address-list": sources,
"out-interface": path.interface, action: "masquerade", disabled: String(!policy.enabled) })
}
if (mainPaths.length) for (const prefix of sourcesCidr) {
add(routePath(family), key + "-return-" + prefixIdentifier(prefix), {
"routing-table": "main", "dst-address": prefix, gateway: tunnel.peerAddress + "%" + binding.name + "@" + namespace,
disabled: String(!policy.enabled),
})
}
}
function validateSite(site: IxSite, otherId?: number) {
unique(site.interfaces.map(entry => entry.name), "интерфейс IX")
unique(site.groups.map(entry => entry.id), "группа шлюзов")
unique(site.groups.map(entry => host(entry.gateway)), "служебный next hop")
unique(site.neighbors.map(entry => entry.id), "BGP-сосед")
unique(site.neighbors.map(entry => host(entry.address)), "адрес BGP-соседа")
unique(site.routes.map(entry => canonicalBgpPolicyPrefix(entry.prefix)), "префикс")
unique(site.exits, "интернет-выход")
const bindings = new Map(site.interfaces.map(binding => [binding.name, binding]))
const groups = new Map(site.groups.map(group => [group.id, group]))
for (const binding of site.interfaces) {
if (binding.kind === "gre-ipsec") {
requireIx(binding.endpoint && binding.localEndpoint && isIP(binding.endpoint) === 4 && isIP(binding.localEndpoint) === 4 &&
binding.endpoint !== binding.localEndpoint, "GRE/IPsec требует двух разных фиксированных внешних IPv4-адресов")
}
if (binding.natIpv4) requireIx(binding.kind === "uplink" && !binding.peerServerId, "NAT разрешён только на локальном uplink")
const wireguard = binding.provisionWireguard
if (wireguard) {
requireIx(binding.kind === "wireguard" && inNetwork(wireguard.localAddress, wireguard.peerAddress) &&
host(wireguard.localAddress.split("/")[0]) !== host(wireguard.peerAddress), "Неверные адреса WireGuard-подключения")
requireIx(!wireguard.endpointPort || binding.endpoint, "Порт WireGuard требует внешнего адреса")
requireIx(!binding.endpoint || wireguard.endpointPort, "Внешний адрес WireGuard требует порта")
}
const gre = binding.provisionGre
if (gre) {
requireIx(binding.kind === "gre-ipsec" && binding.linux && inNetwork(gre.localAddress, gre.peerAddress) &&
host(gre.localAddress.split("/")[0]) !== host(gre.peerAddress), "Неверные адреса управляемого GRE/IPsec")
}
if (binding.provisionTransit) {
const link = binding.provisionTransit
requireIx(binding.kind === "wireguard" && binding.peerServerId && !binding.linux && !wireguard &&
inNetwork(link.localAddress, link.remoteAddress) && link.remoteAddress !== link.localAddress.split("/")[0] &&
link.remoteEndpoint !== link.localEndpoint && link.remoteWan.viaMain &&
isIP(link.remoteWan.nextHop) === isIP(link.remoteAddress),
"Неверные параметры управляемого транзита IX")
}
if (binding.linux) {
const tunnel = wireguard ?? gre
requireIx(tunnel && !binding.peerServerId, "Linux-клиенту нужен управляемый туннель")
const family = familyOf(tunnel.localAddress)
requireIx([...binding.linux.destinations, ...binding.prefixes].every(prefix => familyOf(prefix) === family &&
Number(prefix.split("/")[1]) > 0), "Префиксы Linux должны совпадать с семейством туннеля и не могут быть default")
const group = binding.linux.exit && groups.get(binding.linux.exit)
requireIx(!binding.linux.exit || group && familyOf(group.gateway) === family && group.onFailure === "block",
"Для Linux нужен выход того же семейства без неявного переключения на общий шлюз")
requireIx(!group || groupPaths(group).every(path => path.interface !== binding.name), "Клиентский туннель не может быть своим выходом")
}
}
const probes = new Map<string, string>()
const ownedNetworks = site.interfaces.flatMap(binding => [
...binding.prefixes, ...(binding.provisionTransit ? [binding.provisionTransit.localAddress] : []),
...(binding.linux ? [host((binding.provisionWireguard ?? binding.provisionGre)!.peerAddress),
host((binding.provisionWireguard ?? binding.provisionGre)!.localAddress.split("/")[0])] : []),
].map(prefix => ({ binding, prefix })))
for (const [index, first] of ownedNetworks.entries()) {
requireIx(Number(first.prefix.split("/")[1]) > 0, "Префикс подключения не может быть default route")
for (const second of ownedNetworks.slice(0, index)) {
if (first.binding === second.binding) continue
requireIx(!inNetwork(first.prefix, second.prefix) && !inNetwork(second.prefix, first.prefix), "Префиксы разных подключений пересекаются")
}
}
for (const group of site.groups) {
const family = familyOf(group.gateway) as Family
requireIx(!ownedNetworks.some(entry => inNetwork(entry.prefix, group.gateway)), "Служебный next hop пересекает сеть подключения")
requireIx(!inNetwork(sink[family].local, group.gateway), "Служебный next hop пересекает сеть отбрасывания")
if (group.backup) requireIx(group.primary.interface !== group.backup.interface, "Резерв требует другого интерфейса")
for (const candidate of groupPaths(group)) {
requireIx(candidate.viaMain ? !bindings.has(candidate.interface) : bindings.has(candidate.interface), "Шлюз использует интерфейс вне своей таблицы")
requireIx([candidate.nextHop, candidate.probe].every(address => isIP(address) === family), "Семейства адресов шлюза не совпадают")
requireIx(!site.groups.some(entry => host(entry.gateway) === host(candidate.probe) || host(entry.gateway) === host(candidate.nextHop)), "Рекурсивный шлюз не может быть целью пробы или соседом")
requireIx(!inNetwork(sink[family].local, candidate.probe) && !inNetwork(sink[family].local, candidate.nextHop), "Путь использует служебную сеть отбрасывания")
const probe = host(candidate.probe), path = host(candidate.nextHop) + "%" + candidate.interface
requireIx(!probes.has(probe) || probes.get(probe) === path, "Контрольный адрес закреплён за несколькими путями")
probes.set(probe, path)
}
}
const exits = site.exits.map(id => groups.get(id))
requireIx(exits.every(Boolean), "Неизвестная группа обычного выхода")
for (const exit of exits) {
requireIx(exit!.onFailure === "block", "Обычный выход не может ссылаться сам на себя")
}
for (const group of site.groups) {
if (group.onFailure === "segment-exit") requireIx(exits.some(exit => familyOf(exit!.gateway) === familyOf(group.gateway)), "Для fallback нужен выход того же семейства")
}
for (const route of site.routes) {
const group = groups.get(route.group)
requireIx(group && familyOf(route.prefix) === familyOf(group.gateway), "Маршрут использует неизвестную группу или другое семейство")
requireIx(Number(route.prefix.split("/")[1]) > 0, "Default route задаётся в разделе выходов")
requireIx(!site.groups.some(entry => canonicalBgpPolicyPrefix(route.prefix) === host(entry.gateway)) && !probes.has(canonicalBgpPolicyPrefix(route.prefix)), "Префикс совпадает со служебным маршрутом")
}
for (const network of site.discardNetworks) {
requireIx(Number(network.split("/")[1]) > 0, "Маршрут защиты не может быть default route")
}
for (const peer of site.neighbors) {
const binding = bindings.get(peer.binding)
const family = familyOf(peer.address)
requireIx(binding && familyOf(peer.localAddress) === family, "BGP-сосед использует необъявленный интерфейс или другое семейство")
requireIx(peer.remoteAs !== site.autonomousSystem, "IX принимает только явно настроенных eBGP-соседей")
unique(peer.rules.map(rule => rule.community), "community у BGP-соседа")
const groupIds = peer.type === "public-feed" ? peer.rules.map(rule => rule.group) : [peer.group]
requireIx(groupIds.length && groupIds.every(id => id && groups.has(id) && familyOf(groups.get(id)!.gateway) === family), "У BGP-соседа нет подходящей группы шлюзов")
requireIx(peer.prefixes.concat(peer.exportPrefixes).every(prefix => familyOf(prefix) === family && Number(prefix.split("/")[1]) > 0), "Неверный диапазон BGP-соседа")
if (peer.type === "public-feed") {
requireIx(!peer.group && !peer.exportPrefixes.length, "Публичный фид не принимает экспорт IX")
continue
}
requireIx(peer.prefixes.length && !peer.rules.length, "Частный сосед должен объявлять согласованный диапазон")
requireIx(groups.get(peer.group!)?.onFailure === "block", "Частный префикс нельзя отправлять в обычный выход")
requireIx(peer.prefixes.every(prefix => binding.prefixes.some(allowed => inNetwork(allowed, prefix))), "BGP импортирует только диапазоны подключения")
if (peer.type === "exchange") requireIx(otherId && binding.peerServerId === otherId && binding.kind === "wireguard", "Межплощадочный BGP требует WireGuard до второй площадки")
requireIx(peer.exportPrefixes.every(prefix => ownedNetworks.some(entry => entry.binding !== binding && inNetwork(entry.prefix, prefix))), "Экспорт разрешён только из согласованных сетей других подключений")
}
}
export function compileIxConfiguration(id: string, configuration: IxConfiguration): IxRouterObject[] {
const namespace = ixNamespace(id)
const result: IxRouterObject[] = []
unique(configuration.sites.map(site => String(site.serverId)), "площадка IX")
const remoteExit = (site: IxSite, remoteId: number) => site.groups.filter(group => site.exits.includes(group.id))
.flatMap(groupPaths).some(path => site.interfaces.some(binding => binding.name === path.interface && binding.peerServerId === remoteId))
if (configuration.sites.length === 2) {
const [a, b] = configuration.sites
requireIx(!remoteExit(a, b.serverId) || !remoteExit(b, a.serverId), "Основные и резервные выходы образуют цикл между IX")
}
for (const site of configuration.sites) {
const otherId = configuration.sites.find(candidate => candidate.serverId !== site.serverId)?.serverId
validateSite(site, otherId)
const add = (path: string, key: string, fields: Record<string, string>) => {
const nameOnly = ["/ip/ipsec/profile", "/ip/ipsec/proposal", "/ip/ipsec/peer", "/routing/table"].includes(path)
result.push({ serverId: site.serverId, path, fields: nameOnly ? fields : { ...fields, comment: namespace + ":" + key } })
}
const protectGre = (binding: IxSite["interfaces"][number], key: string) => {
add("/ip/firewall/filter", "gre-in-" + key, { chain: "input", protocol: "gre", "src-address": host(binding.endpoint!), "dst-address": host(binding.localEndpoint!), "ipsec-policy": "in,none", action: "drop" })
add("/ip/firewall/filter", "gre-out-" + key, { chain: "output", protocol: "gre", "src-address": host(binding.localEndpoint!), "dst-address": host(binding.endpoint!), "ipsec-policy": "out,none", action: "drop" })
}
const dropInterface = ixDiscardInterface(id)
for (const [index, binding] of site.interfaces.entries()) {
const wireguard = binding.provisionWireguard
const key = binding.linux ? binding.name : String(index)
if (binding.provisionTransit) compileIxTransit(namespace, site, binding, object => result.push(object))
if (wireguard) add("/interface/wireguard", "wg-" + key, { name: binding.name, "listen-port": String(wireguard.listenPort),
...(binding.linux && { disabled: String(!binding.linux.enabled) }) })
const gre = binding.provisionGre
if (gre) {
const transport = namespace + "-" + key
protectGre(binding, key)
add("/ip/ipsec/profile", key, { name: transport, "enc-algorithm": "aes-256", "hash-algorithm": "sha256", "dh-group": "modp2048" })
add("/ip/ipsec/proposal", key, { name: transport, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256", "pfs-group": "modp2048" })
add("/ip/ipsec/peer", key, { name: transport, address: host(binding.endpoint!), "local-address": binding.localEndpoint!,
profile: transport, "exchange-mode": "ike2", passive: "true" })
add("/ip/ipsec/identity", "gre-identity-" + key, { peer: transport, "auth-method": "pre-shared-key",
secret: "ix-credential:" + gre.credentialId, disabled: String(!binding.linux!.enabled) })
add("/ip/ipsec/policy", "gre-policy-" + key, { peer: transport, "src-address": host(binding.localEndpoint!),
"dst-address": host(binding.endpoint!), protocol: "gre", action: "encrypt", level: "require", tunnel: "false", proposal: transport })
add("/interface/gre", "gre-" + key, { name: binding.name, "local-address": binding.localEndpoint!,
"remote-address": binding.endpoint!, "allow-fast-path": "false", disabled: String(!binding.linux!.enabled) })
}
}
add("/interface/bridge", "drop-bridge", { name: dropInterface, "protocol-mode": "none" })
add("/ip/vrf", "vrf", { name: namespace, interfaces: [dropInterface, ...site.interfaces.map(binding => binding.name)].join(",") })
for (const binding of site.interfaces.filter(binding => binding.linux)) {
compileLinuxPolicy(namespace, site, binding, add)
}
if (site.interfaces.length) {
const egress = ixEgressList(id)
add("/interface/list", "egress-list", { name: egress })
for (const binding of site.interfaces) {
add("/interface/list/member", "egress-member-" + binding.name, { list: egress, interface: binding.name })
}
for (const family of families) {
const filter = family === 4 ? "/ip/firewall/filter" : "/ipv6/firewall/filter"
for (const peer of site.neighbors.filter(peer => familyOf(peer.address) === family)) {
const control = { chain: "input", "in-interface": namespace, protocol: "tcp", "src-address": host(peer.address), action: "accept" }
add(filter, "allow-bgp-" + peer.id, { ...control, "dst-port": "179" })
add(filter, "bgp-reply-" + peer.id, { ...control, "src-port": "179", "connection-state": "established" })
}
add(filter, "allow-control-" + family, { chain: "input", "in-interface": namespace, protocol: family === 4 ? "icmp" : "icmpv6", action: "accept" })
add(filter, "deny-input-" + family, { chain: "input", "in-interface": namespace, action: "drop" })
add(filter, "allow-segment-" + family, { chain: "forward", "in-interface": namespace, "out-interface": namespace, action: "accept" })
add(filter, "egress-allow-" + family, { chain: "forward", "in-interface": namespace, "out-interface-list": egress, action: "accept" })
add(filter, "deny-outside-" + family, { chain: "forward", "in-interface": namespace, action: "drop" })
add(filter, "deny-inside-" + family, { chain: "forward", "out-interface": namespace, action: "drop" })
add(filter, "egress-deny-" + family, { chain: "forward", "out-interface-list": egress, action: "drop" })
}
for (const [index, binding] of site.interfaces.entries()) {
const key = binding.linux ? binding.name : String(index)
if (binding.natIpv4) add("/ip/firewall/nat", "nat-" + index, { chain: "srcnat", action: "masquerade", "out-interface": binding.name })
if (binding.kind === "gre-ipsec" && !binding.provisionGre) protectGre(binding, key)
}
}
for (const [index, binding] of site.interfaces.entries()) {
const wireguard = binding.provisionWireguard
const tunnel = wireguard ?? binding.provisionGre
if (binding.provisionTransit) result.push(...ixTransitSourceObjects(namespace, site, binding))
if (!tunnel) continue
const key = binding.linux ? binding.name : String(index)
const family = familyOf(tunnel.localAddress)
add(family === 4 ? "/ip/address" : "/ipv6/address", (binding.linux ? "client-address-" : "wg-address-") + key, {
address: tunnel.localAddress, interface: binding.name, ...(family === 6 ? { advertise: "no" } : {}),
})
if (wireguard) add("/interface/wireguard/peers", "wg-peer-" + key, {
interface: binding.name, "public-key": wireguard.peerPublicKey,
"allowed-address": [...new Set([host(wireguard.peerAddress), ...binding.prefixes.map(canonicalBgpPolicyPrefix)])].join(","),
...(binding.endpoint ? { "endpoint-address": binding.endpoint, "endpoint-port": String(wireguard.endpointPort) } : {}),
})
for (const prefix of binding.linux ? binding.prefixes : []) {
add(routePath(family), "client-network-" + key + "-" + prefixIdentifier(prefix), {
"routing-table": namespace, "dst-address": canonicalBgpPolicyPrefix(prefix),
gateway: tunnel.peerAddress + "%" + binding.name + "@" + namespace,
})
}
}
const groups = new Map(site.groups.map(group => [group.id, group]))
const bgpGroups = new Set(site.neighbors.flatMap(peer => peer.type === "public-feed" ? peer.rules.map(rule => rule.group) : [peer.group]))
const knownProbes = new Set<string>()
const privateNetworks = [...new Set(site.discardNetworks.concat(site.neighbors.filter(peer => peer.type !== "public-feed").flatMap(peer => peer.prefixes),
site.interfaces.flatMap(binding => binding.linux?.destinations ?? [])).map(canonicalBgpPolicyPrefix))]
for (const family of families) {
if (!site.groups.some(group => familyOf(group.gateway) === family) && !privateNetworks.some(prefix => familyOf(prefix) === family)) continue
const path = routePath(family)
const addressPath = family === 4 ? "/ip/address" : "/ipv6/address"
add(addressPath, "drop-address-" + family, { address: sink[family].local, interface: dropInterface, ...(family === 6 ? { advertise: "no" } : {}) })
const localRoute = (key: string, fields: Record<string, string>) => add(path, key, { "routing-table": namespace, ...fields })
const familyExits = site.exits.map(id => groups.get(id)!).filter(group => familyOf(group.gateway) === family)
const via = (address: string) => address + "@" + namespace
for (const group of site.groups.filter(group => familyOf(group.gateway) === family)) {
if (bgpGroups.has(group.id)) requireIx(inNetwork(bgpGatewayRange[family], group.gateway), "Используйте служебный next hop BGP из " + bgpGatewayRange[family])
const paths = groupPaths(group).concat(group.onFailure === "segment-exit" ? familyExits.flatMap(groupPaths) : [])
const distinctPaths = [...new Map(paths.map(candidate => [host(candidate.probe), candidate])).values()]
for (const [index, candidate] of distinctPaths.entries()) {
const probe = host(candidate.probe)
if (!knownProbes.has(probe)) {
const fields = { "dst-address": probe, gateway: candidate.nextHop + "%" + candidate.interface + "@" + (candidate.viaMain ? "main" : namespace),
scope: "10", "target-scope": "10" }
if (candidate.viaMain && candidate.probe !== candidate.nextHop) {
add(path, "probe-main-" + knownProbes.size, { ...fields, "routing-table": "main" })
} else localRoute("probe-" + knownProbes.size, fields)
knownProbes.add(probe)
}
localRoute("gw-" + group.id + "-" + index, { "dst-address": host(group.gateway), ...checkedIxHop(candidate, namespace), scope: "20", distance: String(10 + index) })
}
localRoute("gw-" + group.id + "-discard", { "dst-address": host(group.gateway), gateway: sink[family].neighbor + "%" + dropInterface + "@" + namespace, scope: "20", "target-scope": "10", distance: "254" })
// RouterOS 7.24 resolves addresses rewritten by a BGP input filter in main.
if (bgpGroups.has(group.id)) add(path, "bgp-resolve-" + group.id, {
"routing-table": "main", "dst-address": host(group.gateway), gateway: via(group.gateway), scope: "22", "target-scope": "21",
})
}
for (const [index, route] of site.routes.entries()) {
if (familyOf(route.prefix) === family) localRoute("static-" + index, { "dst-address": canonicalBgpPolicyPrefix(route.prefix), gateway: via(groups.get(route.group)!.gateway), "target-scope": "21" })
}
for (const [index, prefix] of privateNetworks.entries()) {
if (familyOf(prefix) === family) localRoute("guard-" + index, { "dst-address": prefix, blackhole: "yes", distance: "254" })
}
// Compare exit path health directly: a group's final discard next hop must never win as an ordinary exit.
for (const [index, candidate] of familyExits.flatMap(groupPaths).entries()) {
localRoute("exit-" + family + "-" + index, { "dst-address": defaultRoute[family], ...checkedIxHop(candidate, namespace), distance: String(10 + index) })
}
localRoute("default-discard-" + family, { "dst-address": defaultRoute[family], blackhole: "yes", distance: "254" })
}
if (!site.neighbors.length) continue
add("/routing/bgp/instance", "bgp-instance", { name: namespace, as: String(site.autonomousSystem), "router-id": site.routerId, vrf: namespace, "routing-table": namespace })
for (const peer of site.neighbors) {
const family = familyOf(peer.address) as Family
const input = namespace + "-" + peer.id + "-in"
const output = namespace + "-" + peer.id + "-out"
const subnetCondition = (prefix: string) => "dst in " + canonicalBgpPolicyPrefix(prefix)
const setGateway = (groupId: string) => "set gw " + groups.get(groupId)!.gateway + "; set scope-target 23; accept;"
const lines = ["if (dst == " + defaultRoute[family] + ") { reject; }"]
if (peer.type === "public-feed") {
const protectedNetworks = [...forbiddenPublic[family], ...privateNetworks.filter(prefix => familyOf(prefix) === family), ...site.groups.filter(group => familyOf(group.gateway) === family).map(group => host(group.gateway)), ...knownProbes].filter(prefix => familyOf(prefix) === family)
lines.push("if (" + protectedNetworks.map(subnetCondition).join(" || ") + ") { reject; }")
const restriction = peer.prefixes.length ? " && (" + peer.prefixes.map(subnetCondition).join(" || ") + ")" : ""
for (const rule of peer.rules) lines.push("if (bgp-communities includes " + rule.community + restriction + ") { " + setGateway(rule.group) + " }")
} else {
lines.push("if (" + peer.prefixes.map(subnetCondition).join(" || ") + ") { " + setGateway(peer.group!) + " }")
}
const exportRules = peer.exportPrefixes.length ? "if (" + peer.exportPrefixes.map(subnetCondition).join(" || ") + ") { accept; } reject;" : "reject;"
add("/routing/filter/rule", "bgp-in-" + peer.id, { chain: input, rule: lines.concat("reject;").join("\n") })
add("/routing/filter/rule", "bgp-out-" + peer.id, { chain: output, rule: exportRules })
add("/routing/bgp/connection", "neighbor-" + peer.id, {
name: namespace + "-" + peer.id, instance: namespace, afi: familyName(family),
"local.role": "ebgp", "local.address": peer.localAddress, "remote.address": host(peer.address), "remote.as": String(peer.remoteAs),
"routing-table": namespace, vrf: namespace, "input.filter": input, "output.filter-chain": output,
["input.limit-process-routes-ipv" + family]: String(peer.limit),
...(peer.type === "exchange" ? { multihop: "yes", "output.redistribute": "static" } : {}),
})
}
}
unique(result.filter(object => object.fields["routing-table"] === "main" && object.fields["dst-address"])
.map(object => object.serverId + ":" + object.fields["dst-address"]), "служебный или обратный маршрут IX в main")
requireIx(result.length <= 500, "План IX превышает 500 объектов; разделите конфигурацию")
return result
}
@@ -0,0 +1,238 @@
import type { PoolClient } from "pg"
import { isIPv4 } from "node:net"
import { ixSegmentConfigurationSchema, type IxConfiguration, type IxSegment } from "@mmapp/contracts/internet-exchange"
import { pool } from "../db/index.js"
import { audit } from "../modules/mcp/store.js"
import { IxConflict, ixDeviceIds } from "./internet-exchange-plan.js"
import { admitPartitionWriter } from "./partition-write-transaction.js"
interface SegmentRow {
id: string
revision: number
applied_revision: number | null
configuration: unknown
updated_at: Date
}
// VPS bond metadata has its own revision and never enters a RouterOS plan or segment export.
const columns = "id,revision,applied_revision,(configuration - 'linuxBonds') AS configuration,updated_at"
const visible = "(configuration->>'deleted') IS DISTINCT FROM 'true'"
function segment(row: SegmentRow): IxSegment {
return { id: row.id, revision: row.revision, appliedRevision: row.applied_revision,
configuration: ixSegmentConfigurationSchema.parse(row.configuration), updatedAt: row.updated_at.toISOString() }
}
export async function listIxSegments(limit: number, offset: number, allowedIds?: readonly number[]) {
const { rows } = await pool.query<SegmentRow>(
`SELECT ${columns} FROM ix_segments s
WHERE ${visible} AND ($1::bigint[] IS NULL OR NOT EXISTS (
SELECT 1 FROM ix_segment_devices d WHERE d.segment_id=s.id AND NOT (d.server_id=ANY($1::bigint[]))
))
ORDER BY name,id LIMIT $2 OFFSET $3`, [allowedIds ?? null, limit, offset])
return rows.map(segment)
}
export async function readIxSegment(id: string, sql: Pick<PoolClient, "query"> = pool) {
const { rows: [row] } = await sql.query<SegmentRow>(`SELECT ${columns} FROM ix_segments WHERE id=$1 AND ${visible}`, [id])
return row ? segment(row) : null
}
export async function isIxSegmentArchived(id: string, revision: number) {
const { rowCount } = await pool.query("SELECT 1 FROM ix_segments WHERE id=$1 AND revision=$2 AND configuration->>'deleted'='true'", [id, revision])
return rowCount === 1
}
export async function assertIxSegmentWithoutBonds(id: string) {
const { rowCount } = await pool.query(`SELECT 1 FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') g
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true'
AND (s.id=$1::uuid OR EXISTS (SELECT FROM jsonb_array_elements(g->'members') m WHERE m->>'segmentId'=$1::text))
LIMIT 1`, [id])
if (rowCount) throw new IxConflict("Сначала исключите сегмент из групп туннелей Linux")
}
export async function ixBondClientId(segmentId: string, serverId: number, interfaceName: string) {
const { rows } = await pool.query<{ id: string }>(`SELECT g->>'clientId' AS id FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') g
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND g->'members' @> $1::jsonb LIMIT 1`,
[JSON.stringify([{ segmentId, serverId, interfaceName }])])
return rows[0]?.id
}
export async function ixKnownVpsClient(id: string) {
const { rowCount } = await pool.query(`SELECT 1 FROM ix_segments s
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND
(s.configuration->'linuxBonds' @> $1::jsonb OR r.configuration->'sites' @> $2::jsonb) LIMIT 1`,
[JSON.stringify([{ clientId: id }]), JSON.stringify([{ interfaces: [{ linux: { clientId: id, enabled: true } }] }])])
return !!rowCount
}
export async function assertIxBondClientAssignments(segmentId: string, configuration: IxConfiguration) {
const assignments = configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.linux?.clientId
? [{ server_id: site.serverId, iface: binding.name, client_id: binding.linux.clientId }] : []))
if (!assignments.length) return
const { rowCount } = await pool.query(`SELECT 1 FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') g
CROSS JOIN LATERAL jsonb_array_elements(g->'members') m
JOIN jsonb_to_recordset($2::jsonb) AS a(server_id bigint, iface text, client_id uuid)
ON m->>'serverId' = a.server_id::text AND m->>'interfaceName' = a.iface
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND m->>'segmentId'=$1 AND g->>'clientId'<>a.client_id::text LIMIT 1`,
[segmentId, JSON.stringify(assignments)])
if (rowCount) throw new IxConflict("Сначала исключите подключение из действующей группы VPS")
}
export async function readIxRevision(id: string, revision: number) {
const { rows: [row] } = await pool.query("SELECT configuration FROM ix_segment_revisions WHERE segment_id=$1 AND revision=$2", [id, revision])
if (!row) throw new IxConflict("Ревизия IX не найдена", 404)
return ixSegmentConfigurationSchema.parse(row.configuration)
}
export async function assertIxName(id: string, name: string) {
const { rows } = await pool.query("SELECT 1 FROM ix_segments WHERE name=$1 AND id<>$2", [name, id])
if (rows.length) throw new IxConflict("Имя IX уже занято")
}
export async function assertIxSites(configuration: IxConfiguration, sql: Pick<PoolClient, "query"> = pool) {
const ids = ixDeviceIds(configuration)
const { rows } = await sql.query<{ id: number; type: string; enabled: boolean }>(
"SELECT id,type,enabled FROM servers WHERE id=ANY($1::bigint[])", [ids])
if (ids.length !== rows.length || rows.some(row => !row.enabled) || configuration.sites.some(site => rows.find(row => row.id === site.serverId)?.type !== "ix-node")) {
throw new IxConflict("Площадки должны привязываться к включённым серверам типа IX Node, а все соседние устройства должны быть доступны")
}
}
export function assertIxRevision(current: IxSegment | null, expected: number) {
if ((current?.revision ?? 0) !== expected) throw new IxConflict("Ревизия IX изменилась. Обновите данные и подготовьте новый план")
}
export async function ixReservedRouterIds(id?: string, sql: Pick<PoolClient, "query"> = pool) {
const { rows } = await sql.query<{ router_id: string }>(`
SELECT site->>'routerId' AS router_id
FROM ix_segments s
LEFT JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
CROSS JOIN LATERAL jsonb_array_elements(COALESCE(s.configuration->'sites','[]'::jsonb) ||
COALESCE(r.configuration->'sites','[]'::jsonb)) site
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true'
AND ($1::uuid IS NULL OR s.id<>$1)
`, [id ?? null])
return new Set(rows.map(row => row.router_id))
}
export async function ixReservedTunnelBindings(serverId: number, excludeSegmentId?: string, sql: Pick<PoolClient, "query"> = pool) {
const { rows } = await sql.query<{ configuration: unknown }>(`
SELECT s.configuration - 'linuxBonds' AS configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
WHERE d.server_id=$1 AND ($2::uuid IS NULL OR s.id<>$2) AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
UNION ALL
SELECT r.configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
WHERE d.server_id=$1 AND ($2::uuid IS NULL OR s.id<>$2) AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
`, [serverId, excludeSegmentId ?? null])
return rows.flatMap(({ configuration }) => ixSegmentConfigurationSchema.parse(configuration).sites
.flatMap(site => site.interfaces.filter(binding => site.serverId === serverId || binding.peerServerId === serverId)))
}
export async function ixReservedLinuxPoolBlocks() {
const { rows } = await pool.query<{ address: string }>(`
SELECT DISTINCT address
FROM ix_segments s LEFT JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
CROSS JOIN LATERAL jsonb_array_elements(COALESCE(s.configuration->'sites','[]'::jsonb) ||
COALESCE(r.configuration->'sites','[]'::jsonb)) site
CROSS JOIN LATERAL jsonb_array_elements(site->'interfaces') binding
CROSS JOIN LATERAL (VALUES
(split_part(COALESCE(binding->'provisionWireguard'->>'localAddress',binding->'provisionGre'->>'localAddress'),'/',1)),
(COALESCE(binding->'provisionWireguard'->>'peerAddress',binding->'provisionGre'->>'peerAddress'))) hosts(address)
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND binding ? 'linux' AND address LIKE '10.254.%'`)
return new Set(rows.map(row => {
const [, , third, last] = row.address.split(".").map(Number)
return third * 256 + (last & ~3)
}))
}
export function nextIxRouterId(used: ReadonlySet<string>) {
const [address, mask] = (process.env.MMAPP_IX_ROUTER_ID_POOL ?? "10.255.0.0/16").split("/")
const length = Number(mask)
if (!isIPv4(address) || !Number.isInteger(length) || length < 16 || length > 30) {
throw new IxConflict("Пул Router ID должен быть IPv4-сетью с маской от /16 до /30")
}
const size = 2 ** (32 - length)
const base = address.split(".").reduce((value, part) => value * 256 + Number(part), 0)
if (base % size !== 0) throw new IxConflict("Для пула Router ID укажите адрес сети")
for (let index = 1; index < size - 1; index++) {
const value = base + index
const candidate = [value >>> 24, (value >>> 16) & 255, (value >>> 8) & 255, value & 255].join(".")
if (!used.has(candidate)) return candidate
}
throw new IxConflict("Пул Router ID IX исчерпан")
}
export async function assertIxRouterIds(id: string, configuration: IxConfiguration, sql: Pick<PoolClient, "query"> = pool) {
const used = await ixReservedRouterIds(id, sql)
const existing = await readIxSegment(id, sql)
const local = new Set<string>()
for (const site of configuration.sites) {
const unchanged = existing?.configuration.sites.some(old => old.serverId === site.serverId && old.routerId === site.routerId)
if (local.has(site.routerId) || site.routerId === "0.0.0.0" || (site.autoRouterId && !unchanged && used.has(site.routerId))) {
throw new IxConflict("Router ID " + site.routerId + " уже используется")
}
local.add(site.routerId)
}
}
export async function writeIxRevision(id: string, expected: number, configuration: IxConfiguration, actor: string, applied: boolean) {
const client = await pool.connect()
try {
await client.query("BEGIN")
await admitPartitionWriter(client)
await client.query("SELECT pg_advisory_xact_lock(hashtextextended('ix-router-id',0))")
await assertIxSites(configuration, client)
await assertIxRouterIds(id, configuration, client)
const revision = expected + 1
const { rows: [row] } = expected === 0
? await client.query<SegmentRow>(`INSERT INTO ix_segments(id,name,revision,configuration,applied_revision)
VALUES ($1,$2,$3,$4::jsonb,$5) ON CONFLICT DO NOTHING RETURNING ${columns}`,
[id, configuration.name, revision, JSON.stringify(configuration), applied ? revision : null])
: await client.query<SegmentRow>(`UPDATE ix_segments SET name=$2,revision=$3,configuration=$4::jsonb ||
CASE WHEN configuration ? 'linuxBonds' THEN jsonb_build_object('linuxBonds', configuration->'linuxBonds') ELSE '{}'::jsonb END,
applied_revision=CASE WHEN $5::boolean THEN $3 ELSE applied_revision END,updated_at=now()
WHERE id=$1 AND revision=$6 AND ${visible} RETURNING ${columns}`,
[id, configuration.name, revision, JSON.stringify(configuration), applied, expected])
if (!row) throw new IxConflict("Имя IX уже занято или ревизия сменилась")
// Keep references to the applied topology while it can still hold live resources.
const appliedConfiguration = !applied && row.applied_revision !== null
? (await client.query("SELECT configuration FROM ix_segment_revisions WHERE segment_id=$1 AND revision=$2", [id, row.applied_revision])).rows[0]?.configuration
: null
const ids = [...new Set(ixDeviceIds(configuration).concat(appliedConfiguration ? ixDeviceIds(ixSegmentConfigurationSchema.parse(appliedConfiguration)) : []))]
await client.query("DELETE FROM ix_segment_devices WHERE segment_id=$1", [id])
await client.query("INSERT INTO ix_segment_devices(segment_id,server_id) SELECT $1, unnest($2::bigint[])", [id, ids])
await client.query("INSERT INTO ix_segment_revisions(segment_id,revision,configuration,actor_id) VALUES ($1,$2,$3::jsonb,$4)",
[id, revision, JSON.stringify(configuration), actor])
await client.query("COMMIT")
return segment(row)
} catch (error) {
await client.query("ROLLBACK").catch(() => {})
if (error && typeof error === "object" && "code" in error && error.code === "23505") throw new IxConflict("Имя IX уже занято")
throw error
} finally { client.release() }
}
export async function archiveIxSegment(id: string, revision: number, actorId: string) {
const client = await pool.connect()
try {
await client.query("BEGIN")
await admitPartitionWriter(client)
// Keep the revision journal and free the name and device references using the existing writer grants.
const { rowCount } = await client.query(`UPDATE ix_segments
SET name='deleted:' || id::text, configuration=configuration || '{"deleted":true}'::jsonb, updated_at=now()
WHERE id=$1 AND revision=$2 AND ${visible}`, [id, revision])
if (rowCount !== 1) throw new IxConflict("Ревизия IX изменилась. Обновите данные и подготовьте новый план")
await client.query("DELETE FROM ix_segment_devices WHERE segment_id=$1", [id])
await audit(client, actorId, "ix.segment.deleted", null, { segmentId: id, revision })
await client.query("COMMIT")
} catch (error) {
await client.query("ROLLBACK").catch(() => {})
throw error
} finally {
client.release()
}
}
@@ -0,0 +1,94 @@
import { createHash } from "node:crypto"
import type { IxRouterObject, IxSite } from "@mmapp/contracts/internet-exchange"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
type Binding = IxSite["interfaces"][number]
export function ixTransitRemoteInterface(namespace: string, name: string) {
return namespace.slice(0, 16) + "-" + name.slice(-12)
}
export function compileIxTransit(namespace: string, site: IxSite, binding: Binding, add: (object: IxRouterObject) => void) {
const transit = binding.provisionTransit!
const serverId = binding.peerServerId!
const remote = ixTransitRemoteInterface(namespace, binding.name)
const remoteVrf = remote + "-v"
const ipv6 = transit.remoteAddress.includes(":")
const ip = ipv6 ? "/ipv6" : "/ip"
const hostMask = ipv6 ? "/128" : "/32"
const defaultPrefix = ipv6 ? "::/0" : "0.0.0.0/0"
const clients = site.interfaces.filter(item => {
const group = site.groups.find(group => group.id === item.linux?.exit)
return item.linux?.enabled && group && [group.primary.interface, group.backup?.interface].includes(binding.name)
})
const sources = [...new Set(clients.flatMap(client => [
(client.provisionWireguard ?? client.provisionGre)!.peerAddress + hostMask, ...client.prefixes,
]).map(canonicalBgpPolicyPrefix))].sort()
const hub = transit.localAddress.split("/")[0]
const mask = transit.localAddress.split("/")[1]
const key = (role: string, kind: "private" | "public") => `ix-transit:${kind}:${transit.credentialId}:${role}`
const emit = (node: number, path: string, suffix: string, fields: Record<string, string>) => add({
serverId: node, path, fields: { ...fields, comment: namespace + ":transit-" + binding.name + "-" + suffix },
})
const emitRemote = (path: string, suffix: string, fields: Record<string, string>) => emit(serverId, path, suffix, fields)
emitRemote("/interface/wireguard", "wg", {
name: remote, "listen-port": String(transit.remotePort), "private-key": key("b", "private"),
})
emitRemote("/ip/vrf", "vrf", { name: remoteVrf, interfaces: remote })
emitRemote(ip + "/address", "address", { interface: remote, address: transit.remoteAddress + "/" + mask,
...(ipv6 && { advertise: "no" }) })
emitRemote("/interface/wireguard/peers", "peer", {
interface: remote, "public-key": key("a", "public"), "allowed-address": [hub + hostMask, ...sources].join(","),
"endpoint-address": transit.localEndpoint, "endpoint-port": String(transit.localPort), "persistent-keepalive": "25s",
})
emitRemote(ip + "/route", "default", { "routing-table": remoteVrf, "dst-address": defaultPrefix,
gateway: transit.remoteWan.nextHop + "%" + transit.remoteWan.interface + "@main",
})
emitRemote(ip + "/route", "default-drop", { "routing-table": remoteVrf, "dst-address": defaultPrefix, blackhole: "yes", distance: "254" })
const filter = ip + "/firewall/filter"
const srcList = remote + "-src"
emitRemote("/ip/firewall/filter", "listen", { chain: "input", protocol: "udp", "src-address": transit.localEndpoint + "/32",
"dst-address": transit.remoteEndpoint + "/32", "dst-port": String(transit.remotePort), action: "accept" })
emitRemote(filter, "ping", { chain: "input", "in-interface": remoteVrf, protocol: ipv6 ? "icmpv6" : "icmp", "src-address": hub + hostMask, action: "accept" })
emitRemote(filter, "deny-management", { chain: "input", "in-interface": remoteVrf, action: "drop" })
emitRemote(filter, "out", { chain: "forward", "in-interface": remoteVrf, "out-interface": transit.remoteWan.interface,
"src-address-list": srcList, action: "accept" })
emitRemote(filter, "return-filter", {
chain: "forward", "dst-address-list": srcList, "connection-state": "established,related", action: "accept",
})
emitRemote(filter, "deny-forward", { chain: "forward", "in-interface": remoteVrf, action: "drop" })
emitRemote(filter, "deny-inbound", { chain: "forward", "dst-address-list": srcList, action: "drop" })
if (!ipv6) emitRemote("/ip/firewall/nat", "nat", { chain: "srcnat", "out-interface": transit.remoteWan.interface,
"src-address-list": srcList, action: "masquerade" })
for (const address of [hub + hostMask, ...sources]) {
const identity = createHash("sha256").update(address).digest("hex").slice(0, 12)
emitRemote(ip + "/firewall/address-list", "client-" + identity, { address, list: srcList })
for (const table of address === hub + hostMask ? ["main"] : [remoteVrf, "main"]) emitRemote(ip + "/route", "return-" + table + "-" + identity, {
"routing-table": table, "dst-address": address, gateway: hub + "%" + remote + "@" + remoteVrf,
})
}
emit(site.serverId, "/interface/wireguard", "source-wg", {
name: binding.name, "listen-port": String(transit.localPort), "private-key": key("a", "private"),
})
// Source peer/address depend on the local VRF assignment and are emitted by the caller.
}
export function ixTransitSourceObjects(namespace: string, site: IxSite, binding: Binding): IxRouterObject[] {
const transit = binding.provisionTransit!
const ipv6 = transit.remoteAddress.includes(":")
return [
{ serverId: site.serverId, path: ipv6 ? "/ipv6/address" : "/ip/address", fields: { address: transit.localAddress, interface: binding.name,
...(ipv6 && { advertise: "no" }),
comment: namespace + ":transit-" + binding.name + "-source-address" } },
{ serverId: site.serverId, path: "/interface/wireguard/peers", fields: {
interface: binding.name, "public-key": `ix-transit:public:${transit.credentialId}:b`, "allowed-address": ipv6 ? "::/0" : "0.0.0.0/0",
"endpoint-address": transit.remoteEndpoint, "endpoint-port": String(transit.remotePort), "persistent-keepalive": "25s",
comment: namespace + ":transit-" + binding.name + "-source-peer",
} },
{ serverId: site.serverId, path: "/ip/firewall/filter", fields: {
chain: "input", action: "accept", protocol: "udp", "src-address": transit.remoteEndpoint + "/32",
"dst-address": transit.localEndpoint + "/32", "dst-port": String(transit.localPort),
comment: namespace + ":transit-" + binding.name + "-source-listen",
} },
]
}
@@ -47,7 +47,7 @@ async function getSettingsRow() {
retentionDays: 14, retentionDays: 14,
createdAt: now, createdAt: now,
updatedAt: now, updatedAt: now,
}) }).onConflictDoNothing({ target: internetPathSettings.id })
return (await db.select().from(internetPathSettings).where(eq(internetPathSettings.id, 1)).limit(1))[0] return (await db.select().from(internetPathSettings).where(eq(internetPathSettings.id, 1)).limit(1))[0]
} }
@@ -0,0 +1,42 @@
import assert from "node:assert/strict"
import { readFileSync } from "node:fs"
import { test } from "node:test"
import { ixBondBundleSchema, type IxSite } from "@mmapp/contracts/internet-exchange"
import { ixGreClientTemplate, ixWireguardClientTemplate } from "./internet-exchange-client.js"
const bundle = ixBondBundleSchema.parse(JSON.parse(readFileSync(
new URL("../../../packages/contracts/testdata/ix-bond-v1.json", import.meta.url), "utf8")))
test("the shared ix-client fixture accepts weighted members and rejects overlapping tunnel addresses", () => {
assert.deepEqual(bundle.members.map(path => path.weight), [3, 1])
const changed = structuredClone(bundle)
changed.members[0].probe = changed.members[1].address
assert.equal(ixBondBundleSchema.safeParse(changed).success, false)
const invalidKey = structuredClone(bundle)
invalidKey.members[0].peerPublicKey = "B".repeat(43) + "="
assert.equal(ixBondBundleSchema.safeParse(invalidKey).success, false)
})
test("group transport brings up an encrypted link without claiming routes used by other members", () => {
const [wg, gre] = bundle.members
const linux = { name: bundle.name, enabled: true, exit: "wan", destinations: [], peerEndpoint: "192.0.2.99" }
const binding: IxSite["interfaces"][number] = {
name: "wg-test", kind: "wireguard", linux, prefixes: [], provisionWireguard: {
listenPort: 51820, endpointPort: 51820, localAddress: wg.probe + "/30", peerAddress: wg.address,
hubEndpoint: wg.endpoint, peerPublicKey: wg.peerPublicKey!,
},
}
const wgConfig = ixWireguardClientTemplate(binding, wg.peerPublicKey!, bundle.destinations, undefined, true)
assert.match(wgConfig, /Table = off/)
assert.doesNotMatch(wgConfig, /PostUp|PreDown/)
assert.match(wgConfig, /0\.0\.0\.0\/0/)
assert.match(ixWireguardClientTemplate(binding, wg.peerPublicKey!, bundle.destinations), /Table = auto/)
const greConfig = ixGreClientTemplate({ name: "gre-test", kind: "gre-ipsec", linux, prefixes: [],
localEndpoint: gre.endpoint, endpoint: linux.peerEndpoint, provisionGre: {
localAddress: gre.probe + "/30", peerAddress: gre.address, credentialId: bundle.id,
} }, 17, undefined, undefined, true)
assert.match(greConfig.template, /start_action = trap/)
assert.match(greConfig.setup, /systemctl enable --now ix-gre-/)
assert.match(greConfig.setup, /ExecStart=.*ip address add 10\.123\.2\.2\/32/)
assert.doesNotMatch(greConfig.setup, /ip -[46] rule|route replace|secret =/)
})
@@ -0,0 +1,26 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { createIxImportLinks, type IxImportBundle } from "./ix-import-links.js"
const bundle: IxImportBundle = { version: 1, kind: "wireguard", name: "ixw000000000000", config: "fixture" }
test("only one concurrent request can claim a link", async () => {
const links = createIxImportLinks(() => 10)
let reads = 0
const code = links.issue(20, async () => { reads++; return bundle })
assert.match(code, /^[A-Za-z0-9_-]{32}$/)
const responses = await Promise.allSettled([links.redeem(code), links.redeem(code)])
assert.deepEqual(responses[0], { status: "fulfilled", value: bundle })
assert.equal(responses[1].status, "rejected")
assert.equal(reads, 1)
})
test("expiry is enforced before and after loading the bundle", async () => {
let now = 10
const links = createIxImportLinks(() => now)
const expired = links.issue(20, async () => { assert.fail("expired link read its source") })
const tooSlow = links.issue(30, async () => { now = 31; return bundle })
now = 20
await assert.rejects(links.redeem(expired), /истекла/)
await assert.rejects(links.redeem(tooSlow), /истекла/)
})
+39
View File
@@ -0,0 +1,39 @@
import { createHash, randomBytes } from "node:crypto"
import { performance } from "node:perf_hooks"
import type { IxBondBundle } from "@mmapp/contracts/internet-exchange"
import { IxConflict } from "./internet-exchange-plan.js"
export type IxImportGre = { local: string; remote: string; address: string; psk: string }
export type IxImportBundle =
| { version: 1; kind: "wireguard"; name: string; config: string }
| { version: 1; kind: "gre-ipsec"; name: string; gre: IxImportGre }
| { version: 1; kind: "bond"; bond: IxBondBundle }
const digest = (code: string) => createHash("sha256").update(code).digest("hex")
const maxLinks = 256
const expired = () => new IxConflict("Ссылка истекла или уже использована", 410)
export function createIxImportLinks(now = () => performance.now()) {
const links = new Map<string, { deadline: number; load: () => Promise<IxImportBundle> }>()
return {
issue(deadline: number, load: () => Promise<IxImportBundle>) {
const current = now()
for (const [key, entry] of links) if (entry.deadline <= current) links.delete(key)
if (deadline <= current) throw expired()
if (links.size >= maxLinks) throw new IxConflict("Слишком много активных ссылок импорта", 429)
const code = randomBytes(24).toString("base64url")
// shortcut: pending links live in this backend process, use shared storage if the backend is replicated.
links.set(digest(code), { deadline, load })
return code
},
async redeem(code: string) {
const key = digest(code), entry = links.get(key)
links.delete(key)
if (!entry || entry.deadline <= now()) throw expired()
const bundle = await entry.load()
if (entry.deadline <= now()) throw expired()
return bundle
},
}
}
Loaded 100 of 236 files, more files were not shown because too many files have changed in this diff. Show more