diff --git a/README.md b/README.md index f11196f77..a4bfb9fe8 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Pangolin is an open-source, identity-based remote access platform built on WireG ## Deployment Options -- **Pangolin Cloud** — Fully managed service - no infrastructure required. -- **Self-Host: Community Edition** — Free, open source, and licensed under AGPL-3. -- **Self-Host: Enterprise Edition** — Licensed under Fossorial Commercial License. Free for personal and hobbyist use, and for businesses making less than \$100K USD gross annual revenue. +- **Pangolin Cloud** - Fully managed service - no infrastructure required. +- **Self-Host: Community Edition** - Free, open source, and licensed under AGPL-3. +- **Self-Host: Enterprise Edition** - Licensed under Fossorial Commercial License. Free for personal and hobbyist use, and for businesses making less than \$100K USD gross annual revenue. ## Key Features diff --git a/bruno/API Keys/Create API Key.bru b/bruno/API Keys/Create API Key.bru deleted file mode 100644 index 009b4b049..000000000 --- a/bruno/API Keys/Create API Key.bru +++ /dev/null @@ -1,17 +0,0 @@ -meta { - name: Create API Key - type: http - seq: 1 -} - -put { - url: http://localhost:3000/api/v1/api-key - body: json - auth: inherit -} - -body:json { - { - "isRoot": true - } -} diff --git a/bruno/API Keys/Delete API Key.bru b/bruno/API Keys/Delete API Key.bru deleted file mode 100644 index 9285f7889..000000000 --- a/bruno/API Keys/Delete API Key.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: Delete API Key - type: http - seq: 2 -} - -delete { - url: http://localhost:3000/api/v1/api-key/dm47aacqxxn3ubj - body: none - auth: inherit -} diff --git a/bruno/API Keys/List API Key Actions.bru b/bruno/API Keys/List API Key Actions.bru deleted file mode 100644 index ae5b721e1..000000000 --- a/bruno/API Keys/List API Key Actions.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: List API Key Actions - type: http - seq: 6 -} - -get { - url: http://localhost:3000/api/v1/api-key/ex0izu2c37fjz9x/actions - body: none - auth: inherit -} diff --git a/bruno/API Keys/List Org API Keys.bru b/bruno/API Keys/List Org API Keys.bru deleted file mode 100644 index 468e964b9..000000000 --- a/bruno/API Keys/List Org API Keys.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: List Org API Keys - type: http - seq: 4 -} - -get { - url: http://localhost:3000/api/v1/org/home-lab/api-keys - body: none - auth: inherit -} diff --git a/bruno/API Keys/List Root API Keys.bru b/bruno/API Keys/List Root API Keys.bru deleted file mode 100644 index 8ef31b68c..000000000 --- a/bruno/API Keys/List Root API Keys.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: List Root API Keys - type: http - seq: 3 -} - -get { - url: http://localhost:3000/api/v1/root/api-keys - body: none - auth: inherit -} diff --git a/bruno/API Keys/Set API Key Actions.bru b/bruno/API Keys/Set API Key Actions.bru deleted file mode 100644 index 54a35c438..000000000 --- a/bruno/API Keys/Set API Key Actions.bru +++ /dev/null @@ -1,17 +0,0 @@ -meta { - name: Set API Key Actions - type: http - seq: 5 -} - -post { - url: http://localhost:3000/api/v1/api-key/ex0izu2c37fjz9x/actions - body: json - auth: inherit -} - -body:json { - { - "actionIds": ["listSites"] - } -} diff --git a/bruno/API Keys/Set API Key Orgs.bru b/bruno/API Keys/Set API Key Orgs.bru deleted file mode 100644 index 3f0676c5b..000000000 --- a/bruno/API Keys/Set API Key Orgs.bru +++ /dev/null @@ -1,17 +0,0 @@ -meta { - name: Set API Key Orgs - type: http - seq: 7 -} - -post { - url: http://localhost:3000/api/v1/api-key/ex0izu2c37fjz9x/orgs - body: json - auth: inherit -} - -body:json { - { - "orgIds": ["home-lab"] - } -} diff --git a/bruno/API Keys/folder.bru b/bruno/API Keys/folder.bru deleted file mode 100644 index bb8cd5c73..000000000 --- a/bruno/API Keys/folder.bru +++ /dev/null @@ -1,3 +0,0 @@ -meta { - name: API Keys -} diff --git a/bruno/Auth/2fa-disable.bru b/bruno/Auth/2fa-disable.bru deleted file mode 100644 index c98539c73..000000000 --- a/bruno/Auth/2fa-disable.bru +++ /dev/null @@ -1,18 +0,0 @@ -meta { - name: 2fa-disable - type: http - seq: 6 -} - -post { - url: http://localhost:3000/api/v1/auth/2fa/disable - body: json - auth: none -} - -body:json { - { - "password": "aaaaa-1A", - "code": "377289" - } -} diff --git a/bruno/Auth/2fa-enable.bru b/bruno/Auth/2fa-enable.bru deleted file mode 100644 index a3a01d177..000000000 --- a/bruno/Auth/2fa-enable.bru +++ /dev/null @@ -1,17 +0,0 @@ -meta { - name: 2fa-enable - type: http - seq: 4 -} - -post { - url: http://localhost:3000/api/v1/auth/2fa/enable - body: json - auth: none -} - -body:json { - { - "code": "374138" - } -} diff --git a/bruno/Auth/2fa-request.bru b/bruno/Auth/2fa-request.bru deleted file mode 100644 index fcf0c9862..000000000 --- a/bruno/Auth/2fa-request.bru +++ /dev/null @@ -1,17 +0,0 @@ -meta { - name: 2fa-request - type: http - seq: 5 -} - -post { - url: http://localhost:3000/api/v1/auth/2fa/request - body: json - auth: none -} - -body:json { - { - "password": "aaaaa-1A" - } -} diff --git a/bruno/Auth/change-password.bru b/bruno/Auth/change-password.bru deleted file mode 100644 index 7d1c707e5..000000000 --- a/bruno/Auth/change-password.bru +++ /dev/null @@ -1,18 +0,0 @@ -meta { - name: change-password - type: http - seq: 9 -} - -post { - url: http://localhost:3000/api/v1/auth/change-password - body: json - auth: none -} - -body:json { - { - "oldPassword": "", - "newPassword": "" - } -} diff --git a/bruno/Auth/login.bru b/bruno/Auth/login.bru deleted file mode 100644 index 3825a2525..000000000 --- a/bruno/Auth/login.bru +++ /dev/null @@ -1,18 +0,0 @@ -meta { - name: login - type: http - seq: 1 -} - -post { - url: http://localhost:3000/api/v1/auth/login - body: json - auth: none -} - -body:json { - { - "email": "admin@fosrl.io", - "password": "Password123!" - } -} diff --git a/bruno/Auth/logout.bru b/bruno/Auth/logout.bru deleted file mode 100644 index 623cd47fe..000000000 --- a/bruno/Auth/logout.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: logout - type: http - seq: 3 -} - -post { - url: http://localhost:4000/api/v1/auth/logout - body: none - auth: none -} diff --git a/bruno/Auth/reset-password-request.bru b/bruno/Auth/reset-password-request.bru deleted file mode 100644 index 29c3b89d1..000000000 --- a/bruno/Auth/reset-password-request.bru +++ /dev/null @@ -1,17 +0,0 @@ -meta { - name: reset-password-request - type: http - seq: 10 -} - -post { - url: http://localhost:3000/api/v1/auth/reset-password/request - body: json - auth: none -} - -body:json { - { - "email": "milo@pangolin.net" - } -} diff --git a/bruno/Auth/reset-password.bru b/bruno/Auth/reset-password.bru deleted file mode 100644 index 8d567b164..000000000 --- a/bruno/Auth/reset-password.bru +++ /dev/null @@ -1,19 +0,0 @@ -meta { - name: reset-password - type: http - seq: 11 -} - -post { - url: http://localhost:3000/api/v1/auth/reset-password - body: json - auth: none -} - -body:json { - { - "token": "3uhsbom72dwdhboctwrtntyd6jrlg4jtf5oaxy4k", - "newPassword": "aaaaa-1A", - "code": "6irqCGR3" - } -} diff --git a/bruno/Auth/signup.bru b/bruno/Auth/signup.bru deleted file mode 100644 index bec59235e..000000000 --- a/bruno/Auth/signup.bru +++ /dev/null @@ -1,18 +0,0 @@ -meta { - name: signup - type: http - seq: 2 -} - -put { - url: http://localhost:3000/api/v1/auth/signup - body: json - auth: none -} - -body:json { - { - "email": "numbat@pangolin.net", - "password": "Password123!" - } -} diff --git a/bruno/Auth/verify-email-request.bru b/bruno/Auth/verify-email-request.bru deleted file mode 100644 index 72189d1b2..000000000 --- a/bruno/Auth/verify-email-request.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: verify-email-request - type: http - seq: 8 -} - -post { - url: http://localhost:3000/api/v1/auth/verify-email/request - body: none - auth: none -} diff --git a/bruno/Auth/verify-email.bru b/bruno/Auth/verify-email.bru deleted file mode 100644 index a06a7108c..000000000 --- a/bruno/Auth/verify-email.bru +++ /dev/null @@ -1,17 +0,0 @@ -meta { - name: verify-email - type: http - seq: 7 -} - -post { - url: http://localhost:3000/api/v1/auth/verify-email - body: json - auth: none -} - -body:json { - { - "code": "50317187" - } -} diff --git a/bruno/Auth/verify-user.bru b/bruno/Auth/verify-user.bru deleted file mode 100644 index 38955449d..000000000 --- a/bruno/Auth/verify-user.bru +++ /dev/null @@ -1,15 +0,0 @@ -meta { - name: verify-user - type: http - seq: 4 -} - -get { - url: http://localhost:3001/api/v1/badger/verify-user?sessionId=mb52273jkb6t3oys2bx6ur5x7rcrkl26c7warg3e - body: none - auth: none -} - -params:query { - sessionId: mb52273jkb6t3oys2bx6ur5x7rcrkl26c7warg3e -} diff --git a/bruno/Clients/createClient.bru b/bruno/Clients/createClient.bru deleted file mode 100644 index 7577bb280..000000000 --- a/bruno/Clients/createClient.bru +++ /dev/null @@ -1,22 +0,0 @@ -meta { - name: createClient - type: http - seq: 1 -} - -put { - url: http://localhost:3000/api/v1/site/1/client - body: json - auth: none -} - -body:json { - { - "siteId": 1, - "name": "test", - "type": "olm", - "subnet": "100.90.129.4/30", - "olmId": "029yzunhx6nh3y5", - "secret": "l0ymp075y3d4rccb25l6sqpgar52k09etunui970qq5gj7x6" - } -} diff --git a/bruno/Clients/pickClientDefaults.bru b/bruno/Clients/pickClientDefaults.bru deleted file mode 100644 index 61509c112..000000000 --- a/bruno/Clients/pickClientDefaults.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: pickClientDefaults - type: http - seq: 2 -} - -get { - url: http://localhost:3000/api/v1/site/1/pick-client-defaults - body: none - auth: none -} diff --git a/bruno/IDP/Create OIDC Provider.bru b/bruno/IDP/Create OIDC Provider.bru deleted file mode 100644 index 23e807cf9..000000000 --- a/bruno/IDP/Create OIDC Provider.bru +++ /dev/null @@ -1,22 +0,0 @@ -meta { - name: Create OIDC Provider - type: http - seq: 1 -} - -put { - url: http://localhost:3000/api/v1/org/home-lab/idp/oidc - body: json - auth: inherit -} - -body:json { - { - "clientId": "JJoSvHCZcxnXT2sn6CObj6a21MuKNRXs3kN5wbys", - "clientSecret": "2SlGL2wOGgMEWLI9yUuMAeFxre7qSNJVnXMzyepdNzH1qlxYnC4lKhhQ6a157YQEkYH3vm40KK4RCqbYiF8QIweuPGagPX3oGxEj2exwutoXFfOhtq4hHybQKoFq01Z3", - "authUrl": "http://localhost:9000/application/o/authorize/", - "tokenUrl": "http://localhost:9000/application/o/token/", - "scopes": ["email", "openid", "profile"], - "userIdentifier": "email" - } -} diff --git a/bruno/IDP/Generate OIDC URL.bru b/bruno/IDP/Generate OIDC URL.bru deleted file mode 100644 index 90443096f..000000000 --- a/bruno/IDP/Generate OIDC URL.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: Generate OIDC URL - type: http - seq: 2 -} - -get { - url: http://localhost:3000/api/v1 - body: none - auth: inherit -} diff --git a/bruno/IDP/folder.bru b/bruno/IDP/folder.bru deleted file mode 100644 index fc1369159..000000000 --- a/bruno/IDP/folder.bru +++ /dev/null @@ -1,3 +0,0 @@ -meta { - name: IDP -} diff --git a/bruno/Internal/Traefik Config.bru b/bruno/Internal/Traefik Config.bru deleted file mode 100644 index 9fc1c1dcb..000000000 --- a/bruno/Internal/Traefik Config.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: Traefik Config - type: http - seq: 1 -} - -get { - url: http://localhost:3001/api/v1/traefik-config - body: none - auth: inherit -} diff --git a/bruno/Internal/folder.bru b/bruno/Internal/folder.bru deleted file mode 100644 index 702931ec4..000000000 --- a/bruno/Internal/folder.bru +++ /dev/null @@ -1,3 +0,0 @@ -meta { - name: Internal -} diff --git a/bruno/Newt/Create Newt.bru b/bruno/Newt/Create Newt.bru deleted file mode 100644 index 56baf89bd..000000000 --- a/bruno/Newt/Create Newt.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: Create Newt - type: http - seq: 2 -} - -get { - url: http://localhost:3000/api/v1/newt - body: none - auth: none -} diff --git a/bruno/Newt/Get Token.bru b/bruno/Newt/Get Token.bru deleted file mode 100644 index 93d91cc5d..000000000 --- a/bruno/Newt/Get Token.bru +++ /dev/null @@ -1,18 +0,0 @@ -meta { - name: Get Token - type: http - seq: 1 -} - -get { - url: http://localhost:3000/api/v1/auth/newt/get-token - body: json - auth: none -} - -body:json { - { - "newtId": "o0d4rdxq3stnz7b", - "secret": "sy7l09fnaesd03iwrfp9m3qf0ryn19g0zf3dqieaazb4k7vk" - } -} diff --git a/bruno/Olm/createOlm.bru b/bruno/Olm/createOlm.bru deleted file mode 100644 index ca755dea8..000000000 --- a/bruno/Olm/createOlm.bru +++ /dev/null @@ -1,15 +0,0 @@ -meta { - name: createOlm - type: http - seq: 1 -} - -put { - url: http://localhost:3000/api/v1/olm - body: none - auth: inherit -} - -settings { - encodeUrl: true -} diff --git a/bruno/Olm/folder.bru b/bruno/Olm/folder.bru deleted file mode 100644 index d245e6d1c..000000000 --- a/bruno/Olm/folder.bru +++ /dev/null @@ -1,8 +0,0 @@ -meta { - name: Olm - seq: 15 -} - -auth { - mode: inherit -} diff --git a/bruno/Orgs/Check Id.bru b/bruno/Orgs/Check Id.bru deleted file mode 100644 index 17b63953c..000000000 --- a/bruno/Orgs/Check Id.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: Check Id - type: http - seq: 2 -} - -get { - url: http://localhost:3000/api/v1/org/checkId - body: none - auth: none -} diff --git a/bruno/Orgs/listOrgs.bru b/bruno/Orgs/listOrgs.bru deleted file mode 100644 index 89c34d0cb..000000000 --- a/bruno/Orgs/listOrgs.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: listOrgs - type: http - seq: 1 -} - -get { - url: - body: none - auth: none -} diff --git a/bruno/Remote Exit Node/createRemoteExitNode.bru b/bruno/Remote Exit Node/createRemoteExitNode.bru deleted file mode 100644 index 1c749a311..000000000 --- a/bruno/Remote Exit Node/createRemoteExitNode.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: createRemoteExitNode - type: http - seq: 1 -} - -put { - url: http://localhost:4000/api/v1/org/org_i21aifypnlyxur2/remote-exit-node - body: none - auth: none -} diff --git a/bruno/Resources/listResourcesByOrg.bru b/bruno/Resources/listResourcesByOrg.bru deleted file mode 100644 index 6efce1b20..000000000 --- a/bruno/Resources/listResourcesByOrg.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: listResourcesByOrg - type: http - seq: 1 -} - -get { - url: - body: none - auth: none -} diff --git a/bruno/Resources/listResourcesBySite.bru b/bruno/Resources/listResourcesBySite.bru deleted file mode 100644 index 81c9cf99b..000000000 --- a/bruno/Resources/listResourcesBySite.bru +++ /dev/null @@ -1,16 +0,0 @@ -meta { - name: listResourcesBySite - type: http - seq: 2 -} - -get { - url: http://localhost:3000/api/v1/site/1/resources?limit=10&offset=0 - body: none - auth: none -} - -params:query { - limit: 10 - offset: 0 -} diff --git a/bruno/Sites/Get Site.bru b/bruno/Sites/Get Site.bru deleted file mode 100644 index fc2f7e62b..000000000 --- a/bruno/Sites/Get Site.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: Get Site - type: http - seq: 2 -} - -get { - url: http://localhost:3000/api/v1/org/test/sites/mexican-mole-lizard-windy - body: none - auth: none -} diff --git a/bruno/Sites/listSites.bru b/bruno/Sites/listSites.bru deleted file mode 100644 index b7912330a..000000000 --- a/bruno/Sites/listSites.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: listSites - type: http - seq: 1 -} - -get { - url: - body: none - auth: none -} diff --git a/bruno/Targets/listTargets.bru b/bruno/Targets/listTargets.bru deleted file mode 100644 index 7981eb453..000000000 --- a/bruno/Targets/listTargets.bru +++ /dev/null @@ -1,16 +0,0 @@ -meta { - name: listTargets - type: http - seq: 1 -} - -get { - url: http://localhost:3000/api/v1/resource/web.main.localhost/targets?limit=10&offset=0 - body: none - auth: none -} - -params:query { - limit: 10 - offset: 0 -} diff --git a/bruno/Test.bru b/bruno/Test.bru deleted file mode 100644 index 16286ec8c..000000000 --- a/bruno/Test.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: Test - type: http - seq: 2 -} - -get { - url: http://localhost:3000/api/v1 - body: none - auth: inherit -} diff --git a/bruno/Traefik/traefik-config.bru b/bruno/Traefik/traefik-config.bru deleted file mode 100644 index a50b7aa15..000000000 --- a/bruno/Traefik/traefik-config.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: traefik-config - type: http - seq: 1 -} - -get { - url: http://localhost:3001/api/v1/traefik-config - body: none - auth: none -} diff --git a/bruno/Users/adminListUsers.bru b/bruno/Users/adminListUsers.bru deleted file mode 100644 index cdc410956..000000000 --- a/bruno/Users/adminListUsers.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: adminListUsers - type: http - seq: 2 -} - -get { - url: http://localhost:3000/api/v1/users - body: none - auth: none -} diff --git a/bruno/Users/adminRemoveUser.bru b/bruno/Users/adminRemoveUser.bru deleted file mode 100644 index 9e9f35079..000000000 --- a/bruno/Users/adminRemoveUser.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: adminRemoveUser - type: http - seq: 3 -} - -delete { - url: http://localhost:3000/api/v1/user/ky5r7ivqs8wc7u4 - body: none - auth: none -} diff --git a/bruno/Users/getUser.bru b/bruno/Users/getUser.bru deleted file mode 100644 index d86372527..000000000 --- a/bruno/Users/getUser.bru +++ /dev/null @@ -1,11 +0,0 @@ -meta { - name: getUser - type: http - seq: 1 -} - -get { - url: - body: none - auth: none -} diff --git a/bruno/bruno.json b/bruno/bruno.json deleted file mode 100644 index f19d936a8..000000000 --- a/bruno/bruno.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "version": "1", - "name": "Pangolin", - "type": "collection", - "ignore": [ - "node_modules", - ".git" - ], - "presets": { - "requestType": "http", - "requestUrl": "http://localhost:3000/api/v1" - } -} \ No newline at end of file diff --git a/docker-compose.pgr.yml b/docker-compose.pgr.yml index 9e6b2c5af..764c09150 100644 --- a/docker-compose.pgr.yml +++ b/docker-compose.pgr.yml @@ -7,8 +7,8 @@ services: POSTGRES_DB: postgres # Default database name POSTGRES_USER: postgres # Default user POSTGRES_PASSWORD: password # Default password (change for production!) - # volumes: - # - ./config/postgres:/var/lib/postgresql/data + volumes: + - ./config/postgres:/var/lib/postgresql/data ports: - "5432:5432" # Map host port 5432 to container port 5432 restart: no diff --git a/license_header_checker.py b/license_header_checker.py index c173d693b..ab7ddf4d5 100644 --- a/license_header_checker.py +++ b/license_header_checker.py @@ -96,7 +96,7 @@ def process_directory(root_dir): if has_correct_header: print(f"Header up-to-date: {file_path}") else: - # Either no header exists or the header is outdated — write + # Either no header exists or the header is outdated - write # the correct one. action = "Replaced header in" if has_any_header else "Added header to" new_content = HEADER_NORMALIZED + '\n\n' + body @@ -106,7 +106,7 @@ def process_directory(root_dir): files_modified += 1 else: if has_any_header: - # Remove the header — it shouldn't be here. + # Remove the header - it shouldn't be here. with open(file_path, 'w', encoding='utf-8') as f: f.write(body) print(f"Removed header from: {file_path}") @@ -134,4 +134,4 @@ if __name__ == "__main__": print(f"Error: Directory '{target_directory}' not found.") sys.exit(1) - process_directory(os.path.abspath(target_directory)) \ No newline at end of file + process_directory(os.path.abspath(target_directory)) diff --git a/messages/bg-BG.json b/messages/bg-BG.json index aec6f718c..bf953e4d4 100644 --- a/messages/bg-BG.json +++ b/messages/bg-BG.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "Свържете се с отдел продажби, за да активирате тази функция.", + "contactSalesBookDemo": "Резервирайте демонстрация", + "contactSalesOr": "или", + "contactSalesContactUs": "свържете се с нас", "setupCreate": "Създайте организацията, сайта и ресурсите", "headerAuthCompatibilityInfo": "Активирайте това, за да принудите отговор '401 Неупълномощено', когато липсва токен за автентификация. Това е необходимо за браузъри или специфични HTTP библиотеки, които не изпращат идентификационни данни без сървърно предизвикателство.", "headerAuthCompatibility": "Разширена съвместимост.", @@ -19,6 +23,14 @@ "componentsInvalidKey": "Засечен е невалиден или изтекъл лиценз. Проверете лицензионните условия, за да се възползвате от всички функционалности.", "dismiss": "Отхвърляне", "subscriptionViolationMessage": "Превишихте ограничението на текущия си план. Коригирайте проблема, като премахнете сайтове, потребители или други ресурси, за да оставате в рамките на плана си.", + "trialBannerMessage": "Пробният Ви период изтича след {countdown}. Актуализирайте за запазване на достъпа.", + "trialBannerExpired": "Пробният Ви период е изтекъл. Актуализирайте сега, за да възстановите достъпа.", + "trialActive": "Активен пробен период", + "trialExpired": "Пробният период е изтекъл", + "trialHasEnded": "Пробният Ви период е приключил.", + "trialDaysRemaining": "{count, plural, one {# ден остава} other {# дни остават}}", + "trialDaysLeftShort": "{days}д остават до края на пробния период", + "trialGoToBilling": "Отидете на страницата за фактуриране", "subscriptionViolationViewBilling": "Преглед на фактурирането", "componentsLicenseViolation": "Нарушение на лиценза: Сървърът използва {usedSites} сайта, което надвишава лицензионния лимит от {maxSites} сайта. Проверете лицензионните условия, за да се възползвате от всички функционалности.", "componentsSupporterMessage": "Благодарим ви, че подкрепяте Pangolin като {tier}!", @@ -267,8 +279,11 @@ "orgMissing": "Липсва идентификатор на организация", "orgMissingMessage": "Невъзможност за регенериране на покана без идентификатор на организация.", "accessUsersManage": "Управление на потребители", + "accessUserManage": "Управление на потребител", "accessUsersDescription": "Канете и управлявайте потребители с достъп до тази организация", "accessUsersSearch": "Търсене на потребители...", + "accessUsersRoleFilterCount": "{count, plural, one {# роля} other {# роли}}", + "accessUsersRoleFilterClear": "Изчистване на филтрите за роли", "accessUserCreate": "Създайте потребител", "accessUserRemove": "Премахнете потребител", "username": "Потребителско име", @@ -1257,6 +1272,7 @@ "actionViewLogs": "Преглед на дневници", "noneSelected": "Нищо не е избрано", "orgNotFound2": "Няма намерени организации.", + "search": "Търси…", "searchPlaceholder": "Търсене...", "emptySearchOptions": "Няма намерени опции", "create": "Създаване", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "Управление.", "sidebarLogAndAnalytics": "Лог & Анализи", "sidebarBluePrints": "Чертежи", + "sidebarAlerting": "Извеждане на предупреждения", + "sidebarHealthChecks": "Проверки на състоянието", "sidebarOrganization": "Организация", "sidebarManagement": "Управление", "sidebarBillingAndLicenses": "Фактуриране & Лицензи", "sidebarLogsAnalytics": "Анализи", + "alertingTitle": "Извеждане на предупреждения", + "alertingDescription": "Определете източници, тригери и действия за уведомления", + "alertingRules": "Правила за предупреждение", + "alertingSearchRules": "Търсене на правила…", + "alertingAddRule": "Създаване на правило", + "alertingColumnSource": "Източник", + "alertingColumnTrigger": "Тригер", + "alertingColumnActions": "Действия", + "alertingColumnEnabled": "Активирано", + "alertingDeleteQuestion": "Моля, потвърдете, че искате да изтриете това правило за предупреждение.", + "alertingDeleteRule": "Изтриване на правило за предупреждение", + "alertingRuleDeleted": "Правилото за предупреждение е изтрито", + "alertingRuleSaved": "Правилото за предупреждение е запазено", + "alertingRuleSavedCreatedDescription": "Вашето ново правило за предупреждение беше създадено. Все още можете да го редактирате на тази страница.", + "alertingRuleSavedUpdatedDescription": "Промените, направени по това правило за предупреждение, бяха запазени.", + "alertingEditRule": "Редактиране на правило за предупреждение", + "alertingCreateRule": "Създаване на правило за предупреждение", + "alertingRuleCredenzaDescription": "Изберете какво да наблюдавате, кога да се активира и как да уведомите", + "alertingRuleNamePlaceholder": "Сайтът на производство е недостъпен", + "alertingRuleEnabled": "Правилото е активирано", + "alertingSectionSource": "Източник", + "alertingSourceType": "Тип на източника", + "alertingSourceSite": "Сайт", + "alertingSourceHealthCheck": "Проверка на състоянието", + "alertingPickSites": "Сайтове", + "alertingPickHealthChecks": "Проверки на състоянието", + "alertingPickResources": "Ресурси", + "alertingAllSites": "Всички сайтове", + "alertingAllSitesDescription": "Предупреждението се активира за всеки сайт", + "alertingSpecificSites": "Специфични сайтове", + "alertingSpecificSitesDescription": "Изберете специфични сайтове за наблюдение", + "alertingAllHealthChecks": "Всички проверки на състоянието", + "alertingAllHealthChecksDescription": "Предупреждението се активира за всяка проверка на състоянието", + "alertingSpecificHealthChecks": "Специфични проверки на състоянието", + "alertingSpecificHealthChecksDescription": "Изберете специфични проверки на състоянието за наблюдение", + "alertingAllResources": "Всички ресурси", + "alertingAllResourcesDescription": "Предупреждението се активира за всеки ресурс", + "alertingSpecificResources": "Специфични ресурси", + "alertingSpecificResourcesDescription": "Изберете специфични ресурси за наблюдение", + "alertingSelectResources": "Изберете ресурси…", + "alertingResourcesSelected": "Избрани {count} ресурса", + "alertingResourcesEmpty": "Няма ресурси с целите в първите 10 резултата.", + "alertingSectionTrigger": "Тригер", + "alertingTrigger": "Кога да се активира", + "alertingTriggerSiteOnline": "Сайтът е онлайн", + "alertingTriggerSiteOffline": "Сайтът е офлайн", + "alertingTriggerSiteToggle": "Състоянието на сайта се променя", + "alertingTriggerHcHealthy": "Проверка на състоянието е здрава", + "alertingTriggerHcUnhealthy": "Проверка на състоянието не е здрава", + "alertingTriggerHcToggle": "Състоянието на проверката се променя", + "alertingTriggerResourceHealthy": "Ресурсът е здрав", + "alertingTriggerResourceUnhealthy": "Ресурсът не е здрав", + "alertingSearchHealthChecks": "Търсене на проверки на състоянието…", + "alertingHealthChecksEmpty": "Няма налични проверки на състоянието.", + "alertingTriggerResourceToggle": "Състоянието на ресурса се променя", + "alertingSourceResource": "Ресурс", + "alertingSectionActions": "Действия", + "alertingAddAction": "Добавяне на действие", + "alertingActionNotify": "Имейл", + "alertingActionNotifyDescription": "Изпращане на имейл известия на потребители или роли", + "alertingActionWebhook": "Уеб кука", + "alertingActionWebhookDescription": "Изпращане на HTTP заявка към персонализирана крайна точка", + "alertingExternalIntegration": "Външна интеграция", + "alertingExternalPagerDutyDescription": "Изпратете предупреждения към PagerDuty за управление на инциденти", + "alertingExternalOpsgenieDescription": "Пренасочете предупрежденията към Opsgenie за управление на дежурните отчети", + "alertingExternalServiceNowDescription": "Създавайте инциденти в ServiceNow от събития на предупреждения", + "alertingExternalIncidentIoDescription": "Активирайте работни потоци в Incident.io от събития на предупреждения", + "alertingActionType": "Тип на действието", + "alertingNotifyUsers": "Потребители", + "alertingNotifyRoles": "Роли", + "alertingNotifyEmails": "Имейл адреси", + "alertingEmailPlaceholder": "Добавете имейл и натиснете Enter", + "alertingWebhookMethod": "HTTP метод", + "alertingWebhookSecret": "Секрет за подписване (по избор)", + "alertingWebhookSecretPlaceholder": "HMAC секрет", + "alertingWebhookHeaders": "Заглавия", + "alertingAddHeader": "Добавете заглавие", + "alertingSelectSites": "Изберете сайтове…", + "alertingSitesSelected": "Избрани {count} сайта", + "alertingSelectHealthChecks": "Изберете проверки на състоянието…", + "alertingHealthChecksSelected": "Избрани {count} проверки на състоянието", + "alertingNoHealthChecks": "Няма цели с активирани проверки на състоянието", + "alertingHealthCheckStub": "Изборът на източник за проверки на състоянието все още не е свързан - все още можете да конфигурирате тригери и действия.", + "alertingSelectUsers": "Изберете потребители…", + "alertingUsersSelected": "Избрани {count} потребителя", + "alertingSelectRoles": "Изберете роли…", + "alertingRolesSelected": "Избрани {count} роли", + "alertingSummarySites": "Сайтове ({count})", + "alertingSummaryAllSites": "Всички сайтове", + "alertingSummaryHealthChecks": "Проверки на състоянието ({count})", + "alertingSummaryAllHealthChecks": "Всички проверки на състоянието", + "alertingSummaryResources": "Ресурси ({count})", + "alertingSummaryAllResources": "Всички ресурси", + "alertingErrorNameRequired": "Въведете име", + "alertingErrorActionsMin": "Добавете поне едно действие", + "alertingErrorPickSites": "Изберете поне един сайт", + "alertingErrorPickHealthChecks": "Изберете поне една проверка на състоянието", + "alertingErrorPickResources": "Изберете поне един ресурс", + "alertingErrorTriggerSite": "Изберете тригер за сайт", + "alertingErrorTriggerHealth": "Изберете тригер за проверка на състоянието", + "alertingErrorTriggerResource": "Изберете тригер за ресурс", + "alertingErrorNotifyRecipients": "Изберете потребители, роли или поне един имейл", + "alertingConfigureSource": "Конфигуриране на източник", + "alertingConfigureTrigger": "Конфигуриране на тригер", + "alertingConfigureActions": "Конфигуриране на действия", + "alertingBackToRules": "Назад към правилата", + "alertingRuleCooldown": "Време за изчакване (секунди)", + "alertingRuleCooldownDescription": "Минимално време между повторни предупреждения за същото правило. Задайте на 0, за да се задейства всеки път.", + "alertingDraftBadge": "Чернова - запазете, за да съхраните правилото", + "alertingSidebarHint": "Кликнете върху стъпка на платното, за да я редактирате тук.", + "alertingGraphCanvasTitle": "Последователност на правилото", + "alertingGraphCanvasDescription": "Визуален преглед на източник, тригер и действия. Изберете елемент за редакция в панела.", + "alertingNodeNotConfigured": "Още не е конфигурирано", + "alertingNodeActionsCount": "{count, plural, one {# действие} other {# действия}}", + "alertingNodeRoleSource": "Източник", + "alertingNodeRoleTrigger": "Тригер", + "alertingNodeRoleAction": "Действие", + "alertingTabRules": "Правила за предупреждение", + "alertingTabHealthChecks": "Проверки на състоянието", + "alertingRulesBannerTitle": "Получавайте известия", + "alertingRulesBannerDescription": "Всяко правило свързва това, което да се наблюдава (сайт, проверка на състоянието или ресурс), кога да се активира (например офлайн или нездраве) и как да уведомите екипа чрез имейл, уеб куки или интеграции. Използвайте този списък, за да създавате, активирате и управлявате тези правила.", + "alertingHealthChecksBannerTitle": "Наблюдавайте здравето и ресурсите", + "alertingHealthChecksBannerDescription": "Проверките на състоянието са HTTP или TCP монитори, които определяте веднъж. След това можете да ги използвате като източници в правила за предупреждения, така че да бъдете уведомени, когато целта стане здраве или нездраве. Проверките на състоянието на ресурсите също се появяват тук.", + "standaloneHcTableTitle": "Проверки на състоянието", + "standaloneHcSearchPlaceholder": "Търсене на проверки на състоянието…", + "standaloneHcAddButton": "Създаване на проверка на състоянието", + "standaloneHcCreateTitle": "Създаване на проверка на състоянието", + "standaloneHcEditTitle": "Редактиране на проверка на състоянието", + "standaloneHcDescription": "Конфигурирайте HTTP или TCP проверка на състоянието за използване в правилата за предупреждения.", + "standaloneHcNameLabel": "Име", + "standaloneHcNamePlaceholder": "Моят HTTP монитор", + "standaloneHcDeleteTitle": "Изтриване на проверка на състоянието", + "standaloneHcDeleteQuestion": "Моля, потвърдете, че искате да изтриете тази проверка на състоянието.", + "standaloneHcDeleted": "Проверката на състоянието е изтрита", + "standaloneHcSaved": "Проверката на състоянието е запазена", + "standaloneHcColumnHealth": "Здраве", + "standaloneHcColumnMode": "Режим", + "standaloneHcColumnTarget": "Цел", + "standaloneHcHealthStateHealthy": "Здраве", + "standaloneHcHealthStateUnhealthy": "Нездраве", + "standaloneHcHealthStateUnknown": "Неизвестно", + "standaloneHcFilterAnySite": "Всички сайтове", + "standaloneHcFilterAnyResource": "Всички ресурси", + "standaloneHcFilterMode": "Режим", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "Пинг", + "standaloneHcFilterHealth": "Здраве", + "standaloneHcFilterEnabled": "Активирано", + "standaloneHcFilterEnabledOn": "Активирано", + "standaloneHcFilterEnabledOff": "Деактивирано", + "standaloneHcFilterSiteIdFallback": "Сайт {id}", + "standaloneHcFilterResourceIdFallback": "Ресурс {id}", "blueprints": "Чертежи", "blueprintsDescription": "Прилагайте декларативни конфигурации и преглеждайте предишни изпълнения", "blueprintAdd": "Добави Чертеж", @@ -1763,6 +1935,15 @@ "healthCheckIntervalMin": "Интервалът за проверка трябва да е поне 5 секунди", "healthCheckTimeoutMin": "Времето за изчакване трябва да е поне 1 секунда", "healthCheckRetryMin": "Опитите за повторение трябва да са поне 1", + "healthCheckMode": "Режим на проверка", + "healthCheckStrategy": "Стратегия", + "healthCheckModeDescription": "Режимът TCP проверява само свързаността. Режимът HTTP валидира HTTP отговора.", + "healthyThreshold": "Праг за здраве", + "healthyThresholdDescription": "Поредица от успехи, необходими за отбелязване като здраве.", + "unhealthyThreshold": "Праг за нездраве", + "unhealthyThresholdDescription": "Поредица от провали, необходими за отбелязване като нездраве.", + "healthCheckHealthyThresholdMin": "Прагът за здраве трябва да бъде поне 1", + "healthCheckUnhealthyThresholdMin": "Прагът за нездраве трябва да бъде поне 1", "httpMethod": "HTTP Метод", "selectHttpMethod": "Изберете HTTP метод", "domainPickerSubdomainLabel": "Поддомен", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "Порт", "editInternalResourceDialogModeHost": "Хост", "editInternalResourceDialogModeCidr": "CIDR", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "Метод", + "editInternalResourceDialogEnableSsl": "Активирайте SSL", + "editInternalResourceDialogEnableSslDescription": "Активирайте SSL/TLS криптиране за сигурни HTTPS връзки към целта.", "editInternalResourceDialogDestination": "Дестинация", "editInternalResourceDialogDestinationHostDescription": "IP адресът или името на хоста на ресурса в мрежата на сайта.", "editInternalResourceDialogDestinationIPDescription": "IP адресът или името на хоста на ресурса в мрежата на сайта.", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "Име", "createInternalResourceDialogSite": "Сайт", "selectSite": "Изберете сайт...", + "multiSitesSelectorSitesCount": "{count, plural, one {# сайт} other {# сайтове}}", "noSitesFound": "Не са намерени сайтове.", "createInternalResourceDialogProtocol": "Протокол", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "Порт", "createInternalResourceDialogModeHost": "Хост", "createInternalResourceDialogModeCidr": "CIDR", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "Метод", + "createInternalResourceDialogScheme": "Метод", + "createInternalResourceDialogEnableSsl": "Активирайте SSL", + "createInternalResourceDialogEnableSslDescription": "Активирайте SSL/TLS криптиране за сигурни HTTPS връзки към целта.", "createInternalResourceDialogDestination": "Дестинация", "createInternalResourceDialogDestinationHostDescription": "IP адресът или името на хоста на ресурса в мрежата на сайта.", "createInternalResourceDialogDestinationCidrDescription": "CIDR диапазонът на ресурса в мрежата на сайта.", "createInternalResourceDialogAlias": "Псевдоним", "createInternalResourceDialogAliasDescription": "По избор вътрешен DNS псевдоним за този ресурс.", + "internalResourceDownstreamSchemeRequired": "Методът е задължителен за HTTP ресурси", + "internalResourceHttpPortRequired": "Портът към целта е задължителен за HTTP ресурси", "siteConfiguration": "Конфигурация", "siteAcceptClientConnections": "Приемане на клиентски връзки", "siteAcceptClientConnectionsDescription": "Позволете на потребителските устройства и клиенти да получават достъп до ресурси на този сайт. Това може да бъде променено по-късно.", @@ -1994,7 +2189,7 @@ "description": "По-надежден и по-нисък поддръжка на Самостоятелно-хостван Панголиин сървър с допълнителни екстри", "introTitle": "Управлявано Самостоятелно-хостван Панголиин", "introDescription": "е опция за внедряване, предназначена за хора, които искат простота и допълнителна надеждност, като същевременно запазят данните си частни и самостоятелно-хоствани.", - "introDetail": "С тази опция все още управлявате свой собствен Панголиин възел — вашите тунели, SSL терминатора и трафик остават на вашия сървър. Разликата е, че управлението и мониторингът се обработват чрез нашия облачен панел за контрол, който отключва редица предимства:", + "introDetail": "С тази опция все още управлявате свой собствен Панголиин възел - вашите тунели, SSL терминатора и трафик остават на вашия сървър. Разликата е, че управлението и мониторингът се обработват чрез нашия облачен панел за контрол, който отключва редица предимства:", "benefitSimplerOperations": { "title": "По-прости операции", "description": "Няма нужда да управлявате свой собствен имейл сървър или да настройвате сложни аларми. Ще получите проверки и предупреждения при прекъсване от самото начало." @@ -2297,7 +2492,7 @@ "alerts": { "commercialUseDisclosure": { "title": "Разкриване на употреба", - "description": "Изберете лицензионен клас, който точно отразява вашата целена употреба. Персоналният лиценз позволява безплатно ползване на софтуера за индивидуална, некомерсиална или маломащабна комерсиална дейност с годишен брутен приход под 100,000 USD. Всяко ползване извън тези граници — включително ползване във фирма, организация или друга доходоносна среда — изисква валиден корпоративен лиценз и плащане на съответната лицензионна такса. Всички потребители, независимо дали са лични или корпоративни, трябва да спазват Условията на Fossorial Commercial License." + "description": "Изберете лицензионен клас, който точно отразява вашата целена употреба. Персоналният лиценз позволява безплатно ползване на софтуера за индивидуална, некомерсиална или маломащабна комерсиална дейност с годишен брутен приход под 100,000 USD. Всяко ползване извън тези граници - включително ползване във фирма, организация или друга доходоносна среда - изисква валиден корпоративен лиценз и плащане на съответната лицензионна такса. Всички потребители, независимо дали са лични или корпоративни, трябва да спазват Условията на Fossorial Commercial License." }, "trialPeriodInformation": { "title": "Информация за пробен период", @@ -2429,6 +2624,7 @@ "validPassword": "Валидна парола", "validEmail": "Валиден имейл", "validSSO": "Валидно SSO", + "connectedClient": "Свързан клиент", "resourceBlocked": "Блокирани ресурси", "droppedByRule": "Прекратено от правило", "noSessions": "Няма сесии", @@ -2668,6 +2864,10 @@ "editInternalResourceDialogDestinationLabel": "Дестинация.", "editInternalResourceDialogDestinationDescription": "Посочете адреса дестинация за вътрешния ресурс. Това може да бъде име на хост, IP адрес или CIDR обхват в зависимост от избрания режим. По избор настройте вътрешен DNS алиас за по-лесно идентифициране.", "editInternalResourceDialogPortRestrictionsDescription": "Ограничете достъпа до конкретни TCP/UDP портове или позволете/блокирайте всички портове.", + "createInternalResourceDialogHttpConfiguration": "Конфигурация HTTP", + "createInternalResourceDialogHttpConfigurationDescription": "Изберете домейна, който клиентите ще използват, за да достигнат този ресурс чрез HTTP или HTTPS.", + "editInternalResourceDialogHttpConfiguration": "Конфигурация HTTP", + "editInternalResourceDialogHttpConfigurationDescription": "Изберете домейна, който клиентите ще използват, за да достигнат този ресурс чрез HTTP или HTTPS.", "editInternalResourceDialogTcp": "TCP.", "editInternalResourceDialogUdp": "UDP.", "editInternalResourceDialogIcmp": "ICMP.", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "Ще се върнем скоро! Нашият сайт понастоящем е в процес на планирана поддръжка.", "maintenancePageMessageDescription": "Подробно съобщение, обясняващо поддръжката.", "maintenancePageTimeTitle": "Очаквано време за завършване (по избор).", + "privateMaintenanceScreenTitle": "Екран за поддръжка", + "privateMaintenanceScreenMessage": "Този домейн се използва при частен ресурс. Моля, свържете се с клиента на Pangolin, за да получите достъп до този ресурс.", "maintenanceTime": "например, 2 часа, 1 ноември в 17:00.", "maintenanceEstimatedTimeDescription": "Кога очаквате поддръжката да бъде завършена?", "editDomain": "Редактиране на домейна.", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "Добавяне на HTTP дестинация", "httpDestEditDescription": "Актуализирайте конфигурацията за този HTTP събитий.", "httpDestAddDescription": "Конфигурирайте нов HTTP крайна точка, за да получавате събития на вашата организация.", + "S3DestEditTitle": "Редактиране на дестинацията", + "S3DestAddTitle": "Добавете S3 дестинация", + "S3DestEditDescription": "Актуализирайте конфигурацията за тази S3 дестинация за предаване на събития.", + "S3DestAddDescription": "Конфигурирайте нов крайна точка на S3, за да получавате събития на вашата организация.", + "datadogDestEditTitle": "Редактиране на дестинация", + "datadogDestAddTitle": "Добавяне на Datadog дестинация", + "datadogDestEditDescription": "Актуализирайте конфигурацията за тази Datadog дестинация за предаване на събития.", + "datadogDestAddDescription": "Конфигурирайте нова крайна точка на Datadog, за да получавате събития на вашата организация.", "httpDestTabSettings": "Настройки", "httpDestTabHeaders": "Заглавки", "httpDestTabBody": "Тяло", @@ -2882,7 +3092,7 @@ "httpDestFormatJsonArrayTitle": "JSON масив", "httpDestFormatJsonArrayDescription": "Една заявка на партида, тялото е JSON масив. Съвместим с повечето общи уеб куки и Datadog.", "httpDestFormatNdjsonTitle": "NDJSON", - "httpDestFormatNdjsonDescription": "Една заявка на партида, тялото е ново линии отделени JSON — един обект на ред, няма външен масив. Изисквано от Splunk HEC, Elastic / OpenSearch и Grafana.", + "httpDestFormatNdjsonDescription": "Една заявка на партида, тялото е ново линии отделени JSON - един обект на ред, няма външен масив. Изисквано от Splunk HEC, Elastic / OpenSearch и Grafana.", "httpDestFormatSingleTitle": "Едно събитие на заявка", "httpDestFormatSingleDescription": "Изпращат се отделни HTTP POST за всяко индивидуално събитие. Използвайте само за крайни точки, които не могат да обработват партиди.", "httpDestLogTypesTitle": "Видове логове", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "Дестинацията беше създадена успешно", "httpDestUpdateFailed": "Неуспешно актуализиране на дестинацията", "httpDestCreateFailed": "Неуспешно създаване на дестинацията", + "followRedirects": "Следвайте пренасочвания", + "followRedirectsDescription": "Автоматично следвайте HTTP пренасочвания за заявки.", + "alertingErrorWebhookUrl": "Моля, въведете валид URL адрес за уеб куката.", + "healthCheckStrategyHttp": "Проверява свързаността и проверява статуса на HTTP отговора.", + "healthCheckStrategyTcp": "Проверява само TCP свързаност, без да изследва отговора.", + "healthCheckStrategySnmp": "Прави SNMP get заявка, за да провери здравето на мрежовите устройства и инфраструктура.", + "healthCheckStrategyIcmp": "Използва ICMP echo заявки (пинг), за да провери дали ресурсът е достъпен и отговаря.", + "healthCheckTabStrategy": "Стратегия", + "healthCheckTabConnection": "Връзка", + "healthCheckTabAdvanced": "Разширени", + "healthCheckStrategyNotAvailable": "Тази стратегия не е достъпна. Моля, свържете се с отдел продажби, за да активирате тази функция.", + "uptime30d": "Работно време (30д)", "idpAddActionCreateNew": "Създайте нов доставчик на самоличност", "idpAddActionImportFromOrg": "Импортиране от друга организация", "idpImportDialogTitle": "Импортиране на доставчик на самоличност", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "Това не може да бъде отменено за тази организация.", "idpUnassociatedDescription": "Доставчика на самоличност е успешно отвързан от тази организация", "idpUnassociateMenu": "Отвързване", - "idpDeleteAllOrgsMenu": "Изтриване" + "idpDeleteAllOrgsMenu": "Изтриване", + "publicIpEndpoint": "Крайна точка", + "lastTriggeredAt": "Последен тригер", + "reject": "Отхвърляне" } diff --git a/messages/cs-CZ.json b/messages/cs-CZ.json index 7919aa02c..0e43a4043 100644 --- a/messages/cs-CZ.json +++ b/messages/cs-CZ.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "Obraťte se na prodejce, aby tuto funkci povolil.", + "contactSalesBookDemo": "Zarezervovat demo", + "contactSalesOr": "nebo", + "contactSalesContactUs": "kontaktujte nás", "setupCreate": "Vytvořte organizaci, stránku a zdroje", "headerAuthCompatibilityInfo": "Povolte toto, aby vyvolalo odpověď 401 Neoprávněné, když chybí autentizační token. Toto je potřeba pro prohlížeče nebo specifické HTTP knihovny, které neposílají přihlašovací údaje bez výzvy serveru.", "headerAuthCompatibility": "Rozšířená kompatibilita", @@ -19,6 +23,14 @@ "componentsInvalidKey": "Byly nalezeny neplatné nebo propadlé licenční klíče. Pokud chcete nadále používat všechny funkce, postupujte podle licenčních podmínek.", "dismiss": "Zavřít", "subscriptionViolationMessage": "Jste za hranicemi vašeho aktuálního plánu. Opravte problém odstraněním webů, uživatelů nebo jiných zdrojů, abyste zůstali ve vašem tarifu.", + "trialBannerMessage": "Vaše zkušební verze vyprší za {countdown}. Pro udržení přístupu upgraduje.", + "trialBannerExpired": "Vaše zkušební verze vypršela. Upgradujte nyní pro obnovu přístupu.", + "trialActive": "Zkušební verze je aktivní", + "trialExpired": "Zkušební verze vypršela", + "trialHasEnded": "Vaše zkušební verze skončila.", + "trialDaysRemaining": "{count, plural, one {# den zbývá} few {# dny zbývají} many {# dní zbývá} other {# dny zbývají}}", + "trialDaysLeftShort": "Zbývá {days} d ve zkušební verzi", + "trialGoToBilling": "Přejděte na fakturační stránku", "subscriptionViolationViewBilling": "Zobrazit fakturaci", "componentsLicenseViolation": "Porušení licenčních podmínek: Tento server používá {usedSites} stránek, což překračuje limit {maxSites} licencovaných stránek. Pokud chcete nadále používat všechny funkce, postupujte podle licenčních podmínek.", "componentsSupporterMessage": "Děkujeme, že podporujete Pangolin jako {tier}!", @@ -267,8 +279,11 @@ "orgMissing": "Chybí ID organizace", "orgMissingMessage": "Nelze obnovit pozvánku bez ID organizace.", "accessUsersManage": "Spravovat uživatele", + "accessUserManage": "Spravovat uživatele", "accessUsersDescription": "Pozvat a spravovat uživatele s přístupem k této organizaci", "accessUsersSearch": "Hledat uživatele...", + "accessUsersRoleFilterCount": "{count, plural, one {# role} few {# role} many {# rolí} other {# roli}}", + "accessUsersRoleFilterClear": "Vymazat filtry rolí", "accessUserCreate": "Vytvořit uživatele", "accessUserRemove": "Odstranit uživatele", "username": "Uživatelské jméno", @@ -1257,6 +1272,7 @@ "actionViewLogs": "Zobrazit logy", "noneSelected": "Není vybráno", "orgNotFound2": "Nebyly nalezeny žádné organizace.", + "search": "Vyhledávání…", "searchPlaceholder": "Hledat...", "emptySearchOptions": "Nebyly nalezeny žádné možnosti", "create": "Vytvořit", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "Spravovat", "sidebarLogAndAnalytics": "Log & Analytics", "sidebarBluePrints": "Plány", + "sidebarAlerting": "Upozornění", + "sidebarHealthChecks": "Kontroly stavu", "sidebarOrganization": "Organizace", "sidebarManagement": "Správa", "sidebarBillingAndLicenses": "Fakturace a licence", "sidebarLogsAnalytics": "Analytici", + "alertingTitle": "Upozornění", + "alertingDescription": "Definujte zdroje, spouštěče a akce pro oznámení", + "alertingRules": "Pravidla upozornění", + "alertingSearchRules": "Hledat pravidla…", + "alertingAddRule": "Vytvořit pravidlo", + "alertingColumnSource": "Zdroj", + "alertingColumnTrigger": "Spouštěč", + "alertingColumnActions": "Akce", + "alertingColumnEnabled": "Povoleno", + "alertingDeleteQuestion": "Potvrďte, prosím, zda chcete toto pravidlo upozornění smazat.", + "alertingDeleteRule": "Smazat pravidlo upozornění", + "alertingRuleDeleted": "Pravidlo upozornění bylo smazáno", + "alertingRuleSaved": "Pravidlo upozornění bylo uloženo", + "alertingRuleSavedCreatedDescription": "Vaše nové pravidlo upozornění bylo vytvořeno. Můžete ho dál upravovat na této stránce.", + "alertingRuleSavedUpdatedDescription": "Vaše změny pro toto pravidlo upozornění byly uloženy.", + "alertingEditRule": "Upravit pravidlo upozornění", + "alertingCreateRule": "Vytvořit pravidlo upozornění", + "alertingRuleCredenzaDescription": "Vyberte, co sledovat, kdy ho spustit a jak oznamovat", + "alertingRuleNamePlaceholder": "Produkční stránka je dolů", + "alertingRuleEnabled": "Pravidlo povoleno", + "alertingSectionSource": "Zdroj", + "alertingSourceType": "Typ zdroje", + "alertingSourceSite": "Lokalita", + "alertingSourceHealthCheck": "Kontrola stavu", + "alertingPickSites": "Lokality", + "alertingPickHealthChecks": "Kontroly stavu", + "alertingPickResources": "Zdroje", + "alertingAllSites": "Všechny lokality", + "alertingAllSitesDescription": "Upozornění pro jakoukoli lokalitu", + "alertingSpecificSites": "Specifické lokality", + "alertingSpecificSitesDescription": "Vyberte specifické lokality k sledování", + "alertingAllHealthChecks": "Všechny kontroly stavu", + "alertingAllHealthChecksDescription": "Upozornění pro jakoukoli kontrolu stavu", + "alertingSpecificHealthChecks": "Specifické kontroly stavu", + "alertingSpecificHealthChecksDescription": "Vyberte specifické kontroly stavu k sledování", + "alertingAllResources": "Všechny zdroje", + "alertingAllResourcesDescription": "Upozornění pro jakýkoli zdroj", + "alertingSpecificResources": "Specifické zdroje", + "alertingSpecificResourcesDescription": "Vyberte specifické zdroje k sledování", + "alertingSelectResources": "Vyberte zdroje…", + "alertingResourcesSelected": "{count} zdrojů vybráno", + "alertingResourcesEmpty": "Žádné zdroje s cíly v prvních 10 výsledcích.", + "alertingSectionTrigger": "Spouštěč", + "alertingTrigger": "Kdy upozornit", + "alertingTriggerSiteOnline": "Stránky online", + "alertingTriggerSiteOffline": "Stránky offline", + "alertingTriggerSiteToggle": "Změny stavu stránek", + "alertingTriggerHcHealthy": "Kontrola stavu je zdravá", + "alertingTriggerHcUnhealthy": "Kontrola stavu je nezdravá", + "alertingTriggerHcToggle": "Změny stavu kontroly stavu", + "alertingTriggerResourceHealthy": "Zdroj je zdravý", + "alertingTriggerResourceUnhealthy": "Zdroj je nezdravý", + "alertingSearchHealthChecks": "Hledat kontroly stavu…", + "alertingHealthChecksEmpty": "Nejsou dostupné kontroly stavu.", + "alertingTriggerResourceToggle": "Změny stavu zdroje", + "alertingSourceResource": "Zdroj", + "alertingSectionActions": "Akce", + "alertingAddAction": "Přidat akci", + "alertingActionNotify": "Email", + "alertingActionNotifyDescription": "Odesílat emailová upozornění uživatelům nebo rolím", + "alertingActionWebhook": "Webhook", + "alertingActionWebhookDescription": "Odeslání HTTP požadavku na vlastní koncový bod", + "alertingExternalIntegration": "Externí integrace", + "alertingExternalPagerDutyDescription": "Odesílat upozornění do PagerDuty pro řízení incidentů", + "alertingExternalOpsgenieDescription": "Směrujte upozornění do Opsgenie pro řízení, když je někdo na telefonu", + "alertingExternalServiceNowDescription": "Vytvářet incidenty ServiceNow z událostí upozornění", + "alertingExternalIncidentIoDescription": "Spouštět Incident.io workflowy z událostí upozornění", + "alertingActionType": "Typ akce", + "alertingNotifyUsers": "Uživatelé", + "alertingNotifyRoles": "Role", + "alertingNotifyEmails": "Emailové adresy", + "alertingEmailPlaceholder": "Přidejte e-mail a stiskněte Enter", + "alertingWebhookMethod": "HTTP metoda", + "alertingWebhookSecret": "Přihlašovací tajemství (volitelné)", + "alertingWebhookSecretPlaceholder": "HMAC tajemství", + "alertingWebhookHeaders": "Hlavičky", + "alertingAddHeader": "Přidat hlavičku", + "alertingSelectSites": "Vybrat lokality…", + "alertingSitesSelected": "{count} lokalit vybráno", + "alertingSelectHealthChecks": "Vybrat kontroly stavu…", + "alertingHealthChecksSelected": "{count} kontrol stavu vybráno", + "alertingNoHealthChecks": "Žádné cíle s povolenými kontrolami stavu", + "alertingHealthCheckStub": "Výběr zdrojů kontrol stavu ještě není propojen – můžete stále konfigurovat spouštěče a akce.", + "alertingSelectUsers": "Vybrat uživatele…", + "alertingUsersSelected": "{count} uživatelů vybráno", + "alertingSelectRoles": "Vybrat role…", + "alertingRolesSelected": "{count} rolí vybráno", + "alertingSummarySites": "Lokality ({count})", + "alertingSummaryAllSites": "Všechny lokality", + "alertingSummaryHealthChecks": "Kontroly stavu ({count})", + "alertingSummaryAllHealthChecks": "Všechny kontroly stavu", + "alertingSummaryResources": "Zdroje ({count})", + "alertingSummaryAllResources": "Všechny zdroje", + "alertingErrorNameRequired": "Zadejte jméno", + "alertingErrorActionsMin": "Přidat alespoň jednu akci", + "alertingErrorPickSites": "Vyberte alespoň jednu lokalitu", + "alertingErrorPickHealthChecks": "Vyberte alespoň jednu kontrolu stavu", + "alertingErrorPickResources": "Vyberte alespoň jeden zdroj", + "alertingErrorTriggerSite": "Vyberte spouštěč lokality", + "alertingErrorTriggerHealth": "Vyberte spouštěč kontroly stavu", + "alertingErrorTriggerResource": "Vyberte spouštěč zdroje", + "alertingErrorNotifyRecipients": "Vyberte uživatele, role nebo alespoň jeden email", + "alertingConfigureSource": "Konfigurace zdroje", + "alertingConfigureTrigger": "Konfigurace spouštěče", + "alertingConfigureActions": "Konfigurace akcí", + "alertingBackToRules": "Zpět na pravidla", + "alertingRuleCooldown": "Odpočinek (sekundy)", + "alertingRuleCooldownDescription": "Minimální doba mezi opakovanými upozorněními pro stejné pravidlo. Nastavte na 0 pro spuštění pokaždé.", + "alertingDraftBadge": "Koncept - uložit pro uložení tohoto pravidla", + "alertingSidebarHint": "Kliknutím na krok na plátno ho zde upravte.", + "alertingGraphCanvasTitle": "Průběh pravidla", + "alertingGraphCanvasDescription": "Vizuální přehled o zdroji, spouštěči a akcích. Vyberte uzel k jeho editaci v panelu.", + "alertingNodeNotConfigured": "Ještě není nakonfigurováno", + "alertingNodeActionsCount": "{count, plural, one {# akce} few {# akce} many {# akcí} other {# akce}}", + "alertingNodeRoleSource": "Zdroj", + "alertingNodeRoleTrigger": "Spouštěč", + "alertingNodeRoleAction": "Akce", + "alertingTabRules": "Pravidla upozornění", + "alertingTabHealthChecks": "Kontroly stavu", + "alertingRulesBannerTitle": "Dostávat upozornění", + "alertingRulesBannerDescription": "Každé pravidlo spojuje, co sledovat (lokalita, kontrola stavu nebo zdroj), kdy ho spustit (například offline nebo nezdravé), a jak informovat váš tým emailem, webhookem nebo integracemi. Použijte tento seznam k vytvoření, povolení a správě těchto pravidel.", + "alertingHealthChecksBannerTitle": "Monitorujte zdraví a zdroje", + "alertingHealthChecksBannerDescription": "Kontroly stavu jsou HTTP nebo TCP monitory, které nastavíte jednou. Poté je můžete použít jako zdroje v pravidlech upozornění, takže budete informováni, když se cíl stane zdravým nebo nezdravým. Kontroly stavu také zde se objeví.", + "standaloneHcTableTitle": "Kontroly stavu", + "standaloneHcSearchPlaceholder": "Hledat kontroly stavu…", + "standaloneHcAddButton": "Vytvořit kontrolu stavu", + "standaloneHcCreateTitle": "Vytvořit kontrolu stavu", + "standaloneHcEditTitle": "Upravit kontrolu stavu", + "standaloneHcDescription": "Nakonfigurujte HTTP nebo TCP kontrolu stavu pro použití v pravidlech upozornění.", + "standaloneHcNameLabel": "Jméno", + "standaloneHcNamePlaceholder": "Můj HTTP Monitor", + "standaloneHcDeleteTitle": "Smazat kontrolu stavu", + "standaloneHcDeleteQuestion": "Potvrďte, prosím, zda chcete tuto kontrolu stavu smazat.", + "standaloneHcDeleted": "Kontrola stavu byla smazána", + "standaloneHcSaved": "Kontrola stavu byla uložena", + "standaloneHcColumnHealth": "Zdraví", + "standaloneHcColumnMode": "Režim", + "standaloneHcColumnTarget": "Cíl", + "standaloneHcHealthStateHealthy": "Zdravé", + "standaloneHcHealthStateUnhealthy": "Nezdravé", + "standaloneHcHealthStateUnknown": "Neznámý", + "standaloneHcFilterAnySite": "Všechny lokality", + "standaloneHcFilterAnyResource": "Všechny zdroje", + "standaloneHcFilterMode": "Režim", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "Ping", + "standaloneHcFilterHealth": "Zdraví", + "standaloneHcFilterEnabled": "Povoleno", + "standaloneHcFilterEnabledOn": "Povoleno", + "standaloneHcFilterEnabledOff": "Zakázáno", + "standaloneHcFilterSiteIdFallback": "Stránka {id}", + "standaloneHcFilterResourceIdFallback": "Zdroj {id}", "blueprints": "Plány", "blueprintsDescription": "Použít deklarativní konfigurace a zobrazit předchozí běhy", "blueprintAdd": "Přidat plán", @@ -1763,6 +1935,15 @@ "healthCheckIntervalMin": "Interval kontroly musí být nejméně 5 sekund", "healthCheckTimeoutMin": "Časový limit musí být nejméně 1 sekunda", "healthCheckRetryMin": "Pokusy opakovat musí být alespoň 1", + "healthCheckMode": "Režim kontroly", + "healthCheckStrategy": "Strategie", + "healthCheckModeDescription": "Režim TCP ověřuje pouze připojení. Režim HTTP ověřuje HTTP odezvu.", + "healthyThreshold": "Zdravý práh", + "healthyThresholdDescription": "Počet po sobě jdoucích úspěchů vyžadovaných před označením jako zdravý.", + "unhealthyThreshold": "Nezdravý práh", + "unhealthyThresholdDescription": "Počet po sobě jdoucích selhání vyžadovaných před označením jako nezdravý.", + "healthCheckHealthyThresholdMin": "Zdravý práh musí být alespoň 1", + "healthCheckUnhealthyThresholdMin": "Nezdravý práh musí být alespoň 1", "httpMethod": "HTTP metoda", "selectHttpMethod": "Vyberte HTTP metodu", "domainPickerSubdomainLabel": "Subdoména", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "Přístav", "editInternalResourceDialogModeHost": "Hostitel", "editInternalResourceDialogModeCidr": "CIDR", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "Schéma", + "editInternalResourceDialogEnableSsl": "Povolit SSL", + "editInternalResourceDialogEnableSslDescription": "Povolit šifrování SSL/TLS pro zabezpečené HTTPS připojení k cíli.", "editInternalResourceDialogDestination": "Místo určení", "editInternalResourceDialogDestinationHostDescription": "IP adresa nebo název hostitele zdroje v síti webu.", "editInternalResourceDialogDestinationIPDescription": "IP nebo název hostitele zdroje v síti webu.", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "Jméno", "createInternalResourceDialogSite": "Lokalita", "selectSite": "Vybrat lokalitu...", + "multiSitesSelectorSitesCount": "{count, plural, one {# web} few {# weby} many {# webů} other {# weby}}", "noSitesFound": "Nebyly nalezeny žádné lokality.", "createInternalResourceDialogProtocol": "Protokol", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "Přístav", "createInternalResourceDialogModeHost": "Hostitel", "createInternalResourceDialogModeCidr": "CIDR", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "Schéma", + "createInternalResourceDialogScheme": "Schéma", + "createInternalResourceDialogEnableSsl": "Povolit SSL", + "createInternalResourceDialogEnableSslDescription": "Povolit šifrování SSL/TLS pro zabezpečené HTTPS připojení k cíli.", "createInternalResourceDialogDestination": "Místo určení", "createInternalResourceDialogDestinationHostDescription": "IP adresa nebo název hostitele zdroje v síti webu.", "createInternalResourceDialogDestinationCidrDescription": "Rozsah zdrojů CIDR v síti webu.", "createInternalResourceDialogAlias": "Alias", "createInternalResourceDialogAliasDescription": "Volitelný interní DNS alias pro tento dokument.", + "internalResourceDownstreamSchemeRequired": "HTTP metoda je vyžadována pro HTTP zdroje", + "internalResourceHttpPortRequired": "Přípoječný port je nutný pro HTTP zdroj", "siteConfiguration": "Konfigurace", "siteAcceptClientConnections": "Přijmout připojení klienta", "siteAcceptClientConnectionsDescription": "Povolit uživatelským zařízením a klientům přístup ke zdrojům na tomto webu. To lze později změnit.", @@ -1994,7 +2189,7 @@ "description": "Spolehlivější a nízko udržovaný Pangolinův server s dalšími zvony a bičkami", "introTitle": "Spravovaný Pangolin", "introDescription": "je možnost nasazení určená pro lidi, kteří chtějí jednoduchost a spolehlivost při zachování soukromých a samoobslužných dat.", - "introDetail": "Pomocí této volby stále provozujete vlastní uzel Pangolin — tunely, SSL terminály a provoz všech pobytů na vašem serveru. Rozdíl spočívá v tom, že řízení a monitorování se řeší prostřednictvím našeho cloudového panelu, který odemkne řadu výhod:", + "introDetail": "Pomocí této volby stále provozujete vlastní uzel Pangolin - tunely, SSL terminály a provoz všech pobytů na vašem serveru. Rozdíl spočívá v tom, že řízení a monitorování se řeší prostřednictvím našeho cloudového panelu, který odemkne řadu výhod:", "benefitSimplerOperations": { "title": "Jednoduchý provoz", "description": "Není třeba spouštět svůj vlastní poštovní server nebo nastavit komplexní upozornění. Ze schránky dostanete upozornění na zdravotní kontrolu a výpadek." @@ -2429,6 +2624,7 @@ "validPassword": "Platné heslo", "validEmail": "Valid email", "validSSO": "Valid SSO", + "connectedClient": "Připojený klient", "resourceBlocked": "Zablokované zdroje", "droppedByRule": "Zrušeno pravidlem", "noSessions": "Žádné relace", @@ -2668,6 +2864,10 @@ "editInternalResourceDialogDestinationLabel": "Cíl", "editInternalResourceDialogDestinationDescription": "Určete cílovou adresu pro interní prostředek. Může se jednat o hostname, IP adresu, nebo rozsah CIDR v závislosti na vybraném režimu. Volitelně nastavte interní DNS alias pro snazší identifikaci.", "editInternalResourceDialogPortRestrictionsDescription": "Omezte přístup na specifické TCP/UDP porty nebo povolte/blokujte všechny porty.", + "createInternalResourceDialogHttpConfiguration": "Konfigurace HTTP", + "createInternalResourceDialogHttpConfigurationDescription": "Zvolte doménu, kterou klienti použijí k dosažení tohoto zdroje přes HTTP nebo HTTPS.", + "editInternalResourceDialogHttpConfiguration": "Konfigurace HTTP", + "editInternalResourceDialogHttpConfigurationDescription": "Zvolte doménu, kterou klienti použijí k dosažení tohoto zdroje přes HTTP nebo HTTPS.", "editInternalResourceDialogTcp": "TCP", "editInternalResourceDialogUdp": "UDP", "editInternalResourceDialogIcmp": "ICMP", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "Vrátíme se brzy! Naše stránka právě prochází plánovanou údrbou.", "maintenancePageMessageDescription": "Podrobná zpráva vysvětlující údržbu", "maintenancePageTimeTitle": "Odhadovaný čas dokončení (volitelný)", + "privateMaintenanceScreenTitle": "Soukromá obrazovka údržby", + "privateMaintenanceScreenMessage": "Tato doména je používána na soukromém zdroji. Prosím, připojte se přes klienta Pangolin pro přístup k tomuto zdroji.", "maintenanceTime": "např. 2 hodiny, 1. listopadu v 17:00", "maintenanceEstimatedTimeDescription": "Kdy očekáváte, že údržba bude dokončena", "editDomain": "Upravit doménu", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "Přidat cíl HTTP", "httpDestEditDescription": "Aktualizovat konfiguraci pro tuto destinaci HTTP události", "httpDestAddDescription": "Konfigurace nového koncového bodu HTTP pro příjem událostí vaší organizace.", + "S3DestEditTitle": "Upravit cíl", + "S3DestAddTitle": "Přidat S3 cíl", + "S3DestEditDescription": "Aktualizujte konfiguraci tohoto S3 cíle pro streamování událostí.", + "S3DestAddDescription": "Konfigurujte nový S3 koncový bod pro přijímání událostí vaší organizace.", + "datadogDestEditTitle": "Upravit cíl", + "datadogDestAddTitle": "Přidat Datadog cíl", + "datadogDestEditDescription": "Aktualizujte konfiguraci tohoto Datadog cíle pro streamování událostí.", + "datadogDestAddDescription": "Konfigurujte nový Datadog koncový bod pro přijímání událostí vaší organizace.", "httpDestTabSettings": "Nastavení", "httpDestTabHeaders": "Záhlaví", "httpDestTabBody": "Tělo", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "Cíl byl úspěšně vytvořen", "httpDestUpdateFailed": "Nepodařilo se aktualizovat cíl", "httpDestCreateFailed": "Nepodařilo se vytvořit cíl", + "followRedirects": "Následovat přesměrování", + "followRedirectsDescription": "Automaticky sledovat přesměrování HTTP pro požadavky.", + "alertingErrorWebhookUrl": "Zadejte platnou URL pro webhook.", + "healthCheckStrategyHttp": "Ověření připojení a kontrola stavu HTTP odpovědi.", + "healthCheckStrategyTcp": "Ověření TCP připojení, bez inspekce odpovědi.", + "healthCheckStrategySnmp": "Vytváří SNMP požadavek pro kontrolu stavu síťových zařízení a infrastruktury.", + "healthCheckStrategyIcmp": "Používá se ICMP echo požadavky (pingy) ke kontrole, zda je zdroj dosažitelný a reaguje.", + "healthCheckTabStrategy": "Strategie", + "healthCheckTabConnection": "Připojení", + "healthCheckTabAdvanced": "Pokročilé", + "healthCheckStrategyNotAvailable": "Tato strategie není dostupná. Kontaktujte prodejce pro povolení této funkce.", + "uptime30d": "Doba provozu (30d)", "idpAddActionCreateNew": "Vytvořit nového poskytovatele identity", "idpAddActionImportFromOrg": "Importovat z jiné organizace", "idpImportDialogTitle": "Importovat poskytovatele identity", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "Toto nelze pro tuto organizaci vrátit.", "idpUnassociatedDescription": "Poskytovatel identity byl úspěšně odpojen od této organizace", "idpUnassociateMenu": "Odpojit", - "idpDeleteAllOrgsMenu": "Odstranit" + "idpDeleteAllOrgsMenu": "Odstranit", + "publicIpEndpoint": "Koncový bod", + "lastTriggeredAt": "Poslední spouštěč", + "reject": "Odmítnout" } diff --git a/messages/de-DE.json b/messages/de-DE.json index a041ee694..07e5d93ac 100644 --- a/messages/de-DE.json +++ b/messages/de-DE.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "Vertrieb kontaktieren, um diese Funktion zu aktivieren.", + "contactSalesBookDemo": "Demo vereinbaren", + "contactSalesOr": "oder", + "contactSalesContactUs": "kontaktieren Sie uns", "setupCreate": "Organisation, Standort und Ressourcen erstellen", "headerAuthCompatibilityInfo": "Aktivieren Sie dies, um eine 401 Nicht autorisierte Antwort zu erzwingen, wenn ein Authentifizierungs-Token fehlt. Dies ist erforderlich für Browser oder bestimmte HTTP-Bibliotheken, die keine Anmeldedaten ohne Server-Challenge senden.", "headerAuthCompatibility": "Erweiterte Kompatibilität", @@ -19,6 +23,14 @@ "componentsInvalidKey": "Ungültige oder abgelaufene Lizenzschlüssel erkannt. Beachte die Lizenzbedingungen, um alle Funktionen weiterhin zu nutzen.", "dismiss": "Verwerfen", "subscriptionViolationMessage": "Sie überschreiten Ihre Grenzen für Ihr aktuelles Paket. Korrigieren Sie das Problem, indem Sie Webseiten, Benutzer oder andere Ressourcen entfernen, um in Ihrem Paket zu bleiben.", + "trialBannerMessage": "Ihre Testversion läuft in {countdown} ab. Upgraden, um den Zugriff zu behalten.", + "trialBannerExpired": "Ihre Testversion ist abgelaufen. Jetzt upgraden, um den Zugriff wiederherzustellen.", + "trialActive": "Kostenlose Testversion aktiv", + "trialExpired": "Testversion abgelaufen", + "trialHasEnded": "Ihre Testversion ist beendet.", + "trialDaysRemaining": "{count, plural, one {# Tag übrig} other {# Tage übrig}}", + "trialDaysLeftShort": "Noch {days}d in der Testversion", + "trialGoToBilling": "Zur Rechnungsseite gehen", "subscriptionViolationViewBilling": "Rechnung anzeigen", "componentsLicenseViolation": "Lizenzverstoß: Dieser Server benutzt {usedSites} Standorte, was das Lizenzlimit von {maxSites} Standorten überschreitet. Beachte die Lizenzbedingungen, um alle Funktionen weiterhin zu nutzen.", "componentsSupporterMessage": "Vielen Dank für die Unterstützung von Pangolin als {tier}!", @@ -267,8 +279,11 @@ "orgMissing": "Organisations-ID fehlt", "orgMissingMessage": "Einladung kann ohne Organisations-ID nicht neu generiert werden.", "accessUsersManage": "Benutzer verwalten", + "accessUserManage": "Benutzer verwalten", "accessUsersDescription": "Benutzer mit Zugriff auf diese Organisation einladen und verwalten", "accessUsersSearch": "Benutzer suchen...", + "accessUsersRoleFilterCount": "{count, plural, one {# Rolle} other {# Rollen}}", + "accessUsersRoleFilterClear": "Rollenfilter löschen", "accessUserCreate": "Benutzer erstellen", "accessUserRemove": "Benutzer entfernen", "username": "Benutzername", @@ -1257,6 +1272,7 @@ "actionViewLogs": "Logs anzeigen", "noneSelected": "Keine ausgewählt", "orgNotFound2": "Keine Organisationen gefunden.", + "search": "Suche…", "searchPlaceholder": "Suche...", "emptySearchOptions": "Keine Optionen gefunden", "create": "Erstellen", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "Verwalten", "sidebarLogAndAnalytics": "Log & Analytik", "sidebarBluePrints": "Blaupausen", + "sidebarAlerting": "Benachrichtigung", + "sidebarHealthChecks": "Gesundheits-Checks", "sidebarOrganization": "Organisation", "sidebarManagement": "Management", "sidebarBillingAndLicenses": "Abrechnung & Lizenzen", "sidebarLogsAnalytics": "Analytik", + "alertingTitle": "Benachrichtigung", + "alertingDescription": "Quellen, Auslöser und Aktionen für Benachrichtigungen festlegen", + "alertingRules": "Benachrichtigungsregeln", + "alertingSearchRules": "Suchregeln…", + "alertingAddRule": "Regel erstellen", + "alertingColumnSource": "Quelle", + "alertingColumnTrigger": "Auslöser", + "alertingColumnActions": "Aktionen", + "alertingColumnEnabled": "Aktiviert", + "alertingDeleteQuestion": "Bitte bestätigen Sie, dass Sie diese Benachrichtigungsregel löschen möchten.", + "alertingDeleteRule": "Benachrichtigungsregel löschen", + "alertingRuleDeleted": "Benachrichtigungsregel gelöscht", + "alertingRuleSaved": "Benachrichtigungsregel gespeichert", + "alertingRuleSavedCreatedDescription": "Ihre neue Benachrichtigungsregel wurde erstellt. Sie können sie auf dieser Seite weiter bearbeiten.", + "alertingRuleSavedUpdatedDescription": "Ihre Änderungen an dieser Benachrichtigungsregel wurden gespeichert.", + "alertingEditRule": "Benachrichtigungsregel bearbeiten", + "alertingCreateRule": "Benachrichtigungsregel erstellen", + "alertingRuleCredenzaDescription": "Wählen Sie aus, was beobachtet, wann ausgelöst und wie benachrichtigt werden soll", + "alertingRuleNamePlaceholder": "Produktionsseite ausgefallen", + "alertingRuleEnabled": "Regel aktiviert", + "alertingSectionSource": "Quelle", + "alertingSourceType": "Quellentyp", + "alertingSourceSite": "Standort", + "alertingSourceHealthCheck": "Gesundheits-Check", + "alertingPickSites": "Standorte", + "alertingPickHealthChecks": "Gesundheits-Checks", + "alertingPickResources": "Ressourcen", + "alertingAllSites": "Alle Standorte", + "alertingAllSitesDescription": "Benachrichtigung für jeden Standort", + "alertingSpecificSites": "Bestimmte Standorte", + "alertingSpecificSitesDescription": "Wählen Sie spezifische Standorte zur Beobachtung aus", + "alertingAllHealthChecks": "Alle Gesundheits-Checks", + "alertingAllHealthChecksDescription": "Benachrichtigung für jeden Gesundheits-Check", + "alertingSpecificHealthChecks": "Bestimmte Gesundheits-Checks", + "alertingSpecificHealthChecksDescription": "Wählen Sie spezifische Gesundheits-Checks zur Beobachtung aus", + "alertingAllResources": "Alle Ressourcen", + "alertingAllResourcesDescription": "Benachrichtigung für jede Ressource", + "alertingSpecificResources": "Spezifische Ressourcen", + "alertingSpecificResourcesDescription": "Wählen Sie spezifische Ressourcen zur Beobachtung aus", + "alertingSelectResources": "Ressourcen auswählen…", + "alertingResourcesSelected": "{count} Ressourcen ausgewählt", + "alertingResourcesEmpty": "Keine Ressourcen mit Zielen in den ersten 10 Ergebnissen.", + "alertingSectionTrigger": "Auslöser", + "alertingTrigger": "Wann benachrichtigen", + "alertingTriggerSiteOnline": "Seite online", + "alertingTriggerSiteOffline": "Seite offline", + "alertingTriggerSiteToggle": "Seitenstatus ändern", + "alertingTriggerHcHealthy": "Gesundheits-Check gesund", + "alertingTriggerHcUnhealthy": "Gesundheits-Check ungesund", + "alertingTriggerHcToggle": "Gesundheits-Check-Status ändern", + "alertingTriggerResourceHealthy": "Ressource gesund", + "alertingTriggerResourceUnhealthy": "Ressource ungesund", + "alertingSearchHealthChecks": "Gesundheits-Checks suchen…", + "alertingHealthChecksEmpty": "Keine Gesundheits-Checks verfügbar.", + "alertingTriggerResourceToggle": "Ressourcenstatus ändern", + "alertingSourceResource": "Ressource", + "alertingSectionActions": "Aktionen", + "alertingAddAction": "Aktion hinzufügen", + "alertingActionNotify": "E-Mail", + "alertingActionNotifyDescription": "Versenden Sie E-Mail-Benachrichtigungen an Benutzer oder Rollen", + "alertingActionWebhook": "Webhook", + "alertingActionWebhookDescription": "Senden Sie eine HTTP-Anfrage an einen benutzerdefinierten Endpunkt", + "alertingExternalIntegration": "Externe Integration", + "alertingExternalPagerDutyDescription": "Senden Sie Benachrichtigungen an PagerDuty für Incident Management", + "alertingExternalOpsgenieDescription": "Leiten Sie Benachrichtigungen an Opsgenie für On-Call Management", + "alertingExternalServiceNowDescription": "Erstellen Sie ServiceNow-Incidents aus Benachrichtigungsereignissen", + "alertingExternalIncidentIoDescription": "Starten Sie Incident.io-Workflows aus Benachrichtigungsereignissen", + "alertingActionType": "Aktionstyp", + "alertingNotifyUsers": "Benutzer", + "alertingNotifyRoles": "Rollen", + "alertingNotifyEmails": "E-Mail-Adressen", + "alertingEmailPlaceholder": "E-Mail hinzufügen und Enter drücken", + "alertingWebhookMethod": "HTTP-Methode", + "alertingWebhookSecret": "Signatur geheim (optional)", + "alertingWebhookSecretPlaceholder": "HMAC-Geheimnis", + "alertingWebhookHeaders": "Header", + "alertingAddHeader": "Header hinzufügen", + "alertingSelectSites": "Standorte auswählen…", + "alertingSitesSelected": "{count} Standorte ausgewählt", + "alertingSelectHealthChecks": "Gesundheits-Checks auswählen…", + "alertingHealthChecksSelected": "{count} Gesundheits-Checks ausgewählt", + "alertingNoHealthChecks": "Keine Ziele mit aktivierten Gesundheits-Checks", + "alertingHealthCheckStub": "Gesundheits-Quellenauswahl ist noch nicht verdrahtet – Sie können trotzdem Auslöser und Aktionen konfigurieren.", + "alertingSelectUsers": "Benutzer auswählen…", + "alertingUsersSelected": "{count} Benutzer ausgewählt", + "alertingSelectRoles": "Rollen auswählen…", + "alertingRolesSelected": "{count} Rollen ausgewählt", + "alertingSummarySites": "Standorte ({count})", + "alertingSummaryAllSites": "Alle Standorte", + "alertingSummaryHealthChecks": "Gesundheits-Checks ({count})", + "alertingSummaryAllHealthChecks": "Alle Gesundheits-Checks", + "alertingSummaryResources": "Ressourcen ({count})", + "alertingSummaryAllResources": "Alle Ressourcen", + "alertingErrorNameRequired": "Einen Namen eingeben", + "alertingErrorActionsMin": "Mindestens eine Aktion hinzufügen", + "alertingErrorPickSites": "Wählen Sie mindestens einen Standort aus", + "alertingErrorPickHealthChecks": "Wählen Sie mindestens einen Gesundheits-Check aus", + "alertingErrorPickResources": "Wählen Sie mindestens eine Ressource aus", + "alertingErrorTriggerSite": "Wählen Sie einen Auslöser für den Standort", + "alertingErrorTriggerHealth": "Wählen Sie einen Auslöser für den Gesundheits-Check", + "alertingErrorTriggerResource": "Wählen Sie einen Auslöser für die Ressource", + "alertingErrorNotifyRecipients": "Wählen Sie Benutzer, Rollen oder mindestens eine E-Mail aus", + "alertingConfigureSource": "Quelle konfigurieren", + "alertingConfigureTrigger": "Auslöser konfigurieren", + "alertingConfigureActions": "Aktionen konfigurieren", + "alertingBackToRules": "Zurück zu den Regeln", + "alertingRuleCooldown": "Cooldown (Sekunden)", + "alertingRuleCooldownDescription": "Mindest-Zeit zwischen wiederholten Benachrichtigungen für dieselbe Regel. Auf 0 setzen, um jedes Mal auszulösen.", + "alertingDraftBadge": "Entwurf - speichern, um diese Regel zu sichern", + "alertingSidebarHint": "Klicken Sie auf einen Schritt auf der Leinwand, um ihn hier zu bearbeiten.", + "alertingGraphCanvasTitle": "Regelfluss", + "alertingGraphCanvasDescription": "Visuelle Übersicht über Quelle, Auslöser und Aktionen. Wählen Sie einen Knoten aus, um ihn im Panel zu bearbeiten.", + "alertingNodeNotConfigured": "Noch nicht konfiguriert", + "alertingNodeActionsCount": "{count, plural, one {# Aktion} other {# Aktionen}}", + "alertingNodeRoleSource": "Quelle", + "alertingNodeRoleTrigger": "Auslöser", + "alertingNodeRoleAction": "Aktion", + "alertingTabRules": "Benachrichtigungsregeln", + "alertingTabHealthChecks": "Gesundheits-Checks", + "alertingRulesBannerTitle": "Benachrichtigt werden", + "alertingRulesBannerDescription": "Jede Regel verknüpft, was beobachtet werden soll (eine Seite, ein Gesundheits-Check oder eine Ressource), wann es ausgelöst werden soll (zum Beispiel offline oder ungesund), und wie Ihr Team benachrichtigt wird, z. B. per E-Mail, Webhooks oder Integrationen. Verwenden Sie diese Liste, um diese Regeln zu erstellen, zu aktivieren und zu verwalten.", + "alertingHealthChecksBannerTitle": "Gesundheit & Ressourcen überwachen", + "alertingHealthChecksBannerDescription": "Gesundheits-Checks sind HTTP- oder TCP-Monitore, die Sie einmal definieren. Sie können sie dann als Quellen in Benachrichtigungsregeln verwenden, so dass Sie benachrichtigt werden, wenn ein Ziel gesund oder ungesund wird. Gesundheits-Checks für Ressourcen erscheinen ebenfalls hier.", + "standaloneHcTableTitle": "Gesundheits-Checks", + "standaloneHcSearchPlaceholder": "Gesundheits-Checks suchen…", + "standaloneHcAddButton": "Gesundheits-Check erstellen", + "standaloneHcCreateTitle": "Gesundheits-Check erstellen", + "standaloneHcEditTitle": "Gesundheits-Check bearbeiten", + "standaloneHcDescription": "Konfigurieren Sie einen HTTP- oder TCP-Gesundheits-Check zur Verwendung in Benachrichtigungsregeln.", + "standaloneHcNameLabel": "Name", + "standaloneHcNamePlaceholder": "Mein HTTP-Monitor", + "standaloneHcDeleteTitle": "Gesundheits-Check löschen", + "standaloneHcDeleteQuestion": "Bitte bestätigen Sie, dass Sie diesen Gesundheits-Check löschen möchten.", + "standaloneHcDeleted": "Gesundheits-Check gelöscht", + "standaloneHcSaved": "Gesundheits-Check gespeichert", + "standaloneHcColumnHealth": "Gesundheit", + "standaloneHcColumnMode": "Modus", + "standaloneHcColumnTarget": "Ziel", + "standaloneHcHealthStateHealthy": "Gesund", + "standaloneHcHealthStateUnhealthy": "Ungesund", + "standaloneHcHealthStateUnknown": "Unbekannt", + "standaloneHcFilterAnySite": "Alle Standorte", + "standaloneHcFilterAnyResource": "Alle Ressourcen", + "standaloneHcFilterMode": "Modus", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "Ping", + "standaloneHcFilterHealth": "Gesundheit", + "standaloneHcFilterEnabled": "Aktiviert", + "standaloneHcFilterEnabledOn": "Aktiviert", + "standaloneHcFilterEnabledOff": "Deaktiviert", + "standaloneHcFilterSiteIdFallback": "Standort {id}", + "standaloneHcFilterResourceIdFallback": "Ressource {id}", "blueprints": "Blaupausen", "blueprintsDescription": "Deklarative Konfigurationen anwenden und vorherige Abläufe anzeigen", "blueprintAdd": "Blueprint hinzufügen", @@ -1763,6 +1935,15 @@ "healthCheckIntervalMin": "Prüfintervall muss mindestens 5 Sekunden betragen", "healthCheckTimeoutMin": "Zeitüberschreitung muss mindestens 1 Sekunde betragen", "healthCheckRetryMin": "Wiederholungsversuche müssen mindestens 1 betragen", + "healthCheckMode": "Überprüfungsmodus", + "healthCheckStrategy": "Strategie", + "healthCheckModeDescription": "TCP-Modus überprüft nur die Konnektivität. HTTP-Modus validiert die HTTP-Antwort.", + "healthyThreshold": "Gesundheitsschwelle", + "healthyThresholdDescription": "Erforderliche aufeinanderfolgende Erfolge, bevor als gesund markiert wird.", + "unhealthyThreshold": "Ungesunde Schwelle", + "unhealthyThresholdDescription": "Erforderliche aufeinanderfolgende Fehlschläge, bevor als ungesund markiert wird.", + "healthCheckHealthyThresholdMin": "Gesundheitsschwelle muss mindestens 1 betragen", + "healthCheckUnhealthyThresholdMin": "Ungesunde Schwelle muss mindestens 1 betragen", "httpMethod": "HTTP-Methode", "selectHttpMethod": "HTTP-Methode auswählen", "domainPickerSubdomainLabel": "Subdomain", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "Port", "editInternalResourceDialogModeHost": "Host", "editInternalResourceDialogModeCidr": "CIDR", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "Schema", + "editInternalResourceDialogEnableSsl": "SSL aktivieren", + "editInternalResourceDialogEnableSslDescription": "SSL/TLS-Verschlüsselung für sichere HTTPS-Verbindungen zum Ziel aktivieren.", "editInternalResourceDialogDestination": "Ziel", "editInternalResourceDialogDestinationHostDescription": "Die IP-Adresse oder der Hostname der Ressource im Netzwerk der Website.", "editInternalResourceDialogDestinationIPDescription": "Die IP-Adresse oder Hostname Adresse der Ressource im Netzwerk der Website.", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "Name", "createInternalResourceDialogSite": "Standort", "selectSite": "Standort auswählen...", + "multiSitesSelectorSitesCount": "{count, plural, one {# Standort} other {# Standorte}}", "noSitesFound": "Keine Standorte gefunden.", "createInternalResourceDialogProtocol": "Protokoll", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "Port", "createInternalResourceDialogModeHost": "Host", "createInternalResourceDialogModeCidr": "CIDR", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "Schema", + "createInternalResourceDialogScheme": "Schema", + "createInternalResourceDialogEnableSsl": "SSL aktivieren", + "createInternalResourceDialogEnableSslDescription": "SSL/TLS-Verschlüsselung für sichere HTTPS-Verbindungen zum Ziel aktivieren.", "createInternalResourceDialogDestination": "Ziel", "createInternalResourceDialogDestinationHostDescription": "Die IP-Adresse oder der Hostname der Ressource im Netzwerk der Website.", "createInternalResourceDialogDestinationCidrDescription": "Der CIDR-Bereich der Ressource im Netzwerk der Website.", "createInternalResourceDialogAlias": "Alias", "createInternalResourceDialogAliasDescription": "Ein optionaler interner DNS-Alias für diese Ressource.", + "internalResourceDownstreamSchemeRequired": "Schema ist für HTTP-Ressourcen erforderlich", + "internalResourceHttpPortRequired": "Zielport ist für HTTP-Ressourcen erforderlich", "siteConfiguration": "Konfiguration", "siteAcceptClientConnections": "Clientverbindungen akzeptieren", "siteAcceptClientConnectionsDescription": "Erlaube Benutzer-Geräten und Clients Zugriff auf Ressourcen auf diesem Standort. Dies kann später geändert werden.", @@ -2297,7 +2492,7 @@ "alerts": { "commercialUseDisclosure": { "title": "Verwendungsanzeige", - "description": "Wählen Sie die Lizenz-Ebene, die Ihre beabsichtigte Nutzung genau widerspiegelt. Die Persönliche Lizenz erlaubt die freie Nutzung der Software für individuelle, nicht-kommerzielle oder kleine kommerzielle Aktivitäten mit jährlichen Brutto-Einnahmen von 100.000 USD. Über diese Grenzen hinausgehende Verwendungszwecke – einschließlich der Verwendung innerhalb eines Unternehmens, einer Organisation, oder eine andere umsatzgenerierende Umgebung — erfordert eine gültige Enterprise-Lizenz und die Zahlung der Lizenzgebühr. Alle Benutzer, ob Personal oder Enterprise, müssen die Fossorial Commercial License Bedingungen einhalten." + "description": "Wählen Sie die Lizenz-Ebene, die Ihre beabsichtigte Nutzung genau widerspiegelt. Die Persönliche Lizenz erlaubt die freie Nutzung der Software für individuelle, nicht-kommerzielle oder kleine kommerzielle Aktivitäten mit jährlichen Brutto-Einnahmen von 100.000 USD. Über diese Grenzen hinausgehende Verwendungszwecke – einschließlich der Verwendung innerhalb eines Unternehmens, einer Organisation, oder eine andere umsatzgenerierende Umgebung - erfordert eine gültige Enterprise-Lizenz und die Zahlung der Lizenzgebühr. Alle Benutzer, ob Personal oder Enterprise, müssen die Fossorial Commercial License Bedingungen einhalten." }, "trialPeriodInformation": { "title": "Testperiode Information", @@ -2429,6 +2624,7 @@ "validPassword": "Gültiges Passwort", "validEmail": "Gültige E-Mail-Adresse", "validSSO": "Gültige SSO-Anmeldung", + "connectedClient": "Verbundenes Gerät", "resourceBlocked": "Ressource blockiert", "droppedByRule": "Abgelegt durch Regel", "noSessions": "Keine Sitzungen", @@ -2668,6 +2864,10 @@ "editInternalResourceDialogDestinationLabel": "Ziel", "editInternalResourceDialogDestinationDescription": "Geben Sie die Zieladresse für die interne Ressource an. Dies kann ein Hostname, eine IP-Adresse oder ein CIDR-Bereich sein, abhängig vom gewählten Modus. Legen Sie optional einen internen DNS-Alias für eine vereinfachte Identifizierung fest.", "editInternalResourceDialogPortRestrictionsDescription": "Den Zugriff auf bestimmte TCP/UDP-Ports beschränken oder alle Ports erlauben/blockieren.", + "createInternalResourceDialogHttpConfiguration": "HTTP-Konfiguration", + "createInternalResourceDialogHttpConfigurationDescription": "Wählen Sie die Domain, die Clients verwenden, um über HTTP oder HTTPS auf diese Ressource zuzugreifen.", + "editInternalResourceDialogHttpConfiguration": "HTTP-Konfiguration", + "editInternalResourceDialogHttpConfigurationDescription": "Wählen Sie die Domain, die Clients verwenden, um über HTTP oder HTTPS auf diese Ressource zuzugreifen.", "editInternalResourceDialogTcp": "TCP", "editInternalResourceDialogUdp": "UDP", "editInternalResourceDialogIcmp": "ICMP", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "Wir sind bald wieder da! Unsere Seite wird derzeit planmäßig gewartet.", "maintenancePageMessageDescription": "Detaillierte Meldung zur Erklärung der Wartung", "maintenancePageTimeTitle": "Geschätzte Abschlusszeit (Optional)", + "privateMaintenanceScreenTitle": "Privater Platzhalterschirm", + "privateMaintenanceScreenMessage": "Diese Domain wird auf einer privaten Ressource verwendet. Bitte verbinden Sie sich mit dem Pangolin-Client, um auf diese Ressource zuzugreifen.", "maintenanceTime": "z.B.: 2 Stunden, Nov 1 um 17:00 Uhr", "maintenanceEstimatedTimeDescription": "Wann Sie den Abschluss der Wartung erwarten", "editDomain": "Domain bearbeiten", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "HTTP-Ziel hinzufügen", "httpDestEditDescription": "Aktualisiere die Konfiguration für dieses HTTP-Streaming-Ziel.", "httpDestAddDescription": "Konfigurieren Sie einen neuen HTTP-Endpunkt, um die Ereignisse Ihrer Organisation zu empfangen.", + "S3DestEditTitle": "Ziel bearbeiten", + "S3DestAddTitle": "S3-Ziel hinzufügen", + "S3DestEditDescription": "Konfiguration für dieses S3-Ereignis-Streamingziel aktualisieren.", + "S3DestAddDescription": "Neuen S3-Endpunkt konfigurieren, um die Ereignisse Ihrer Organisation zu erhalten.", + "datadogDestEditTitle": "Ziel bearbeiten", + "datadogDestAddTitle": "Datadog-Ziel hinzufügen", + "datadogDestEditDescription": "Konfiguration für dieses Datadog-Ereignis-Streamingziel aktualisieren.", + "datadogDestAddDescription": "Neuen Datadog-Endpunkt konfigurieren, um die Ereignisse Ihrer Organisation zu erhalten.", "httpDestTabSettings": "Einstellungen", "httpDestTabHeaders": "Kopfzeilen", "httpDestTabBody": "Körper", @@ -2882,7 +3092,7 @@ "httpDestFormatJsonArrayTitle": "JSON Array", "httpDestFormatJsonArrayDescription": "Eine Anfrage pro Stapel ist ein JSON-Array. Kompatibel mit den meisten generischen Webhooks und Datadog.", "httpDestFormatNdjsonTitle": "NDJSON", - "httpDestFormatNdjsonDescription": "Eine Anfrage pro Batch, der Körper ist newline-getrenntes JSON — ein Objekt pro Zeile, kein äußeres Array. Benötigt von Splunk HEC, Elastic / OpenSearch, und Grafana Loki.", + "httpDestFormatNdjsonDescription": "Eine Anfrage pro Batch, der Körper ist newline-getrenntes JSON - ein Objekt pro Zeile, kein äußeres Array. Benötigt von Splunk HEC, Elastic / OpenSearch, und Grafana Loki.", "httpDestFormatSingleTitle": "Ein Ereignis pro Anfrage", "httpDestFormatSingleDescription": "Sendet eine separate HTTP-POST für jedes einzelne Ereignis. Nur für Endpunkte, die Batches nicht handhaben können.", "httpDestLogTypesTitle": "Log-Typen", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "Ziel erfolgreich erstellt", "httpDestUpdateFailed": "Fehler beim Aktualisieren des Ziels", "httpDestCreateFailed": "Fehler beim Erstellen des Ziels", + "followRedirects": "Weiterleitungen folgen", + "followRedirectsDescription": "HTTP-Weiterleitungen für Anfragen automatisch folgen.", + "alertingErrorWebhookUrl": "Bitte geben Sie eine gültige URL für das Webhook ein.", + "healthCheckStrategyHttp": "Prüft die Konnektivität und den HTTP-Antwort-Status.", + "healthCheckStrategyTcp": "Verifiziert nur die TCP-Konnektivität, ohne die Antwort zu überprüfen.", + "healthCheckStrategySnmp": "Stellt eine SNMP-Get-Anfrage, um die Gesundheit von Netzwerkgeräten und Infrastruktur zu überprüfen.", + "healthCheckStrategyIcmp": "Verwendet ICMP-Echo-Anfragen (Pings), um zu überprüfen, ob eine Ressource erreichbar und reaktionsfähig ist.", + "healthCheckTabStrategy": "Strategie", + "healthCheckTabConnection": "Verbindung", + "healthCheckTabAdvanced": "Fortgeschritten", + "healthCheckStrategyNotAvailable": "Diese Strategie ist nicht verfügbar. Bitte kontaktieren Sie den Vertrieb, um diese Funktion zu aktivieren.", + "uptime30d": "Betriebszeit (30 Tage)", "idpAddActionCreateNew": "Neuen Identitätsanbieter erstellen", "idpAddActionImportFromOrg": "Von einer anderen Organisation importieren", "idpImportDialogTitle": "Identitätsanbieter importieren", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "Dies kann für diese Organisation nicht rückgängig gemacht werden.", "idpUnassociatedDescription": "Identitätsanbieter erfolgreich von dieser Organisation gelöst", "idpUnassociateMenu": "Verknüpfung aufheben", - "idpDeleteAllOrgsMenu": "Löschen" + "idpDeleteAllOrgsMenu": "Löschen", + "publicIpEndpoint": "Endpunkt", + "lastTriggeredAt": "Letzter Auslöser", + "reject": "Zurückweisen" } diff --git a/messages/en-US.json b/messages/en-US.json index ff09dc4fd..8414f0a2f 100644 --- a/messages/en-US.json +++ b/messages/en-US.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "Contact sales to enable this feature.", + "contactSalesBookDemo": "Book a demo", + "contactSalesOr": "or", + "contactSalesContactUs": "contact us", "setupCreate": "Create the organization, site, and resources", "headerAuthCompatibilityInfo": "Enable this to force a 401 Unauthorized response when an authentication token is missing. This is required for browsers or specific HTTP libraries that do not send credentials without a server challenge.", "headerAuthCompatibility": "Extended compatibility", @@ -19,6 +23,14 @@ "componentsInvalidKey": "Invalid or expired license keys detected. Follow license terms to continue using all features.", "dismiss": "Dismiss", "subscriptionViolationMessage": "You're beyond your limits for your current plan. Correct the problem by removing sites, users, or other resources to stay within your plan.", + "trialBannerMessage": "Your trial expires in {countdown}. Upgrade to keep access.", + "trialBannerExpired": "Your trial has expired. Upgrade now to restore access.", + "trialActive": "Free Trial Active", + "trialExpired": "Trial Expired", + "trialHasEnded": "Your trial has ended.", + "trialDaysRemaining": "{count, plural, one {# day remaining} other {# days remaining}}", + "trialDaysLeftShort": "{days}d left in trial", + "trialGoToBilling": "Go to billing page", "subscriptionViolationViewBilling": "View billing", "componentsLicenseViolation": "License Violation: This server is using {usedSites} sites which exceeds its licensed limit of {maxSites} sites. Follow license terms to continue using all features.", "componentsSupporterMessage": "Thank you for supporting Pangolin as a {tier}!", @@ -163,7 +175,7 @@ "proxyResourceTitle": "Manage Public Resources", "proxyResourceDescription": "Create and manage resources that are publicly accessible through a web browser", "proxyResourcesBannerTitle": "Web-based Public Access", - "proxyResourcesBannerDescription": "Public resources are HTTPS or TCP/UDP proxies accessible to anyone on the internet through a web browser. Unlike private resources, they do not require client-side software and can include identity and context-aware access policies.", + "proxyResourcesBannerDescription": "Public resources are HTTPS proxies accessible to anyone on the internet through a web browser. Unlike private resources, they do not require client-side software and can include identity and context-aware access policies.", "clientResourceTitle": "Manage Private Resources", "clientResourceDescription": "Create and manage resources that are only accessible through a connected client", "privateResourcesBannerTitle": "Zero-Trust Private Access", @@ -267,8 +279,11 @@ "orgMissing": "Organization ID Missing", "orgMissingMessage": "Unable to regenerate invitation without an organization ID.", "accessUsersManage": "Manage Users", + "accessUserManage": "Manage User", "accessUsersDescription": "Invite and manage users with access to this organization", "accessUsersSearch": "Search users...", + "accessUsersRoleFilterCount": "{count, plural, one {# role} other {# roles}}", + "accessUsersRoleFilterClear": "Clear role filters", "accessUserCreate": "Create User", "accessUserRemove": "Remove User", "username": "Username", @@ -380,7 +395,7 @@ "userTitle": "Manage All Users", "userDescription": "View and manage all users in the system", "userAbount": "About User Management", - "userAbountDescription": "This table displays all root user objects in the system. Each user may belong to multiple organizations. Removing a user from an organization does not delete their root user object - they will remain in the system. To completely remove a user from the system, you must delete their root user object using the delete action in this table.", + "userAbountDescription": "This table displays all base user objects in the system. Each user may belong to multiple organizations. Removing a user from an organization does not delete their base user object. They will remain in the system. To completely remove a user from the system, you must delete their base user object using the delete action in this table.", "userServer": "Server Users", "userSearch": "Search server users...", "userErrorDelete": "Error deleting user", @@ -523,7 +538,7 @@ "userSettings": "User Information", "userSettingsDescription": "Enter the details for the new user", "inviteEmailSent": "Send invite email to user", - "inviteValid": "Valid For", + "inviteValid": "Invite Valid For (days)", "selectDuration": "Select duration", "selectResource": "Select Resource", "filterByResource": "Filter By Resource", @@ -1257,6 +1272,7 @@ "actionViewLogs": "View Logs", "noneSelected": "None selected", "orgNotFound2": "No organizations found.", + "search": "Search…", "searchPlaceholder": "Search...", "emptySearchOptions": "No options found", "create": "Create", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "Manage", "sidebarLogAndAnalytics": "Log & Analytics", "sidebarBluePrints": "Blueprints", + "sidebarAlerting": "Alerting", + "sidebarHealthChecks": "Health checks", "sidebarOrganization": "Organization", "sidebarManagement": "Management", "sidebarBillingAndLicenses": "Billing & Licenses", "sidebarLogsAnalytics": "Analytics", + "alertingTitle": "Alerting", + "alertingDescription": "Define sources, triggers, and actions for notifications", + "alertingRules": "Alert rules", + "alertingSearchRules": "Search rules…", + "alertingAddRule": "Create Rule", + "alertingColumnSource": "Source", + "alertingColumnTrigger": "Trigger", + "alertingColumnActions": "Actions", + "alertingColumnEnabled": "Enabled", + "alertingDeleteQuestion": "Please confirm you want to delete this alert rule.", + "alertingDeleteRule": "Delete alert rule", + "alertingRuleDeleted": "Alert rule deleted", + "alertingRuleSaved": "Alert rule saved", + "alertingRuleSavedCreatedDescription": "Your new alert rule was created. You can keep editing it on this page.", + "alertingRuleSavedUpdatedDescription": "Your changes to this alert rule were saved.", + "alertingEditRule": "Edit Alert Rule", + "alertingCreateRule": "Create Alert Rule", + "alertingRuleCredenzaDescription": "Choose what to watch, when to fire, and how to notify", + "alertingRuleNamePlaceholder": "Production site down", + "alertingRuleEnabled": "Rule enabled", + "alertingSectionSource": "Source", + "alertingSourceType": "Source type", + "alertingSourceSite": "Site", + "alertingSourceHealthCheck": "Health check", + "alertingPickSites": "Sites", + "alertingPickHealthChecks": "Health checks", + "alertingPickResources": "Resources", + "alertingAllSites": "All Sites", + "alertingAllSitesDescription": "Alert fires for any site", + "alertingSpecificSites": "Specific Sites", + "alertingSpecificSitesDescription": "Choose specific sites to watch", + "alertingAllHealthChecks": "All Health Checks", + "alertingAllHealthChecksDescription": "Alert fires for any health check", + "alertingSpecificHealthChecks": "Specific Health Checks", + "alertingSpecificHealthChecksDescription": "Choose specific health checks to watch", + "alertingAllResources": "All Resources", + "alertingAllResourcesDescription": "Alert fires for any resource", + "alertingSpecificResources": "Specific Resources", + "alertingSpecificResourcesDescription": "Choose specific resources to watch", + "alertingSelectResources": "Select resources…", + "alertingResourcesSelected": "{count} resources selected", + "alertingResourcesEmpty": "No resources with targets in the first 10 results.", + "alertingSectionTrigger": "Trigger", + "alertingTrigger": "When to alert", + "alertingTriggerSiteOnline": "Site online", + "alertingTriggerSiteOffline": "Site offline", + "alertingTriggerSiteToggle": "Site status changes", + "alertingTriggerHcHealthy": "Health check healthy", + "alertingTriggerHcUnhealthy": "Health check unhealthy", + "alertingTriggerHcToggle": "Health check status changes", + "alertingTriggerResourceHealthy": "Resource healthy", + "alertingTriggerResourceUnhealthy": "Resource unhealthy", + "alertingSearchHealthChecks": "Search health checks…", + "alertingHealthChecksEmpty": "No health checks available.", + "alertingTriggerResourceToggle": "Resource status changes", + "alertingSourceResource": "Resource", + "alertingSectionActions": "Actions", + "alertingAddAction": "Add Action", + "alertingActionNotify": "Email", + "alertingActionNotifyDescription": "Send email notifications to users or roles", + "alertingActionWebhook": "Webhook", + "alertingActionWebhookDescription": "Send an HTTP request to a custom endpoint", + "alertingExternalIntegration": "External Integration", + "alertingExternalPagerDutyDescription": "Send alerts to PagerDuty for incident management", + "alertingExternalOpsgenieDescription": "Route alerts to Opsgenie for on-call management", + "alertingExternalServiceNowDescription": "Create ServiceNow incidents from alert events", + "alertingExternalIncidentIoDescription": "Trigger Incident.io workflows from alert events", + "alertingActionType": "Action type", + "alertingNotifyUsers": "Users", + "alertingNotifyRoles": "Roles", + "alertingNotifyEmails": "Email addresses", + "alertingEmailPlaceholder": "Add email and press Enter", + "alertingWebhookMethod": "HTTP method", + "alertingWebhookSecret": "Signing secret (optional)", + "alertingWebhookSecretPlaceholder": "HMAC secret", + "alertingWebhookHeaders": "Headers", + "alertingAddHeader": "Add header", + "alertingSelectSites": "Select sites…", + "alertingSitesSelected": "{count} sites selected", + "alertingSelectHealthChecks": "Select health checks…", + "alertingHealthChecksSelected": "{count} health checks selected", + "alertingNoHealthChecks": "No targets with health checks enabled", + "alertingHealthCheckStub": "Health check source selection is not wired up yet - you can still configure triggers and actions.", + "alertingSelectUsers": "Select users…", + "alertingUsersSelected": "{count} users selected", + "alertingSelectRoles": "Select roles…", + "alertingRolesSelected": "{count} roles selected", + "alertingSummarySites": "Sites ({count})", + "alertingSummaryAllSites": "All sites", + "alertingSummaryHealthChecks": "Health checks ({count})", + "alertingSummaryAllHealthChecks": "All health checks", + "alertingSummaryResources": "Resources ({count})", + "alertingSummaryAllResources": "All resources", + "alertingErrorNameRequired": "Enter a name", + "alertingErrorActionsMin": "Add at least one action", + "alertingErrorPickSites": "Select at least one site", + "alertingErrorPickHealthChecks": "Select at least one health check", + "alertingErrorPickResources": "Select at least one resource", + "alertingErrorTriggerSite": "Choose a site trigger", + "alertingErrorTriggerHealth": "Choose a health check trigger", + "alertingErrorTriggerResource": "Choose a resource trigger", + "alertingErrorNotifyRecipients": "Pick users, roles, or at least one email", + "alertingConfigureSource": "Configure Source", + "alertingConfigureTrigger": "Configure Trigger", + "alertingConfigureActions": "Configure Actions", + "alertingBackToRules": "Back to Rules", + "alertingRuleCooldown": "Cooldown (seconds)", + "alertingRuleCooldownDescription": "Minimum time between repeated alerts for the same rule. Set to 0 to fire every time.", + "alertingDraftBadge": "Draft - save to store this rule", + "alertingSidebarHint": "Click a step on the canvas to edit it here.", + "alertingGraphCanvasTitle": "Rule Flow", + "alertingGraphCanvasDescription": "Visual overview of source, trigger, and actions. Select a node to edit it in the panel.", + "alertingNodeNotConfigured": "Not configured yet", + "alertingNodeActionsCount": "{count, plural, one {# action} other {# actions}}", + "alertingNodeRoleSource": "Source", + "alertingNodeRoleTrigger": "Trigger", + "alertingNodeRoleAction": "Action", + "alertingTabRules": "Alert Rules", + "alertingTabHealthChecks": "Health Checks", + "alertingRulesBannerTitle": "Get Notified", + "alertingRulesBannerDescription": "Each rule ties together what to watch (a site, health check, or resource), when to fire (for example offline or unhealthy), and how to notify your team via email, webhooks, or integrations. Use this list to create, enable, and manage those rules.", + "alertingHealthChecksBannerTitle": "Monitor Health & Resources", + "alertingHealthChecksBannerDescription": "Health checks are HTTP or TCP monitors you define once. You can then use them as sources in alert rules so you get notified when a target becomes healthy or unhealthy. Health checks on resources also appear here.", + "standaloneHcTableTitle": "Health Checks", + "standaloneHcSearchPlaceholder": "Search health checks…", + "standaloneHcAddButton": "Create Health Check", + "standaloneHcCreateTitle": "Create Health Check", + "standaloneHcEditTitle": "Edit Health Check", + "standaloneHcDescription": "Configure a HTTP or TCP health check for use in alert rules.", + "standaloneHcNameLabel": "Name", + "standaloneHcNamePlaceholder": "My HTTP Monitor", + "standaloneHcDeleteTitle": "Delete health check", + "standaloneHcDeleteQuestion": "Please confirm you want to delete this health check.", + "standaloneHcDeleted": "Health check deleted", + "standaloneHcSaved": "Health check saved", + "standaloneHcColumnHealth": "Health", + "standaloneHcColumnMode": "Mode", + "standaloneHcColumnTarget": "Target", + "standaloneHcHealthStateHealthy": "Healthy", + "standaloneHcHealthStateUnhealthy": "Unhealthy", + "standaloneHcHealthStateUnknown": "Unknown", + "standaloneHcFilterAnySite": "All sites", + "standaloneHcFilterAnyResource": "All resources", + "standaloneHcFilterMode": "Mode", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "Ping", + "standaloneHcFilterHealth": "Health", + "standaloneHcFilterEnabled": "Enabled", + "standaloneHcFilterEnabledOn": "Enabled", + "standaloneHcFilterEnabledOff": "Disabled", + "standaloneHcFilterSiteIdFallback": "Site {id}", + "standaloneHcFilterResourceIdFallback": "Resource {id}", "blueprints": "Blueprints", "blueprintsDescription": "Apply declarative configurations and view previous runs", "blueprintAdd": "Add Blueprint", @@ -1750,8 +1922,8 @@ "retryAttempts": "Retry Attempts", "expectedResponseCodes": "Expected Response Codes", "expectedResponseCodesDescription": "HTTP status code that indicates healthy status. If left blank, 200-300 is considered healthy.", - "customHeaders": "Custom Headers", - "customHeadersDescription": "Headers new line separated: Header-Name: value", + "customHeaders": "Custom Request Headers", + "customHeadersDescription": "Request headers sent to the downstream targets. Headers new line separated: Header-Name: value", "headersValidationError": "Headers must be in the format: Header-Name: value", "saveHealthCheck": "Save Health Check", "healthCheckSaved": "Health Check Saved", @@ -1763,8 +1935,17 @@ "healthCheckIntervalMin": "Check interval must be at least 5 seconds", "healthCheckTimeoutMin": "Timeout must be at least 1 second", "healthCheckRetryMin": "Retry attempts must be at least 1", - "httpMethod": "HTTP Method", - "selectHttpMethod": "Select HTTP method", + "healthCheckMode": "Check Mode", + "healthCheckStrategy": "Strategy", + "healthCheckModeDescription": "TCP mode verifies connectivity only. HTTP mode validates the HTTP response.", + "healthyThreshold": "Healthy Threshold", + "healthyThresholdDescription": "Consecutive successes required before marking as healthy.", + "unhealthyThreshold": "Unhealthy Threshold", + "unhealthyThresholdDescription": "Consecutive failures required before marking as unhealthy.", + "healthCheckHealthyThresholdMin": "Healthy threshold must be at least 1", + "healthCheckUnhealthyThresholdMin": "Unhealthy threshold must be at least 1", + "httpMethod": "Scheme", + "selectHttpMethod": "Select scheme", "domainPickerSubdomainLabel": "Subdomain", "domainPickerBaseDomainLabel": "Base Domain", "domainPickerSearchDomains": "Search domains...", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "Port", "editInternalResourceDialogModeHost": "Host", "editInternalResourceDialogModeCidr": "CIDR", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "Scheme", + "editInternalResourceDialogEnableSsl": "Enable SSL", + "editInternalResourceDialogEnableSslDescription": "Enable SSL/TLS encryption for secure HTTPS connections to the destination.", "editInternalResourceDialogDestination": "Destination", "editInternalResourceDialogDestinationHostDescription": "The IP address or hostname of the resource on the site's network.", "editInternalResourceDialogDestinationIPDescription": "The IP or hostname address of the resource on the site's network.", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "Name", "createInternalResourceDialogSite": "Site", "selectSite": "Select site...", + "multiSitesSelectorSitesCount": "{count, plural, one {# site} other {# sites}}", "noSitesFound": "No sites found.", "createInternalResourceDialogProtocol": "Protocol", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "Port", "createInternalResourceDialogModeHost": "Host", "createInternalResourceDialogModeCidr": "CIDR", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "Scheme", + "createInternalResourceDialogScheme": "Scheme", + "createInternalResourceDialogEnableSsl": "Enable SSL", + "createInternalResourceDialogEnableSslDescription": "Enable SSL/TLS encryption for secure HTTPS connections to the destination.", "createInternalResourceDialogDestination": "Destination", "createInternalResourceDialogDestinationHostDescription": "The IP address or hostname of the resource on the site's network.", "createInternalResourceDialogDestinationCidrDescription": "The CIDR range of the resource on the site's network.", "createInternalResourceDialogAlias": "Alias", "createInternalResourceDialogAliasDescription": "An optional internal DNS alias for this resource.", + "internalResourceDownstreamSchemeRequired": "Scheme is required for HTTP resources", + "internalResourceHttpPortRequired": "Destination port is required for HTTP resources", "siteConfiguration": "Configuration", "siteAcceptClientConnections": "Accept Client Connections", "siteAcceptClientConnectionsDescription": "Allow user devices and clients to access resources on this site. This can be changed later.", @@ -1994,7 +2189,7 @@ "description": "More reliable and low-maintenance self-hosted Pangolin server with extra bells and whistles", "introTitle": "Managed Self-Hosted Pangolin", "introDescription": "is a deployment option designed for people who want simplicity and extra reliability while still keeping their data private and self-hosted.", - "introDetail": "With this option, you still run your own Pangolin node — your tunnels, SSL termination, and traffic all stay on your server. The difference is that management and monitoring are handled through our cloud dashboard, which unlocks a number of benefits:", + "introDetail": "With this option, you still run your own Pangolin node - your tunnels, SSL termination, and traffic all stay on your server. The difference is that management and monitoring are handled through our cloud dashboard, which unlocks a number of benefits:", "benefitSimplerOperations": { "title": "Simpler operations", "description": "No need to run your own mail server or set up complex alerting. You'll get health checks and downtime alerts out of the box." @@ -2119,7 +2314,7 @@ "selectDomainForOrgAuthPage": "Select a domain for the organization's authentication page", "domainPickerProvidedDomain": "Provided Domain", "domainPickerFreeProvidedDomain": "Provided Domain", - "domainPickerFreeDomainsPaidFeature": "Provided domains are a paid feature. Subscribe to get a domain included with your plan — no need to bring your own.", + "domainPickerFreeDomainsPaidFeature": "Provided domains are a paid feature. Subscribe to get a domain included with your plan - no need to bring your own.", "domainPickerVerified": "Verified", "domainPickerUnverified": "Unverified", "domainPickerManual": "Manual", @@ -2297,7 +2492,7 @@ "alerts": { "commercialUseDisclosure": { "title": "Usage Disclosure", - "description": "Select the license tier that accurately reflects your intended use. The Personal License permits free use of the Software for individual, non-commercial or small-scale commercial activities with annual gross revenue under $100,000 USD. Any use beyond these limits — including use within a business, organization, or other revenue-generating environment — requires a valid Enterprise License and payment of the applicable licensing fee. All users, whether Personal or Enterprise, must comply with the Fossorial Commercial License Terms." + "description": "Select the license tier that accurately reflects your intended use. The Personal License permits free use of the Software for individual, non-commercial or small-scale commercial activities with annual gross revenue under $100,000 USD. Any use beyond these limits - including use within a business, organization, or other revenue-generating environment - requires a valid Enterprise License and payment of the applicable licensing fee. All users, whether Personal or Enterprise, must comply with the Fossorial Commercial License Terms." }, "trialPeriodInformation": { "title": "Trial Period Information", @@ -2416,7 +2611,7 @@ "action": "Action", "actor": "Actor", "timestamp": "Timestamp", - "accessLogs": "Access Logs", + "accessLogs": "Authentication Logs", "exportCsv": "Export CSV", "exportError": "Unknown error when exporting CSV", "exportCsvTooltip": "Within Time Range", @@ -2429,6 +2624,7 @@ "validPassword": "Valid Password", "validEmail": "Valid email", "validSSO": "Valid SSO", + "connectedClient": "Connected Client", "resourceBlocked": "Resource Blocked", "droppedByRule": "Dropped by Rule", "noSessions": "No Sessions", @@ -2436,25 +2632,25 @@ "noMoreAuthMethods": "No Valid Auth", "ip": "IP", "reason": "Reason", - "requestLogs": "Request Logs", + "requestLogs": "HTTPS Request Logs", "requestAnalytics": "Request Analytics", "host": "Host", "location": "Location", - "actionLogs": "Action Logs", - "sidebarLogsRequest": "Request Logs", - "sidebarLogsAccess": "Access Logs", - "sidebarLogsAction": "Action Logs", + "actionLogs": "Admin Action Logs", + "sidebarLogsRequest": "HTTPS Request Logs", + "sidebarLogsAccess": "Authentication Logs", + "sidebarLogsAction": "Admin Action Logs", "logRetention": "Log Retention", "logRetentionDescription": "Manage how long different types of logs are retained for this organization or disable them", - "requestLogsDescription": "View detailed request logs for resources in this organization", + "requestLogsDescription": "View detailed request logs for HTTPS resources in this organization", "requestAnalyticsDescription": "View detailed request analytics for resources in this organization", - "logRetentionRequestLabel": "Request Log Retention", + "logRetentionRequestLabel": "HTTPS Request Log Retention", "logRetentionRequestDescription": "How long to retain request logs", - "logRetentionAccessLabel": "Access Log Retention", + "logRetentionAccessLabel": "Authentication Log Retention", "logRetentionAccessDescription": "How long to retain access logs", - "logRetentionActionLabel": "Action Log Retention", + "logRetentionActionLabel": "Admin Action Log Retention", "logRetentionActionDescription": "How long to retain action logs", - "logRetentionConnectionLabel": "Connection Log Retention", + "logRetentionConnectionLabel": "Network Log Retention", "logRetentionConnectionDescription": "How long to retain connection logs", "logRetentionDisabled": "Disabled", "logRetention3Days": "3 days", @@ -2466,10 +2662,10 @@ "logRetentionEndOfFollowingYear": "End of following year", "actionLogsDescription": "View a history of actions performed in this organization", "accessLogsDescription": "View access auth requests for resources in this organization", - "connectionLogs": "Connection Logs", - "connectionLogsDescription": "View connection logs for tunnels in this organization", - "sidebarLogsConnection": "Connection Logs", - "sidebarLogsStreaming": "Streaming", + "connectionLogs": "Network Logs", + "connectionLogsDescription": "View network session logs handled by sites in this organization", + "sidebarLogsConnection": "Network Logs", + "sidebarLogsStreaming": "Event Streaming", "sourceAddress": "Source Address", "destinationAddress": "Destination Address", "duration": "Duration", @@ -2666,8 +2862,12 @@ "editInternalResourceDialogAddUsers": "Add Users", "editInternalResourceDialogAddClients": "Add Clients", "editInternalResourceDialogDestinationLabel": "Destination", - "editInternalResourceDialogDestinationDescription": "Specify the destination address for the internal resource. This can be a hostname, IP address, or CIDR range depending on the selected mode. Optionally set an internal DNS alias for easier identification.", + "editInternalResourceDialogDestinationDescription": "Choose where this resource runs and how clients reach it. Selecting multiple sites will create a high availability resource that can be accessed from any of the selected sites.", "editInternalResourceDialogPortRestrictionsDescription": "Restrict access to specific TCP/UDP ports or allow/block all ports.", + "createInternalResourceDialogHttpConfiguration": "HTTP configuration", + "createInternalResourceDialogHttpConfigurationDescription": "Choose the domain clients will use to reach this resource over HTTP or HTTPS.", + "editInternalResourceDialogHttpConfiguration": "HTTP configuration", + "editInternalResourceDialogHttpConfigurationDescription": "Choose the domain clients will use to reach this resource over HTTP or HTTPS.", "editInternalResourceDialogTcp": "TCP", "editInternalResourceDialogUdp": "UDP", "editInternalResourceDialogIcmp": "ICMP", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "We'll be back soon! Our site is currently undergoing scheduled maintenance.", "maintenancePageMessageDescription": "Detailed message explaining the maintenance", "maintenancePageTimeTitle": "Estimated Completion Time (Optional)", + "privateMaintenanceScreenTitle": "Private Placeholder Screen", + "privateMaintenanceScreenMessage": "This domain is being used on a private resource. Please connect using the Pangolin client to access this resource.", "maintenanceTime": "e.g., 2 hours, Nov 1 at 5:00 PM", "maintenanceEstimatedTimeDescription": "When you expect maintenance to be completed", "editDomain": "Edit Domain", @@ -2825,9 +3027,9 @@ "streamingHttpWebhookTitle": "HTTP Webhook", "streamingHttpWebhookDescription": "Send events to any HTTP endpoint with flexible authentication and templating.", "streamingS3Title": "Amazon S3", - "streamingS3Description": "Stream events to an S3-compatible object storage bucket. Contact support to enable this destination.", + "streamingS3Description": "Stream events to an S3-compatible object storage bucket.", "streamingDatadogTitle": "Datadog", - "streamingDatadogDescription": "Forward events directly to your Datadog account. Contact support to enable this destination.", + "streamingDatadogDescription": "Forward events directly to your Datadog account.", "streamingTypePickerDescription": "Choose a destination type to get started.", "streamingFailedToLoad": "Failed to load destinations", "streamingUnexpectedError": "An unexpected error occurred.", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "Add HTTP Destination", "httpDestEditDescription": "Update the configuration for this HTTP event streaming destination.", "httpDestAddDescription": "Configure a new HTTP endpoint to receive your organization's events.", + "S3DestEditTitle": "Edit Destination", + "S3DestAddTitle": "Add S3 Destination", + "S3DestEditDescription": "Update the configuration for this S3 event streaming destination.", + "S3DestAddDescription": "Configure a new S3 endpoint to receive your organization's events.", + "datadogDestEditTitle": "Edit Destination", + "datadogDestAddTitle": "Add Datadog Destination", + "datadogDestEditDescription": "Update the configuration for this Datadog event streaming destination.", + "datadogDestAddDescription": "Configure a new Datadog endpoint to receive your organization's events.", "httpDestTabSettings": "Settings", "httpDestTabHeaders": "Headers", "httpDestTabBody": "Body", @@ -2882,18 +3092,18 @@ "httpDestFormatJsonArrayTitle": "JSON Array", "httpDestFormatJsonArrayDescription": "One request per batch, body is a JSON array. Compatible with most generic webhooks and Datadog.", "httpDestFormatNdjsonTitle": "NDJSON", - "httpDestFormatNdjsonDescription": "One request per batch, body is newline-delimited JSON — one object per line, no outer array. Required by Splunk HEC, Elastic / OpenSearch, and Grafana Loki.", + "httpDestFormatNdjsonDescription": "One request per batch, body is newline-delimited JSON - one object per line, no outer array. Required by Splunk HEC, Elastic / OpenSearch, and Grafana Loki.", "httpDestFormatSingleTitle": "One Event Per Request", "httpDestFormatSingleDescription": "Sends a separate HTTP POST for each individual event. Use only for endpoints that cannot handle batches.", "httpDestLogTypesTitle": "Log Types", "httpDestLogTypesDescription": "Choose which log types are forwarded to this destination. Only enabled log types will be streamed.", - "httpDestAccessLogsTitle": "Access Logs", + "httpDestAccessLogsTitle": "Authentication Logs", "httpDestAccessLogsDescription": "Resource access attempts, including authenticated and denied requests.", - "httpDestActionLogsTitle": "Action Logs", + "httpDestActionLogsTitle": "Admin Action Logs", "httpDestActionLogsDescription": "Administrative actions performed by users within the organization.", - "httpDestConnectionLogsTitle": "Connection Logs", + "httpDestConnectionLogsTitle": "Network Logs", "httpDestConnectionLogsDescription": "Site and tunnel connection events, including connects and disconnects.", - "httpDestRequestLogsTitle": "Request Logs", + "httpDestRequestLogsTitle": "HTTPS Request Logs", "httpDestRequestLogsDescription": "HTTP request logs for proxied resources, including method, path, and response code.", "httpDestSaveChanges": "Save Changes", "httpDestCreateDestination": "Create Destination", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "Destination created successfully", "httpDestUpdateFailed": "Failed to update destination", "httpDestCreateFailed": "Failed to create destination", + "followRedirects": "Follow Redirects", + "followRedirectsDescription": "Automatically follow HTTP redirects for requests.", + "alertingErrorWebhookUrl": "Please enter a valid URL for the webhook.", + "healthCheckStrategyHttp": "Validates connectivity and checks the HTTP response status.", + "healthCheckStrategyTcp": "Verifies TCP connectivity only, without inspecting the response.", + "healthCheckStrategySnmp": "Makes an SNMP get request to check the health of network devices and infrastructure.", + "healthCheckStrategyIcmp": "Uses ICMP echo requests (pings) to check if a resource is reachable and responsive.", + "healthCheckTabStrategy": "Strategy", + "healthCheckTabConnection": "Connection", + "healthCheckTabAdvanced": "Advanced", + "healthCheckStrategyNotAvailable": "This strategy is not available. Please contact sales to enable this feature.", + "uptime30d": "Uptime (30d)", "idpAddActionCreateNew": "Create new identity provider", "idpAddActionImportFromOrg": "Import from another organization", "idpImportDialogTitle": "Import Identity Provider", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "This cannot be undone for this organization.", "idpUnassociatedDescription": "Identity provider unassociated from this organization successfully", "idpUnassociateMenu": "Unassociate", - "idpDeleteAllOrgsMenu": "Delete" + "idpDeleteAllOrgsMenu": "Delete", + "publicIpEndpoint": "Endpoint", + "lastTriggeredAt": "Last Trigger", + "reject": "Reject" } diff --git a/messages/es-ES.json b/messages/es-ES.json index 89a42fb96..e119adc1b 100644 --- a/messages/es-ES.json +++ b/messages/es-ES.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "Contacta ventas para habilitar esta función.", + "contactSalesBookDemo": "Reservar una demostración", + "contactSalesOr": "o", + "contactSalesContactUs": "contáctenos", "setupCreate": "Crear la organización, el sitio y los recursos", "headerAuthCompatibilityInfo": "Habilite esto para forzar una respuesta 401 no autorizada cuando falte un token de autenticación. Esto es necesario para navegadores o bibliotecas HTTP específicas que no envían credenciales sin un desafío del servidor.", "headerAuthCompatibility": "Compatibilidad extendida", @@ -19,6 +23,14 @@ "componentsInvalidKey": "Se han detectado claves de licencia inválidas o caducadas. Siga los términos de licencia para seguir usando todas las características.", "dismiss": "Descartar", "subscriptionViolationMessage": "Estás más allá de tus límites para tu plan actual. Corrija el problema eliminando sitios, usuarios u otros recursos para permanecer dentro de tu plan.", + "trialBannerMessage": "Su prueba expira en {countdown}. Actualice para mantener el acceso.", + "trialBannerExpired": "Su prueba ha expirado. Actualice ahora para restaurar el acceso.", + "trialActive": "Prueba gratuita activa", + "trialExpired": "Prueba expirada", + "trialHasEnded": "Su prueba ha terminado.", + "trialDaysRemaining": "{count, plural, one {# día restante} other {# días restantes}}", + "trialDaysLeftShort": "Quedan {days}d en la prueba", + "trialGoToBilling": "Ir a la página de facturación", "subscriptionViolationViewBilling": "Ver facturación", "componentsLicenseViolation": "Violación de la Licencia: Este servidor está usando sitios {usedSites} que exceden su límite de licencias de sitios {maxSites} . Siga los términos de licencia para seguir usando todas las características.", "componentsSupporterMessage": "¡Gracias por apoyar a Pangolin como {tier}!", @@ -267,8 +279,11 @@ "orgMissing": "Falta el ID de la organización", "orgMissingMessage": "No se puede regenerar la invitación sin el ID de la organización.", "accessUsersManage": "Administrar usuarios", + "accessUserManage": "Administrar usuario", "accessUsersDescription": "Invitar y administrar usuarios con acceso a esta organización", "accessUsersSearch": "Buscar usuarios...", + "accessUsersRoleFilterCount": "{count, plural, one {# rol} other {# roles}}", + "accessUsersRoleFilterClear": "Borrar filtros de rol", "accessUserCreate": "Crear usuario", "accessUserRemove": "Eliminar usuario", "username": "Usuario", @@ -1257,6 +1272,7 @@ "actionViewLogs": "Ver registros", "noneSelected": "Ninguno seleccionado", "orgNotFound2": "No se encontraron organizaciones.", + "search": "Buscar…", "searchPlaceholder": "Buscar...", "emptySearchOptions": "No se encontraron opciones", "create": "Crear", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "Gestionar", "sidebarLogAndAnalytics": "Registro y análisis", "sidebarBluePrints": "Planos", + "sidebarAlerting": "Alertas", + "sidebarHealthChecks": "Chequeos de salud", "sidebarOrganization": "Organización", "sidebarManagement": "Gestión", "sidebarBillingAndLicenses": "Facturación y licencias", "sidebarLogsAnalytics": "Analíticas", + "alertingTitle": "Alertas", + "alertingDescription": "Definir fuentes, disparadores y acciones para notificaciones", + "alertingRules": "Reglas de alerta", + "alertingSearchRules": "Buscar reglas…", + "alertingAddRule": "Crear regla", + "alertingColumnSource": "Fuente", + "alertingColumnTrigger": "Disparador", + "alertingColumnActions": "Acciones", + "alertingColumnEnabled": "Activado", + "alertingDeleteQuestion": "Por favor, confirme que desea eliminar esta regla de alerta.", + "alertingDeleteRule": "Eliminar regla de alerta", + "alertingRuleDeleted": "Regla de alerta eliminada", + "alertingRuleSaved": "Regla de alerta guardada", + "alertingRuleSavedCreatedDescription": "Tu nueva regla de alerta fue creada. Puedes seguir editándola en esta página.", + "alertingRuleSavedUpdatedDescription": "Tus cambios a esta regla de alerta fueron guardados.", + "alertingEditRule": "Editar regla de alerta", + "alertingCreateRule": "Crear regla de alerta", + "alertingRuleCredenzaDescription": "Elija qué observar, cuándo disparar y cómo notificar", + "alertingRuleNamePlaceholder": "Sitio de producción caído", + "alertingRuleEnabled": "Regla habilitada", + "alertingSectionSource": "Fuente", + "alertingSourceType": "Tipo de fuente", + "alertingSourceSite": "Sitio", + "alertingSourceHealthCheck": "Chequeo de salud", + "alertingPickSites": "Sitios", + "alertingPickHealthChecks": "Chequeos de salud", + "alertingPickResources": "Recursos", + "alertingAllSites": "Todos los sitios", + "alertingAllSitesDescription": "Las alertas se activan para cualquier sitio", + "alertingSpecificSites": "Sitios específicos", + "alertingSpecificSitesDescription": "Escoja sitios específicos para observar", + "alertingAllHealthChecks": "Todos los chequeos de salud", + "alertingAllHealthChecksDescription": "Las alertas se activan para cualquier chequeo de salud", + "alertingSpecificHealthChecks": "Chequeos de salud específicos", + "alertingSpecificHealthChecksDescription": "Elija chequeos de salud específicos para observar", + "alertingAllResources": "Todos los recursos", + "alertingAllResourcesDescription": "Las alertas se activan para cualquier recurso", + "alertingSpecificResources": "Recursos específicos", + "alertingSpecificResourcesDescription": "Elija recursos específicos para observar", + "alertingSelectResources": "Seleccionar recursos…", + "alertingResourcesSelected": "{count} recursos seleccionados", + "alertingResourcesEmpty": "No hay recursos con objetivos en los primeros 10 resultados.", + "alertingSectionTrigger": "Disparador", + "alertingTrigger": "Cuándo alertar", + "alertingTriggerSiteOnline": "Sitio en línea", + "alertingTriggerSiteOffline": "Sitio fuera de línea", + "alertingTriggerSiteToggle": "El estado del sitio cambia", + "alertingTriggerHcHealthy": "Chequeo de salud saludable", + "alertingTriggerHcUnhealthy": "Chequeo de salud no saludable", + "alertingTriggerHcToggle": "El estado del chequeo de salud cambia", + "alertingTriggerResourceHealthy": "Recurso saludable", + "alertingTriggerResourceUnhealthy": "Recurso no saludable", + "alertingSearchHealthChecks": "Buscar chequeos de salud…", + "alertingHealthChecksEmpty": "No hay chequeos de salud disponibles.", + "alertingTriggerResourceToggle": "El estado del recurso cambia", + "alertingSourceResource": "Recurso", + "alertingSectionActions": "Acciones", + "alertingAddAction": "Añadir acción", + "alertingActionNotify": "E-mail", + "alertingActionNotifyDescription": "Enviar notificaciones por correo electrónico a usuarios o roles", + "alertingActionWebhook": "Webhook", + "alertingActionWebhookDescription": "Enviar una solicitud HTTP a un punto final personalizado", + "alertingExternalIntegration": "Integración externa", + "alertingExternalPagerDutyDescription": "Enviar alertas a PagerDuty para gestión de incidentes", + "alertingExternalOpsgenieDescription": "Dirigir alertas a Opsgenie para gestión de llamadas", + "alertingExternalServiceNowDescription": "Crear incidentes de ServiceNow a partir de eventos de alerta", + "alertingExternalIncidentIoDescription": "Activar flujos de trabajo de Incident.io a partir de eventos de alerta", + "alertingActionType": "Tipo de acción", + "alertingNotifyUsers": "Usuarios", + "alertingNotifyRoles": "Roles", + "alertingNotifyEmails": "Direcciones de correo electrónico", + "alertingEmailPlaceholder": "Añadir email y presionar Enter", + "alertingWebhookMethod": "Método HTTP", + "alertingWebhookSecret": "Firma secreta (opcional)", + "alertingWebhookSecretPlaceholder": "Secreto HMAC", + "alertingWebhookHeaders": "Encabezados", + "alertingAddHeader": "Añadir encabezado", + "alertingSelectSites": "Seleccionar sitios…", + "alertingSitesSelected": "{count} sitios seleccionados", + "alertingSelectHealthChecks": "Seleccionar chequeos de salud…", + "alertingHealthChecksSelected": "{count} chequeos de salud seleccionados", + "alertingNoHealthChecks": "No hay objetivos con chequeos de salud habilitados", + "alertingHealthCheckStub": "La selección de chequeo de salud no está conectada aún - todavía puede configurar disparadores y acciones.", + "alertingSelectUsers": "Seleccionar usuarios…", + "alertingUsersSelected": "{count} usuarios seleccionados", + "alertingSelectRoles": "Seleccionar roles…", + "alertingRolesSelected": "{count} roles seleccionados", + "alertingSummarySites": "Sitios ({count})", + "alertingSummaryAllSites": "Todos los sitios", + "alertingSummaryHealthChecks": "Chequeos de salud ({count})", + "alertingSummaryAllHealthChecks": "Todos los chequeos de salud", + "alertingSummaryResources": "Recursos ({count})", + "alertingSummaryAllResources": "Todos los recursos", + "alertingErrorNameRequired": "Introduce un nombre", + "alertingErrorActionsMin": "Añada al menos una acción", + "alertingErrorPickSites": "Seleccione al menos un sitio", + "alertingErrorPickHealthChecks": "Seleccione al menos un chequeo de salud", + "alertingErrorPickResources": "Seleccione al menos un recurso", + "alertingErrorTriggerSite": "Elija un disparador de sitio", + "alertingErrorTriggerHealth": "Elija un disparador de chequeo de salud", + "alertingErrorTriggerResource": "Elija un disparador de recurso", + "alertingErrorNotifyRecipients": "Elija usuarios, roles o al menos un correo electrónico", + "alertingConfigureSource": "Configurar fuente", + "alertingConfigureTrigger": "Configurar disparador", + "alertingConfigureActions": "Configurar acciones", + "alertingBackToRules": "Volver a las reglas", + "alertingRuleCooldown": "Tiempo de espera (segundos)", + "alertingRuleCooldownDescription": "Tiempo mínimo entre alertas repetidas para la misma regla. Establezca en 0 para disparar cada vez.", + "alertingDraftBadge": "Borrador - guardarlo para almacenar esta regla", + "alertingSidebarHint": "Haga clic en un paso en el lienzo para editarlo aquí.", + "alertingGraphCanvasTitle": "Flujo de regla", + "alertingGraphCanvasDescription": "Visión general visual de fuente, disparador y acciones. Selecciona un nodo para editarlo en el panel.", + "alertingNodeNotConfigured": "Aún no configurado", + "alertingNodeActionsCount": "{count, plural, one {# acción} other {# acciones}}", + "alertingNodeRoleSource": "Fuente", + "alertingNodeRoleTrigger": "Disparador", + "alertingNodeRoleAction": "Acción", + "alertingTabRules": "Reglas de Alerta", + "alertingTabHealthChecks": "Chequeos de salud", + "alertingRulesBannerTitle": "Obtenga notificaciones", + "alertingRulesBannerDescription": "Cada regla vincula lo que se debe observar (un sitio, chequeo de salud o recurso), cuándo disparar (por ejemplo, fuera de línea o no saludable), y cómo notificar a su equipo vía email, webhooks o integraciones. Use esta lista para crear, habilitar y administrar esas reglas.", + "alertingHealthChecksBannerTitle": "Monitorear Salud y Recursos", + "alertingHealthChecksBannerDescription": "Los chequeos de salud son monitores HTTP o TCP que define una vez. Luego puede usarlos como fuentes en reglas de alerta para que se le notifique cuando un objetivo se vuelva saludable o no saludable. Los chequeos de salud en recursos también aparecen aquí.", + "standaloneHcTableTitle": "Chequeos de salud", + "standaloneHcSearchPlaceholder": "Buscar chequeos de salud…", + "standaloneHcAddButton": "Crear chequeo de salud", + "standaloneHcCreateTitle": "Crear chequeo de salud", + "standaloneHcEditTitle": "Editar chequeo de salud", + "standaloneHcDescription": "Configurar un chequeo de salud HTTP o TCP para usar en reglas de alerta.", + "standaloneHcNameLabel": "Nombre", + "standaloneHcNamePlaceholder": "Mi monitor HTTP", + "standaloneHcDeleteTitle": "Eliminar chequeo de salud", + "standaloneHcDeleteQuestion": "Por favor, confirme que desea eliminar este chequeo de salud.", + "standaloneHcDeleted": "Chequeo de salud eliminado", + "standaloneHcSaved": "Chequeo de salud guardado", + "standaloneHcColumnHealth": "Salud", + "standaloneHcColumnMode": "Modo", + "standaloneHcColumnTarget": "Destino", + "standaloneHcHealthStateHealthy": "Saludable", + "standaloneHcHealthStateUnhealthy": "No saludable", + "standaloneHcHealthStateUnknown": "Desconocido", + "standaloneHcFilterAnySite": "Todos los sitios", + "standaloneHcFilterAnyResource": "Todos los recursos", + "standaloneHcFilterMode": "Modo", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "Ping", + "standaloneHcFilterHealth": "Salud", + "standaloneHcFilterEnabled": "Activado", + "standaloneHcFilterEnabledOn": "Activado", + "standaloneHcFilterEnabledOff": "Deshabilitado", + "standaloneHcFilterSiteIdFallback": "Sitio {id}", + "standaloneHcFilterResourceIdFallback": "Recurso {id}", "blueprints": "Planos", "blueprintsDescription": "Aplicar configuraciones declarativas y ver ejecuciones anteriores", "blueprintAdd": "Añadir plano", @@ -1763,6 +1935,15 @@ "healthCheckIntervalMin": "El intervalo de comprobación debe ser de al menos 5 segundos", "healthCheckTimeoutMin": "El tiempo de espera debe ser de al menos 1 segundo", "healthCheckRetryMin": "Los intentos de reintento deben ser de al menos 1", + "healthCheckMode": "Modo de chequeo", + "healthCheckStrategy": "Estrategia", + "healthCheckModeDescription": "El modo TCP verifica solo la conectividad. El modo HTTP valida la respuesta HTTP.", + "healthyThreshold": "Umbral Saludable", + "healthyThresholdDescription": "Éxitos consecutivos requeridos antes de marcar como saludable.", + "unhealthyThreshold": "Umbral No Saludable", + "unhealthyThresholdDescription": "Fallos consecutivos requeridos antes de marcar como no saludable.", + "healthCheckHealthyThresholdMin": "El umbral saludable debe ser al menos 1", + "healthCheckUnhealthyThresholdMin": "El umbral no saludable debe ser al menos 1", "httpMethod": "Método HTTP", "selectHttpMethod": "Seleccionar método HTTP", "domainPickerSubdomainLabel": "Subdominio", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "Puerto", "editInternalResourceDialogModeHost": "Anfitrión", "editInternalResourceDialogModeCidr": "CIDR", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "Esquema", + "editInternalResourceDialogEnableSsl": "Activar SSL", + "editInternalResourceDialogEnableSslDescription": "Habilitar cifrado SSL/TLS para conexiones HTTPS seguras al destino.", "editInternalResourceDialogDestination": "Destino", "editInternalResourceDialogDestinationHostDescription": "La dirección IP o nombre de host del recurso en la red del sitio.", "editInternalResourceDialogDestinationIPDescription": "La dirección IP o nombre de host del recurso en la red del sitio.", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "Nombre", "createInternalResourceDialogSite": "Sitio", "selectSite": "Seleccionar sitio...", + "multiSitesSelectorSitesCount": "{count, plural, one {# sitio} other {# sitios}}", "noSitesFound": "Sitios no encontrados.", "createInternalResourceDialogProtocol": "Protocolo", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "Puerto", "createInternalResourceDialogModeHost": "Anfitrión", "createInternalResourceDialogModeCidr": "CIDR", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "Esquema", + "createInternalResourceDialogScheme": "Esquema", + "createInternalResourceDialogEnableSsl": "Activar SSL", + "createInternalResourceDialogEnableSslDescription": "Habilitar cifrado SSL/TLS para conexiones HTTPS seguras al destino.", "createInternalResourceDialogDestination": "Destino", "createInternalResourceDialogDestinationHostDescription": "La dirección IP o nombre de host del recurso en la red del sitio.", "createInternalResourceDialogDestinationCidrDescription": "El rango CIDR del recurso en la red del sitio.", "createInternalResourceDialogAlias": "Alias", "createInternalResourceDialogAliasDescription": "Un alias DNS interno opcional para este recurso.", + "internalResourceDownstreamSchemeRequired": "Se requiere el método para recursos HTTP", + "internalResourceHttpPortRequired": "Se requiere el puerto de destino para recursos HTTP", "siteConfiguration": "Configuración", "siteAcceptClientConnections": "Aceptar conexiones de clientes", "siteAcceptClientConnectionsDescription": "Permitir a los dispositivos de usuario y clientes acceder a los recursos de este sitio. Esto se puede cambiar más tarde.", @@ -2119,7 +2314,7 @@ "selectDomainForOrgAuthPage": "Seleccione un dominio para la página de autenticación de la organización", "domainPickerProvidedDomain": "Dominio proporcionado", "domainPickerFreeProvidedDomain": "Dominio proporcionado gratis", - "domainPickerFreeDomainsPaidFeature": "Los dominios proporcionados son una función de pago. Suscríbete para obtener un dominio incluido con tu plan — no necesitas traer el tuyo propio.", + "domainPickerFreeDomainsPaidFeature": "Los dominios proporcionados son una función de pago. Suscríbete para obtener un dominio incluido con tu plan - no necesitas traer el tuyo propio.", "domainPickerVerified": "Verificado", "domainPickerUnverified": "Sin verificar", "domainPickerManual": "Manual", @@ -2297,7 +2492,7 @@ "alerts": { "commercialUseDisclosure": { "title": "Divulgación de uso", - "description": "Seleccione el nivel de licencia que refleje con precisión su uso previsto. La Licencia Personal permite el uso libre del Software para actividades comerciales individuales, no comerciales o de pequeña escala con ingresos brutos anuales inferiores a $100,000 USD. Cualquier uso más allá de estos límites — incluyendo el uso dentro de una empresa, organización, u otro entorno de generación de ingresos — requiere una Licencia Empresarial válida y el pago de la cuota de licencia aplicable. Todos los usuarios, ya sean personales o empresariales, deben cumplir con las Condiciones de Licencia Comercial Fossorial." + "description": "Seleccione el nivel de licencia que refleje con precisión su uso previsto. La Licencia Personal permite el uso libre del Software para actividades comerciales individuales, no comerciales o de pequeña escala con ingresos brutos anuales inferiores a $100,000 USD. Cualquier uso más allá de estos límites - incluyendo el uso dentro de una empresa, organización, u otro entorno de generación de ingresos - requiere una Licencia Empresarial válida y el pago de la cuota de licencia aplicable. Todos los usuarios, ya sean personales o empresariales, deben cumplir con las Condiciones de Licencia Comercial Fossorial." }, "trialPeriodInformation": { "title": "Información del período de prueba", @@ -2429,6 +2624,7 @@ "validPassword": "Contraseña válida", "validEmail": "Valid email", "validSSO": "Valid SSO", + "connectedClient": "Cliente conectado", "resourceBlocked": "Recurso bloqueado", "droppedByRule": "Soltado por regla", "noSessions": "No hay sesiones", @@ -2668,6 +2864,10 @@ "editInternalResourceDialogDestinationLabel": "Destino", "editInternalResourceDialogDestinationDescription": "Especifique la dirección de destino para el recurso interno. Puede ser un nombre de host, dirección IP o rango CIDR dependiendo del modo seleccionado. Opcionalmente establezca un alias DNS interno para una identificación más fácil.", "editInternalResourceDialogPortRestrictionsDescription": "Restringir el acceso a puertos TCP/UDP específicos o permitir/bloquear todos los puertos.", + "createInternalResourceDialogHttpConfiguration": "Configuración HTTP", + "createInternalResourceDialogHttpConfigurationDescription": "Elija el dominio que los clientes usarán para alcanzar este recurso a través de HTTP o HTTPS.", + "editInternalResourceDialogHttpConfiguration": "Configuración HTTP", + "editInternalResourceDialogHttpConfigurationDescription": "Elija el dominio que los clientes usarán para alcanzar este recurso a través de HTTP o HTTPS.", "editInternalResourceDialogTcp": "TCP", "editInternalResourceDialogUdp": "UDP", "editInternalResourceDialogIcmp": "ICMP", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "¡Volveremos pronto! Nuestro sitio está actualmente en mantenimiento programado.", "maintenancePageMessageDescription": "Mensaje detallado explicando el mantenimiento", "maintenancePageTimeTitle": "Tiempo estimado de finalización (Opcional)", + "privateMaintenanceScreenTitle": "Pantalla de marcador de posición privada", + "privateMaintenanceScreenMessage": "Este dominio se está utilizando en un recurso privado. Conéctese usando el cliente Pangolin para acceder a este recurso.", "maintenanceTime": "Ej., 2 horas, 1 de noviembre a las 5:00 PM", "maintenanceEstimatedTimeDescription": "Cuando espera que el mantenimiento esté terminado", "editDomain": "Editar dominio", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "Añadir destino HTTP", "httpDestEditDescription": "Actualizar la configuración para este destino de transmisión de eventos HTTP.", "httpDestAddDescription": "Configure un nuevo extremo HTTP para recibir los eventos de su organización.", + "S3DestEditTitle": "Editar destino", + "S3DestAddTitle": "Añadir destino S3", + "S3DestEditDescription": "Actualice la configuración para este destino de transmisión de eventos S3.", + "S3DestAddDescription": "Configure un nuevo punto final S3 para recibir los eventos de su organización.", + "datadogDestEditTitle": "Editar destino", + "datadogDestAddTitle": "Añadir destino Datadog", + "datadogDestEditDescription": "Actualice la configuración para este destino de transmisión de eventos Datadog.", + "datadogDestAddDescription": "Configure un nuevo punto final de Datadog para recibir los eventos de su organización.", "httpDestTabSettings": "Ajustes", "httpDestTabHeaders": "Encabezados", "httpDestTabBody": "Cuerpo", @@ -2882,7 +3092,7 @@ "httpDestFormatJsonArrayTitle": "Matriz JSON", "httpDestFormatJsonArrayDescription": "Una petición por lote, cuerpo es una matriz JSON. Compatible con la mayoría de los webhooks y Datadog.", "httpDestFormatNdjsonTitle": "NDJSON", - "httpDestFormatNdjsonDescription": "Una petición por lote, el cuerpo es JSON delimitado por línea — un objeto por línea, sin arrays externos. Requerido por Splunk HEC, Elastic / OpenSearch, y Grafana Loki.", + "httpDestFormatNdjsonDescription": "Una petición por lote, el cuerpo es JSON delimitado por línea - un objeto por línea, sin arrays externos. Requerido por Splunk HEC, Elastic / OpenSearch, y Grafana Loki.", "httpDestFormatSingleTitle": "Un evento por solicitud", "httpDestFormatSingleDescription": "Envía un HTTP POST separado para cada evento individual. Úsalo sólo para los extremos que no pueden manejar lotes.", "httpDestLogTypesTitle": "Tipos de Log", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "Destino creado correctamente", "httpDestUpdateFailed": "Error al actualizar destino", "httpDestCreateFailed": "Error al crear el destino", + "followRedirects": "Seguir redirecciones", + "followRedirectsDescription": "Seguir automáticamente las redirecciones HTTP para solicitudes.", + "alertingErrorWebhookUrl": "Por favor, introduzca una URL válida para el webhook.", + "healthCheckStrategyHttp": "Valida la conectividad y verifica el estado de respuesta HTTP.", + "healthCheckStrategyTcp": "Verifica la conectividad TCP solamente, sin inspeccionar la respuesta.", + "healthCheckStrategySnmp": "Realiza una solicitud SNMP get para verificar la salud de dispositivos y la infraestructura de red.", + "healthCheckStrategyIcmp": "Usa solicitudes de eco ICMP (pings) para verificar si un recurso es alcanzable y receptivo.", + "healthCheckTabStrategy": "Estrategia", + "healthCheckTabConnection": "Conexión", + "healthCheckTabAdvanced": "Avanzado", + "healthCheckStrategyNotAvailable": "Esta estrategia no está disponible. Contacte ventas para habilitar esta funcionalidad.", + "uptime30d": "Tiempo de actividad (30d)", "idpAddActionCreateNew": "Crear nuevo proveedor de identidad", "idpAddActionImportFromOrg": "Importar de otra organización", "idpImportDialogTitle": "Importar Proveedor de Identidad", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "Esto no se puede deshacer para esta organización.", "idpUnassociatedDescription": "Proveedor de identidad desasociado de esta organización con éxito", "idpUnassociateMenu": "Desasociar", - "idpDeleteAllOrgsMenu": "Eliminar" + "idpDeleteAllOrgsMenu": "Eliminar", + "publicIpEndpoint": "Punto final", + "lastTriggeredAt": "Último disparo", + "reject": "Rechazar" } diff --git a/messages/fr-FR.json b/messages/fr-FR.json index c5ab2ba4a..8b9cd90b9 100644 --- a/messages/fr-FR.json +++ b/messages/fr-FR.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "Contactez le service commercial pour activer cette fonctionnalité.", + "contactSalesBookDemo": "Réserver une démo", + "contactSalesOr": "ou", + "contactSalesContactUs": "contactez-nous", "setupCreate": "Créer l'organisation, le site et les ressources", "headerAuthCompatibilityInfo": "Activez ceci pour forcer une réponse 401 Unauthorized lorsque le jeton d'authentification est manquant. Cela est nécessaire pour les navigateurs ou les bibliothèques HTTP spécifiques qui n'envoient pas de credentials sans un challenge du serveur.", "headerAuthCompatibility": "Compatibilité étendue", @@ -19,6 +23,14 @@ "componentsInvalidKey": "Clés de licence invalides ou expirées détectées. Veuillez respecter les conditions de licence pour continuer à utiliser toutes les fonctionnalités.", "dismiss": "Rejeter", "subscriptionViolationMessage": "Vous dépassez vos limites pour votre forfait actuel. Corrigez le problème en supprimant des sites, des utilisateurs ou d'autres ressources pour rester dans votre forfait.", + "trialBannerMessage": "Votre essai expire dans {countdown}. Passez à l'abonnement pour garder l'accès.", + "trialBannerExpired": "Votre essai a expiré. Passez à l'abonnement maintenant pour restaurer l'accès.", + "trialActive": "Essai gratuit actif", + "trialExpired": "Essai expiré", + "trialHasEnded": "Votre essai est terminé.", + "trialDaysRemaining": "{count, plural, one {# jour restant} other {# jours restants}}", + "trialDaysLeftShort": "{days}j restants dans l'essai", + "trialGoToBilling": "Aller à la page de facturation", "subscriptionViolationViewBilling": "Voir la facturation", "componentsLicenseViolation": "Violation de licence : ce serveur utilise {usedSites} nœuds, ce qui dépasse la limite autorisée de {maxSites} nœuds. Respectez les conditions de licence pour continuer à utiliser toutes les fonctionnalités.", "componentsSupporterMessage": "Merci de soutenir Pangolin en tant que {tier}!", @@ -267,8 +279,11 @@ "orgMissing": "ID d'organisation manquant", "orgMissingMessage": "Impossible de régénérer l'invitation sans un ID d'organisation.", "accessUsersManage": "Gérer les utilisateurs", + "accessUserManage": "Gérer l'utilisateur", "accessUsersDescription": "Inviter et gérer les utilisateurs ayant accès à cette organisation", "accessUsersSearch": "Chercher des utilisateurs...", + "accessUsersRoleFilterCount": "{count, plural, one {# rôle} other {# rôles}}", + "accessUsersRoleFilterClear": "Effacer les filtres de rôle", "accessUserCreate": "Créer un utilisateur", "accessUserRemove": "Supprimer un utilisateur", "username": "Nom d'utilisateur", @@ -1257,6 +1272,7 @@ "actionViewLogs": "Voir les logs", "noneSelected": "Aucune sélection", "orgNotFound2": "Aucune organisation trouvée.", + "search": "Rechercher…", "searchPlaceholder": "Recherche...", "emptySearchOptions": "Aucune option trouvée", "create": "Créer", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "Gérer", "sidebarLogAndAnalytics": "Journaux & Analytiques", "sidebarBluePrints": "Configs", + "sidebarAlerting": "Alertes", + "sidebarHealthChecks": "Vérifications de l'état de santé", "sidebarOrganization": "Organisation", "sidebarManagement": "Gestion", "sidebarBillingAndLicenses": "Facturation & Licences", "sidebarLogsAnalytics": "Analyses", + "alertingTitle": "Alertes", + "alertingDescription": "Définissez des sources, des déclencheurs et des actions pour les notifications", + "alertingRules": "Règles d'alerte", + "alertingSearchRules": "Rechercher des règles…", + "alertingAddRule": "Créer une règle", + "alertingColumnSource": "Source", + "alertingColumnTrigger": "Déclencheur", + "alertingColumnActions": "Actions", + "alertingColumnEnabled": "Activé", + "alertingDeleteQuestion": "Veuillez confirmer que vous souhaitez supprimer cette règle d'alerte.", + "alertingDeleteRule": "Supprimer la règle d'alerte", + "alertingRuleDeleted": "Règle d'alerte supprimée", + "alertingRuleSaved": "Règle d'alerte enregistrée", + "alertingRuleSavedCreatedDescription": "Votre nouvelle règle d'alerte a été créée. Vous pouvez continuer à la modifier sur cette page.", + "alertingRuleSavedUpdatedDescription": "Vos modifications apportées à cette règle d'alerte ont été enregistrées.", + "alertingEditRule": "Modifier la règle d'alerte", + "alertingCreateRule": "Créer une règle d'alerte", + "alertingRuleCredenzaDescription": "Choisissez ce qu'il faut surveiller, quand la déclencher et comment notifier", + "alertingRuleNamePlaceholder": "Site de production hors ligne", + "alertingRuleEnabled": "Règle activée", + "alertingSectionSource": "Source", + "alertingSourceType": "Type de source", + "alertingSourceSite": "Nœud", + "alertingSourceHealthCheck": "Vérification de l'état de santé", + "alertingPickSites": "Nœuds", + "alertingPickHealthChecks": "Vérifications de l'état de santé", + "alertingPickResources": "Ressources", + "alertingAllSites": "Tous les nœuds", + "alertingAllSitesDescription": "Les alertes se déclenchent pour n'importe quel nœud", + "alertingSpecificSites": "Nœuds spécifiques", + "alertingSpecificSitesDescription": "Choisissez des nœuds spécifiques à surveiller", + "alertingAllHealthChecks": "Toutes les vérifications de l'état de santé", + "alertingAllHealthChecksDescription": "Les alertes se déclenchent pour n'importe quelle vérification de l'état de santé", + "alertingSpecificHealthChecks": "Vérifications de l'état de santé spécifiques", + "alertingSpecificHealthChecksDescription": "Choisissez des vérifications de l'état de santé spécifiques à surveiller", + "alertingAllResources": "Toutes les ressources", + "alertingAllResourcesDescription": "Les alertes se déclenchent pour n'importe quelle ressource", + "alertingSpecificResources": "Ressources spécifiques", + "alertingSpecificResourcesDescription": "Choisissez des ressources spécifiques à surveiller", + "alertingSelectResources": "Sélectionner des ressources…", + "alertingResourcesSelected": "{count} ressources sélectionnées", + "alertingResourcesEmpty": "Aucune ressource avec des cibles dans les 10 premiers résultats.", + "alertingSectionTrigger": "Déclencheur", + "alertingTrigger": "Quand alerter", + "alertingTriggerSiteOnline": "Site en ligne", + "alertingTriggerSiteOffline": "Site hors ligne", + "alertingTriggerSiteToggle": "Les changements d'état du site", + "alertingTriggerHcHealthy": "Vérification de l'état de santé sain", + "alertingTriggerHcUnhealthy": "Vérification de l'état de santé non sain", + "alertingTriggerHcToggle": "Les changements d'état de la vérification de l'état de santé", + "alertingTriggerResourceHealthy": "Ressource saine", + "alertingTriggerResourceUnhealthy": "Ressource non saine", + "alertingSearchHealthChecks": "Rechercher des vérifications de l'état de santé…", + "alertingHealthChecksEmpty": "Aucune vérification de l'état de santé disponible.", + "alertingTriggerResourceToggle": "Les changements d'état de la ressource", + "alertingSourceResource": "Ressource", + "alertingSectionActions": "Actions", + "alertingAddAction": "Ajouter une action", + "alertingActionNotify": "Adresse mail", + "alertingActionNotifyDescription": "Envoyez des notifications par e-mail aux utilisateurs ou aux rôles", + "alertingActionWebhook": "Webhook", + "alertingActionWebhookDescription": "Envoyez une requête HTTP à un point de terminaison personnalisé", + "alertingExternalIntegration": "Intégration externe", + "alertingExternalPagerDutyDescription": "Envoyer des alertes à PagerDuty pour la gestion des incidents", + "alertingExternalOpsgenieDescription": "Diriger les alertes vers Opsgenie pour la gestion des appels", + "alertingExternalServiceNowDescription": "Créer des incidents ServiceNow à partir des événements d'alerte", + "alertingExternalIncidentIoDescription": "Déclencher des flux de travail Incident.io à partir d'événements d'alerte", + "alertingActionType": "Type d'action", + "alertingNotifyUsers": "Utilisateurs", + "alertingNotifyRoles": "Rôles", + "alertingNotifyEmails": "Adresses e-mail", + "alertingEmailPlaceholder": "Ajoutez un e-mail et appuyez sur Entrée", + "alertingWebhookMethod": "Méthode HTTP", + "alertingWebhookSecret": "Secret de signature (facultatif)", + "alertingWebhookSecretPlaceholder": "Secret HMAC", + "alertingWebhookHeaders": "En-têtes", + "alertingAddHeader": "Ajouter un en-tête", + "alertingSelectSites": "Sélectionner des sites…", + "alertingSitesSelected": "{count} sites sélectionnés", + "alertingSelectHealthChecks": "Sélectionner des vérifications de l'état de santé…", + "alertingHealthChecksSelected": "{count} vérifications de santé sélectionnées", + "alertingNoHealthChecks": "Aucune cible avec des vérifications de l'état de santé activées", + "alertingHealthCheckStub": "La sélection de la source de vérification de l'état de santé n'est pas encore câblée - vous pouvez toujours configurer les déclencheurs et les actions.", + "alertingSelectUsers": "Sélectionner des utilisateurs…", + "alertingUsersSelected": "{count} utilisateurs sélectionnés", + "alertingSelectRoles": "Sélectionner des rôles…", + "alertingRolesSelected": "{count} rôles sélectionnés", + "alertingSummarySites": "Sites ({count})", + "alertingSummaryAllSites": "Tous les nœuds", + "alertingSummaryHealthChecks": "Vérifications de l'état de santé ({count})", + "alertingSummaryAllHealthChecks": "Toutes les vérifications de l'état de santé", + "alertingSummaryResources": "Ressources ({count})", + "alertingSummaryAllResources": "Toutes les ressources", + "alertingErrorNameRequired": "Entrer un nom", + "alertingErrorActionsMin": "Ajoutez au moins une action", + "alertingErrorPickSites": "Sélectionnez au moins un site", + "alertingErrorPickHealthChecks": "Sélectionnez au moins une vérification de l'état de santé", + "alertingErrorPickResources": "Sélectionnez au moins une ressource", + "alertingErrorTriggerSite": "Choisissez un déclencheur de site", + "alertingErrorTriggerHealth": "Choisissez un déclencheur de vérification de l'état de santé", + "alertingErrorTriggerResource": "Choisissez un déclencheur de ressource", + "alertingErrorNotifyRecipients": "Choisissez des utilisateurs, des rôles ou au moins un e-mail", + "alertingConfigureSource": "Configurer la source", + "alertingConfigureTrigger": "Configurer le déclencheur", + "alertingConfigureActions": "Configurer les actions", + "alertingBackToRules": "Retour aux règles", + "alertingRuleCooldown": "Temps de repos (secondes)", + "alertingRuleCooldownDescription": "Temps minimum entre les alertes répétées pour la même règle. Réglez sur 0 pour déclencher à chaque fois.", + "alertingDraftBadge": "Brouillon - enregistrez pour stocker cette règle", + "alertingSidebarHint": "Cliquez sur une étape dans la vue d'ensemble pour la modifier ici.", + "alertingGraphCanvasTitle": "Flux de règle", + "alertingGraphCanvasDescription": "Vue d'ensemble visuelle de la source, du déclencheur et des actions. Sélectionnez un nœud pour le modifier dans le panneau.", + "alertingNodeNotConfigured": "Pas encore configuré", + "alertingNodeActionsCount": "{count, plural, one {# action} other {# actions}}", + "alertingNodeRoleSource": "Source", + "alertingNodeRoleTrigger": "Déclencheur", + "alertingNodeRoleAction": "Action", + "alertingTabRules": "Règles d'alerte", + "alertingTabHealthChecks": "Vérifications de l'état de santé", + "alertingRulesBannerTitle": "Soyez averti", + "alertingRulesBannerDescription": "Chaque règle associe ce qu'il faut surveiller (un site, une vérification de l'état de santé ou une ressource), quand l'exécuter (par exemple, hors ligne ou non saine), et comment notifier votre équipe par e-mail, webhooks ou intégrations. Utilisez cette liste pour créer, activer et gérer ces règles.", + "alertingHealthChecksBannerTitle": "Surveiller la santé et les ressources", + "alertingHealthChecksBannerDescription": "Les vérifications de l'état de santé sont des moniteurs HTTP ou TCP que vous définissez une fois. Vous pouvez ensuite les utiliser comme sources dans les règles d'alerte pour être averti lorsqu'une cible devient saine ou non saine. Les vérifications de l'état de santé sur les ressources apparaissent également ici.", + "standaloneHcTableTitle": "Vérifications de l'état de santé", + "standaloneHcSearchPlaceholder": "Rechercher des vérifications de l'état de santé…", + "standaloneHcAddButton": "Créer une vérification de l'état de santé", + "standaloneHcCreateTitle": "Créer une vérification de l'état de santé", + "standaloneHcEditTitle": "Modifier la vérification de l'état de santé", + "standaloneHcDescription": "Configurez une vérification HTTP ou TCP de l'état de santé pour une utilisation dans les règles d'alerte.", + "standaloneHcNameLabel": "Nom", + "standaloneHcNamePlaceholder": "Mon moniteur HTTP", + "standaloneHcDeleteTitle": "Supprimer la vérification de l'état de santé", + "standaloneHcDeleteQuestion": "Veuillez confirmer que você souhaitez supprimer cette vérification de l'état de santé.", + "standaloneHcDeleted": "Vérification de l'état de santé supprimée", + "standaloneHcSaved": "Vérification de l'état de santé enregistrée", + "standaloneHcColumnHealth": "Santé", + "standaloneHcColumnMode": "Mode", + "standaloneHcColumnTarget": "Cible", + "standaloneHcHealthStateHealthy": "Sain", + "standaloneHcHealthStateUnhealthy": "En mauvaise santé", + "standaloneHcHealthStateUnknown": "Inconnu", + "standaloneHcFilterAnySite": "Tous les nœuds", + "standaloneHcFilterAnyResource": "Toutes les ressources", + "standaloneHcFilterMode": "Mode", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "Ping", + "standaloneHcFilterHealth": "Santé", + "standaloneHcFilterEnabled": "Activé", + "standaloneHcFilterEnabledOn": "Activé", + "standaloneHcFilterEnabledOff": "Désactivé", + "standaloneHcFilterSiteIdFallback": "Site {id}", + "standaloneHcFilterResourceIdFallback": "Ressource {id}", "blueprints": "Configs", "blueprintsDescription": "Appliquer les configurations déclaratives et afficher les exécutions précédentes", "blueprintAdd": "Ajouter une Config", @@ -1763,6 +1935,15 @@ "healthCheckIntervalMin": "L'intervalle de vérification doit être d'au moins 5 secondes", "healthCheckTimeoutMin": "Le délai doit être d'au moins 1 seconde", "healthCheckRetryMin": "Les tentatives de réessai doivent être d'au moins 1", + "healthCheckMode": "Mode de vérification", + "healthCheckStrategy": "Stratégie", + "healthCheckModeDescription": "Le mode TCP vérifie uniquement la connectivité. Le mode HTTP valide la réponse HTTP.", + "healthyThreshold": "Seuil de santé", + "healthyThresholdDescription": "Succès consécutifs requis avant de marquer comme sain.", + "unhealthyThreshold": "Seuil de non-santé", + "unhealthyThresholdDescription": "Echecs consécutifs requis avant de signaler comme non sain.", + "healthCheckHealthyThresholdMin": "Le seuil de santé doit être d'au moins 1", + "healthCheckUnhealthyThresholdMin": "Le seuil de non-santé doit être d'au moins 1", "httpMethod": "Méthode HTTP", "selectHttpMethod": "Sélectionnez la méthode HTTP", "domainPickerSubdomainLabel": "Sous-domaine", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "Port", "editInternalResourceDialogModeHost": "Hôte", "editInternalResourceDialogModeCidr": "CIDR", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "Méthode HTTP", + "editInternalResourceDialogEnableSsl": "Activer SSL", + "editInternalResourceDialogEnableSslDescription": "Activer le cryptage SSL/TLS pour des connexions HTTPS sécurisées vers la destination.", "editInternalResourceDialogDestination": "Destination", "editInternalResourceDialogDestinationHostDescription": "L'adresse IP ou le nom d'hôte de la ressource sur le réseau du site.", "editInternalResourceDialogDestinationIPDescription": "L'adresse IP ou le nom d'hôte de la ressource sur le réseau du site.", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "Nom", "createInternalResourceDialogSite": "Site", "selectSite": "Sélectionner un site...", + "multiSitesSelectorSitesCount": "{count, plural, one {# site} other {# sites}}", "noSitesFound": "Aucun site trouvé.", "createInternalResourceDialogProtocol": "Protocole", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "Port", "createInternalResourceDialogModeHost": "Hôte", "createInternalResourceDialogModeCidr": "CIDR", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "Méthode HTTP", + "createInternalResourceDialogScheme": "Méthode HTTP", + "createInternalResourceDialogEnableSsl": "Activer SSL", + "createInternalResourceDialogEnableSslDescription": "Activer le cryptage SSL/TLS pour des connexions HTTPS sécurisées vers la destination.", "createInternalResourceDialogDestination": "Destination", "createInternalResourceDialogDestinationHostDescription": "L'adresse IP ou le nom d'hôte de la ressource sur le réseau du site.", "createInternalResourceDialogDestinationCidrDescription": "La gamme CIDR de la ressource sur le réseau du site.", "createInternalResourceDialogAlias": "Alias", "createInternalResourceDialogAliasDescription": "Un alias DNS interne optionnel pour cette ressource.", + "internalResourceDownstreamSchemeRequired": "Un schéma est requis pour les ressources HTTP", + "internalResourceHttpPortRequired": "Le port de destination est requis pour les ressources HTTP", "siteConfiguration": "Configuration", "siteAcceptClientConnections": "Accepter les connexions client", "siteAcceptClientConnectionsDescription": "Autoriser les utilisateurs et les clients à accéder aux ressources de ce site. Cela peut être modifié plus tard.", @@ -1994,7 +2189,7 @@ "description": "Serveur Pangolin auto-hébergé avec des cloches et des sifflets supplémentaires", "introTitle": "Pangolin auto-hébergé géré", "introDescription": "est une option de déploiement conçue pour les personnes qui veulent de la simplicité et de la fiabilité tout en gardant leurs données privées et auto-hébergées.", - "introDetail": "Avec cette option, vous exécutez toujours votre propre nœud Pangolin — vos tunnels, la terminaison SSL et le trafic restent sur votre serveur. La différence est que la gestion et la surveillance sont gérées via notre tableau de bord du cloud, qui déverrouille un certain nombre d'avantages :", + "introDetail": "Avec cette option, vous exécutez toujours votre propre nœud Pangolin - vos tunnels, la terminaison SSL et le trafic restent sur votre serveur. La différence est que la gestion et la surveillance sont gérées via notre tableau de bord du cloud, qui déverrouille un certain nombre d'avantages :", "benefitSimplerOperations": { "title": "Opérations plus simples", "description": "Pas besoin de faire tourner votre propre serveur de messagerie ou de configurer des alertes complexes. Vous obtiendrez des contrôles de santé et des alertes de temps d'arrêt par la suite." @@ -2119,7 +2314,7 @@ "selectDomainForOrgAuthPage": "Sélectionnez un domaine pour la page d'authentification de l'organisation", "domainPickerProvidedDomain": "Domaine fourni", "domainPickerFreeProvidedDomain": "Domaine fourni gratuitement", - "domainPickerFreeDomainsPaidFeature": "Les domaines fournis sont une fonctionnalité payante. Abonnez-vous pour obtenir un domaine inclus avec votre plan — plus besoin de fournir le vôtre.", + "domainPickerFreeDomainsPaidFeature": "Les domaines fournis sont une fonctionnalité payante. Abonnez-vous pour obtenir un domaine inclus avec votre plan - plus besoin de fournir le vôtre.", "domainPickerVerified": "Vérifié", "domainPickerUnverified": "Non vérifié", "domainPickerManual": "Manuel", @@ -2297,7 +2492,7 @@ "alerts": { "commercialUseDisclosure": { "title": "Divulgation d'utilisation", - "description": "Sélectionnez le niveau de licence qui correspond exactement à votre utilisation prévue. La Licence Personnelle autorise l'utilisation libre du Logiciel pour des activités commerciales individuelles, non commerciales ou à petite échelle avec un revenu annuel brut inférieur à 100 000 USD. Toute utilisation au-delà de ces limites — y compris l'utilisation au sein d'une entreprise, d'une organisation, ou tout autre environnement générateur de revenus — nécessite une licence d’entreprise valide et le paiement des droits de licence applicables. Tous les utilisateurs, qu'ils soient personnels ou d'entreprise, doivent se conformer aux conditions de licence commerciale Fossorial." + "description": "Sélectionnez le niveau de licence qui correspond exactement à votre utilisation prévue. La Licence Personnelle autorise l'utilisation libre du Logiciel pour des activités commerciales individuelles, non commerciales ou à petite échelle avec un revenu annuel brut inférieur à 100 000 USD. Toute utilisation au-delà de ces limites - y compris l'utilisation au sein d'une entreprise, d'une organisation, ou tout autre environnement générateur de revenus - nécessite une licence d’entreprise valide et le paiement des droits de licence applicables. Tous les utilisateurs, qu'ils soient personnels ou d'entreprise, doivent se conformer aux conditions de licence commerciale Fossorial." }, "trialPeriodInformation": { "title": "Informations sur la période d'essai", @@ -2429,6 +2624,7 @@ "validPassword": "Mot de passe valide", "validEmail": "Valid email", "validSSO": "Valid SSO", + "connectedClient": "Client connecté", "resourceBlocked": "Ressource bloquée", "droppedByRule": "Abandonné par la règle", "noSessions": "Aucune session", @@ -2668,6 +2864,10 @@ "editInternalResourceDialogDestinationLabel": "Destination", "editInternalResourceDialogDestinationDescription": "Indiquez l'adresse de destination pour la ressource interne. Cela peut être un nom d'hôte, une adresse IP ou une plage CIDR selon le mode sélectionné. Définissez éventuellement un alias DNS interne pour une identification plus facile.", "editInternalResourceDialogPortRestrictionsDescription": "Restreindre l'accès à des ports TCP/UDP spécifiques ou autoriser/bloquer tous les ports.", + "createInternalResourceDialogHttpConfiguration": "Configuration HTTP", + "createInternalResourceDialogHttpConfigurationDescription": "Choisissez le domaine que les clients utiliseront pour atteindre cette ressource via HTTP ou HTTPS.", + "editInternalResourceDialogHttpConfiguration": "Configuration HTTP", + "editInternalResourceDialogHttpConfigurationDescription": "Choisissez le domaine que les clients utiliseront pour atteindre cette ressource via HTTP ou HTTPS.", "editInternalResourceDialogTcp": "TCP", "editInternalResourceDialogUdp": "UDP", "editInternalResourceDialogIcmp": "ICMP", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "Nous serons bientôt de retour ! Notre site est actuellement en maintenance planifiée.", "maintenancePageMessageDescription": "Message détaillé expliquant la maintenance", "maintenancePageTimeTitle": "Temps d'achèvement estimé (facultatif)", + "privateMaintenanceScreenTitle": "Écran de maintien de service privé", + "privateMaintenanceScreenMessage": "Ce domaine est utilisé sur une ressource privée. Veuillez vous connecter à l'aide du client Pangolin pour accéder à cette ressource.", "maintenanceTime": "par exemple, 2 heures, le 1er nov. à 17:00", "maintenanceEstimatedTimeDescription": "Quand vous attendez que la maintenance soit terminée", "editDomain": "Modifier le domaine", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "Ajouter une destination HTTP", "httpDestEditDescription": "Mettre à jour la configuration pour cette destination de streaming d'événements HTTP.", "httpDestAddDescription": "Configurez un nouveau point de terminaison HTTP pour recevoir les événements de votre organisation.", + "S3DestEditTitle": "Modifier la destination", + "S3DestAddTitle": "Ajouter une destination S3", + "S3DestEditDescription": "Mettre à jour la configuration de cette destination de diffusion d'événements S3.", + "S3DestAddDescription": "Configurer un nouveau point de terminaison S3 pour recevoir les événements de votre organisation.", + "datadogDestEditTitle": "Modifier la destination", + "datadogDestAddTitle": "Ajouter une destination Datadog", + "datadogDestEditDescription": "Mettre à jour la configuration de cette destination de diffusion d'événements Datadog.", + "datadogDestAddDescription": "Configurer un nouveau point de terminaison Datadog pour recevoir les événements de votre organisation.", "httpDestTabSettings": "Réglages", "httpDestTabHeaders": "En-têtes", "httpDestTabBody": "Corps", @@ -2882,7 +3092,7 @@ "httpDestFormatJsonArrayTitle": "Tableau JSON", "httpDestFormatJsonArrayDescription": "Une requête par lot, le corps est un tableau JSON. Compatible avec la plupart des webhooks génériques et des datadog.", "httpDestFormatNdjsonTitle": "NDJSON", - "httpDestFormatNdjsonDescription": "Une requête par lot, body est un JSON délimité par une nouvelle ligne — un objet par ligne, pas de tableau extérieur. Requis par Splunk HEC, Elastic / OpenSearch, et Grafana Loki.", + "httpDestFormatNdjsonDescription": "Une requête par lot, body est un JSON délimité par une nouvelle ligne - un objet par ligne, pas de tableau extérieur. Requis par Splunk HEC, Elastic / OpenSearch, et Grafana Loki.", "httpDestFormatSingleTitle": "Un événement par demande", "httpDestFormatSingleDescription": "Envoie un POST HTTP séparé pour chaque événement individuel. Utilisé uniquement pour les terminaux qui ne peuvent pas gérer des lots.", "httpDestLogTypesTitle": "Types de logs", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "Destination créée avec succès", "httpDestUpdateFailed": "Impossible de mettre à jour la destination", "httpDestCreateFailed": "Impossible de créer la destination", + "followRedirects": "Suivre les redirections", + "followRedirectsDescription": "Suivre automatiquement les redirections HTTP pour les requêtes.", + "alertingErrorWebhookUrl": "Veuillez entrer une URL valide pour le webhook.", + "healthCheckStrategyHttp": "Valide la connectivité et vérifie le statut de la réponse HTTP.", + "healthCheckStrategyTcp": "Vérifie uniquement la connectivité TCP, sans inspecter la réponse.", + "healthCheckStrategySnmp": "Effectue une requête SNMP pour vérifier la santé des dispositifs et de l'infrastructure réseau.", + "healthCheckStrategyIcmp": "Utilise des requêtes écho ICMP (pings) pour vérifier si une ressource est accessible et réactive.", + "healthCheckTabStrategy": "Stratégie", + "healthCheckTabConnection": "Connexion", + "healthCheckTabAdvanced": "Avancé", + "healthCheckStrategyNotAvailable": "Cette stratégie n'est pas disponible. Veuillez contacter le service commercial pour activer cette fonctionnalité.", + "uptime30d": "Disponibilité (30j)", "idpAddActionCreateNew": "Créer un nouveau fournisseur d'identité", "idpAddActionImportFromOrg": "Importer d'une autre organisation", "idpImportDialogTitle": "Importer le fournisseur d'identité", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "Cela ne peut pas être annulé pour cette organisation.", "idpUnassociatedDescription": "Fournisseur d'identités dissocié de cette organisation avec succès", "idpUnassociateMenu": "Dissocier", - "idpDeleteAllOrgsMenu": "Supprimer" + "idpDeleteAllOrgsMenu": "Supprimer", + "publicIpEndpoint": "Point de terminaison", + "lastTriggeredAt": "Dernier déclenchement", + "reject": "Rejeter" } diff --git a/messages/it-IT.json b/messages/it-IT.json index b76e1b3c7..e1e3a586e 100644 --- a/messages/it-IT.json +++ b/messages/it-IT.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "Contatta le vendite per abilitare questa funzionalità.", + "contactSalesBookDemo": "Prenota una demo", + "contactSalesOr": "o", + "contactSalesContactUs": "contattaci", "setupCreate": "Creare l'organizzazione, il sito e le risorse", "headerAuthCompatibilityInfo": "Abilita questa funzionalità per forzare una risposta 401 Unauthorized quando manca un token di autenticazione. Questo è richiesto per browser o librerie HTTP specifiche che non inviano credenziali senza una sfida del server.", "headerAuthCompatibility": "Compatibilità estesa", @@ -19,6 +23,14 @@ "componentsInvalidKey": "Rilevata chiave di licenza non valida o scaduta. Segui i termini di licenza per continuare a utilizzare tutte le funzionalità.", "dismiss": "Ignora", "subscriptionViolationMessage": "Hai superato i tuoi limiti per il tuo piano attuale. Correggi il problema rimuovendo siti, utenti o altre risorse per rimanere all'interno del tuo piano.", + "trialBannerMessage": "Il tuo periodo di prova scade tra {countdown}. Aggiorna per mantenere l'accesso.", + "trialBannerExpired": "Il tuo periodo di prova è scaduto. Aggiorna ora per ripristinare l'accesso.", + "trialActive": "Prova Gratuita Attiva", + "trialExpired": "Prova scaduta", + "trialHasEnded": "La tua prova è terminata.", + "trialDaysRemaining": "{count, plural, one {# giorno rimanente} other {# giorni rimanenti}}", + "trialDaysLeftShort": "{days}g rimasti nella prova", + "trialGoToBilling": "Vai alla pagina di fatturazione", "subscriptionViolationViewBilling": "Visualizza fatturazione", "componentsLicenseViolation": "Violazione della licenza: Questo server sta usando i siti {usedSites} che superano il suo limite concesso in licenza per i siti {maxSites} . Segui i termini di licenza per continuare a usare tutte le funzionalità.", "componentsSupporterMessage": "Grazie per aver supportato Pangolin come {tier}!", @@ -267,8 +279,11 @@ "orgMissing": "ID Organizzazione Mancante", "orgMissingMessage": "Impossibile rigenerare l'invito senza un ID organizzazione.", "accessUsersManage": "Gestisci Utenti", + "accessUserManage": "Gestisci Utente", "accessUsersDescription": "Invita e gestisci gli utenti con accesso a questa organizzazione", "accessUsersSearch": "Cerca utenti...", + "accessUsersRoleFilterCount": "{count, plural, one {# ruolo} other {# ruoli}}", + "accessUsersRoleFilterClear": "Cancella filtri ruolo", "accessUserCreate": "Crea Utente", "accessUserRemove": "Rimuovi Utente", "username": "Nome utente", @@ -1257,6 +1272,7 @@ "actionViewLogs": "Visualizza Log", "noneSelected": "Nessuna selezione", "orgNotFound2": "Nessuna organizzazione trovata.", + "search": "Cerca…", "searchPlaceholder": "Cerca...", "emptySearchOptions": "Nessuna opzione trovata", "create": "Crea", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "Gestisci", "sidebarLogAndAnalytics": "Log & Analytics", "sidebarBluePrints": "Progetti", + "sidebarAlerting": "Allerta", + "sidebarHealthChecks": "Controlli di salute", "sidebarOrganization": "Organizzazione", "sidebarManagement": "Gestione", "sidebarBillingAndLicenses": "Fatturazione E Licenze", "sidebarLogsAnalytics": "Analisi", + "alertingTitle": "Allerta", + "alertingDescription": "Definisci fonti, trigger e azioni per le notifiche", + "alertingRules": "Regole di allerta", + "alertingSearchRules": "Cerca regole…", + "alertingAddRule": "Crea Regola", + "alertingColumnSource": "Fonte", + "alertingColumnTrigger": "Trigger", + "alertingColumnActions": "Azioni", + "alertingColumnEnabled": "Abilitato", + "alertingDeleteQuestion": "Si prega di confermare di voler eliminare questa regola di allerta.", + "alertingDeleteRule": "Elimina regola di allerta", + "alertingRuleDeleted": "Regola di allerta eliminata", + "alertingRuleSaved": "Regola di allerta salvata", + "alertingRuleSavedCreatedDescription": "La tua nuova regola di allerta è stata creata. Puoi continuare a modificarla su questa pagina.", + "alertingRuleSavedUpdatedDescription": "Le modifiche a questa regola di allerta sono state salvate.", + "alertingEditRule": "Modifica Regola di Allerta", + "alertingCreateRule": "Crea Regola di Allerta", + "alertingRuleCredenzaDescription": "Scegli cosa monitorare, quando attivare e come notificare", + "alertingRuleNamePlaceholder": "Sito di produzione giù", + "alertingRuleEnabled": "Regola abilitata", + "alertingSectionSource": "Fonte", + "alertingSourceType": "Tipo Di Fonte", + "alertingSourceSite": "Sito", + "alertingSourceHealthCheck": "Controllo di Salute", + "alertingPickSites": "Siti", + "alertingPickHealthChecks": "Controlli di Salute", + "alertingPickResources": "Risorse", + "alertingAllSites": "Tutti i Siti", + "alertingAllSitesDescription": "L'allerta scatta per qualsiasi sito", + "alertingSpecificSites": "Siti Specifici", + "alertingSpecificSitesDescription": "Scegli siti specifici da monitorare", + "alertingAllHealthChecks": "Tutti i Controlli di Salute", + "alertingAllHealthChecksDescription": "L'allerta scatta per qualsiasi controllo di salute", + "alertingSpecificHealthChecks": "Controlli di Salute Specifici", + "alertingSpecificHealthChecksDescription": "Scegli controlli di salute specifici da monitorare", + "alertingAllResources": "Tutte le Risorse", + "alertingAllResourcesDescription": "L'allerta scatta per qualsiasi risorsa", + "alertingSpecificResources": "Risorse Specifiche", + "alertingSpecificResourcesDescription": "Scegli risorse specifiche da monitorare", + "alertingSelectResources": "Seleziona risorse…", + "alertingResourcesSelected": "{count} risorse selezionate", + "alertingResourcesEmpty": "Nessuna risorsa con target nei primi 10 risultati.", + "alertingSectionTrigger": "Trigger", + "alertingTrigger": "Quando allertare", + "alertingTriggerSiteOnline": "Sito online", + "alertingTriggerSiteOffline": "Sito offline", + "alertingTriggerSiteToggle": "I cambiamenti di stato del sito", + "alertingTriggerHcHealthy": "Controllo di Salute Sano", + "alertingTriggerHcUnhealthy": "Controllo di Salute Non Sano", + "alertingTriggerHcToggle": "I cambiamenti di stato del controllo di salute", + "alertingTriggerResourceHealthy": "Risorsa in buona salute", + "alertingTriggerResourceUnhealthy": "Risorsa in cattiva salute", + "alertingSearchHealthChecks": "Cerca controlli di salute…", + "alertingHealthChecksEmpty": "Nessun controllo di salute disponibile.", + "alertingTriggerResourceToggle": "Variazioni di stato della risorsa", + "alertingSourceResource": "Fonte", + "alertingSectionActions": "Azioni", + "alertingAddAction": "Aggiungi Azione", + "alertingActionNotify": "Email", + "alertingActionNotifyDescription": "Invia notifiche email agli utenti o ai ruoli", + "alertingActionWebhook": "Webhook", + "alertingActionWebhookDescription": "Invia una richiesta HTTP a un endpoint personalizzato", + "alertingExternalIntegration": "Integrazione esterna", + "alertingExternalPagerDutyDescription": "Invia avvisi a PagerDuty per la gestione degli incidenti", + "alertingExternalOpsgenieDescription": "Indirizza avvisi a Opsgenie per la gestione delle chiamate", + "alertingExternalServiceNowDescription": "Crea incidenti ServiceNow dagli eventi di allerta", + "alertingExternalIncidentIoDescription": "Attiva i flussi di lavoro di Incident.io dagli eventi di allerta", + "alertingActionType": "Tipo di azione", + "alertingNotifyUsers": "Utenti", + "alertingNotifyRoles": "Ruoli", + "alertingNotifyEmails": "Indirizzi email", + "alertingEmailPlaceholder": "Aggiungi email e premi Invio", + "alertingWebhookMethod": "Metodo HTTP", + "alertingWebhookSecret": "Segreto di firma (opzionale)", + "alertingWebhookSecretPlaceholder": "Segreto HMAC", + "alertingWebhookHeaders": "Intestazioni", + "alertingAddHeader": "Aggiungi intestazione", + "alertingSelectSites": "Seleziona siti…", + "alertingSitesSelected": "{count} siti selezionati", + "alertingSelectHealthChecks": "Seleziona controlli di salute…", + "alertingHealthChecksSelected": "{count} controlli di salute selezionati", + "alertingNoHealthChecks": "Nessun obiettivo con controlli di salute abilitati", + "alertingHealthCheckStub": "Selezione fonte controllo di salute non ancora collegata - puoi comunque configurare trigger e azioni.", + "alertingSelectUsers": "Seleziona utenti…", + "alertingUsersSelected": "{count} utenti selezionati", + "alertingSelectRoles": "Seleziona ruoli…", + "alertingRolesSelected": "{count} ruoli selezionati", + "alertingSummarySites": "Siti ({count})", + "alertingSummaryAllSites": "Tutti i siti", + "alertingSummaryHealthChecks": "Controlli di Salute ({count})", + "alertingSummaryAllHealthChecks": "Tutti i controlli di salute", + "alertingSummaryResources": "Risorse ({count})", + "alertingSummaryAllResources": "Tutte le risorse", + "alertingErrorNameRequired": "Inserisci un nome", + "alertingErrorActionsMin": "Aggiungi almeno un'azione", + "alertingErrorPickSites": "Seleziona almeno un sito", + "alertingErrorPickHealthChecks": "Seleziona almeno un controllo di salute", + "alertingErrorPickResources": "Seleziona almeno una risorsa", + "alertingErrorTriggerSite": "Scegli un trigger sito", + "alertingErrorTriggerHealth": "Scegli un trigger controllo di salute", + "alertingErrorTriggerResource": "Scegli un trigger risorsa", + "alertingErrorNotifyRecipients": "Seleziona utenti, ruoli o almeno un indirizzo email", + "alertingConfigureSource": "Configura Fonte", + "alertingConfigureTrigger": "Configura Trigger", + "alertingConfigureActions": "Configura Azioni", + "alertingBackToRules": "Torna alle Regole", + "alertingRuleCooldown": "Tempo di riposo (secondi)", + "alertingRuleCooldownDescription": "Tempo minimo tra avvisi ripetuti per la stessa regola. Imposta a 0 per attivare ogni volta.", + "alertingDraftBadge": "Bozza - salva per memorizzare questa regola", + "alertingSidebarHint": "Clicca su un passaggio nella tela per modificarlo qui.", + "alertingGraphCanvasTitle": "Flusso della regola", + "alertingGraphCanvasDescription": "Panoramica visiva di fonte, trigger e azioni. Seleziona un nodo per modificarlo nel pannello.", + "alertingNodeNotConfigured": "Non ancora configurato", + "alertingNodeActionsCount": "{count, plural, one {# azione} other {# azioni}}", + "alertingNodeRoleSource": "Fonte", + "alertingNodeRoleTrigger": "Trigger", + "alertingNodeRoleAction": "Azione", + "alertingTabRules": "Regole di Allerta", + "alertingTabHealthChecks": "Controlli di Salute", + "alertingRulesBannerTitle": "Ricevi Notifiche", + "alertingRulesBannerDescription": "Ogni regola collega ciò che monitorare (un sito, controllo di salute o risorsa), quando attivare (ad esempio offline o non sano) e come notificare il tuo team via email, webhook o integrazioni. Usa questo elenco per creare, abilitare e gestire queste regole.", + "alertingHealthChecksBannerTitle": "Monitora Salute & Risorse", + "alertingHealthChecksBannerDescription": "I controlli di salute sono monitor HTTP o TCP che definisci una volta. Puoi poi usarli come fonti nelle regole di allerta così ricevi avvisi quando un obiettivo diventa sano o non sano. I controlli di salute sulle risorse appaiono anche qui.", + "standaloneHcTableTitle": "Controlli di Salute", + "standaloneHcSearchPlaceholder": "Cerca controlli di salute…", + "standaloneHcAddButton": "Crea Controllo di Salute", + "standaloneHcCreateTitle": "Crea Controllo di Salute", + "standaloneHcEditTitle": "Modifica Controllo di Salute", + "standaloneHcDescription": "Configura un controllo di salute HTTP o TCP da utilizzare nelle regole di allerta.", + "standaloneHcNameLabel": "Nome", + "standaloneHcNamePlaceholder": "Il mio Monitor HTTP", + "standaloneHcDeleteTitle": "Elimina controllo di salute", + "standaloneHcDeleteQuestion": "Si prega di confermare di voler eliminare questo controllo di integrità.", + "standaloneHcDeleted": "Controllo di salute eliminato", + "standaloneHcSaved": "Controllo di salute salvato", + "standaloneHcColumnHealth": "Salute", + "standaloneHcColumnMode": "Modalità", + "standaloneHcColumnTarget": "Target", + "standaloneHcHealthStateHealthy": "Sano", + "standaloneHcHealthStateUnhealthy": "Non Sano", + "standaloneHcHealthStateUnknown": "Sconosciuto", + "standaloneHcFilterAnySite": "Tutti i siti", + "standaloneHcFilterAnyResource": "Tutte le risorse", + "standaloneHcFilterMode": "Modalità", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "Ping", + "standaloneHcFilterHealth": "Salute", + "standaloneHcFilterEnabled": "Abilitato", + "standaloneHcFilterEnabledOn": "Abilitato", + "standaloneHcFilterEnabledOff": "Disabilitato", + "standaloneHcFilterSiteIdFallback": "Sito {id}", + "standaloneHcFilterResourceIdFallback": "Risorsa {id}", "blueprints": "Progetti", "blueprintsDescription": "Applica le configurazioni dichiarative e visualizza le partite precedenti", "blueprintAdd": "Aggiungi Progetto", @@ -1763,6 +1935,15 @@ "healthCheckIntervalMin": "L'intervallo del controllo deve essere almeno di 5 secondi", "healthCheckTimeoutMin": "Il timeout deve essere di almeno 1 secondo", "healthCheckRetryMin": "I tentativi di riprova devono essere almeno 1", + "healthCheckMode": "Verifica Modalità", + "healthCheckStrategy": "Strategia", + "healthCheckModeDescription": "La modalità TCP verifica solo la connettività. La modalità HTTP valida la risposta HTTP.", + "healthyThreshold": "Soglia di salute", + "healthyThresholdDescription": "Successi consecutivi necessari prima di contrassegnare come sano.", + "unhealthyThreshold": "Soglia non sana", + "unhealthyThresholdDescription": "Fallimenti consecutivi richiesti prima di contrassegnare come non sano.", + "healthCheckHealthyThresholdMin": "La soglia di salute deve essere almeno 1", + "healthCheckUnhealthyThresholdMin": "La soglia non sana deve essere almeno 1", "httpMethod": "Metodo HTTP", "selectHttpMethod": "Seleziona metodo HTTP", "domainPickerSubdomainLabel": "Sottodominio", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "Porta", "editInternalResourceDialogModeHost": "Host", "editInternalResourceDialogModeCidr": "CIDR", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "Metodo HTTP", + "editInternalResourceDialogEnableSsl": "Abilitare SSL", + "editInternalResourceDialogEnableSslDescription": "Abilita la crittografia SSL/TLS per connessioni HTTPS sicure alla destinazione.", "editInternalResourceDialogDestination": "Destinazione", "editInternalResourceDialogDestinationHostDescription": "L'indirizzo IP o il nome host della risorsa nella rete del sito.", "editInternalResourceDialogDestinationIPDescription": "L'indirizzo IP o hostname della risorsa nella rete del sito.", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "Nome", "createInternalResourceDialogSite": "Sito", "selectSite": "Seleziona sito...", + "multiSitesSelectorSitesCount": "{count, plural, one {# sito} other {# siti}}", "noSitesFound": "Nessun sito trovato.", "createInternalResourceDialogProtocol": "Protocollo", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "Porta", "createInternalResourceDialogModeHost": "Host", "createInternalResourceDialogModeCidr": "CIDR", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "Metodo HTTP", + "createInternalResourceDialogScheme": "Metodo HTTP", + "createInternalResourceDialogEnableSsl": "Abilitare SSL", + "createInternalResourceDialogEnableSslDescription": "Abilita la crittografia SSL/TLS per connessioni HTTPS sicure alla destinazione.", "createInternalResourceDialogDestination": "Destinazione", "createInternalResourceDialogDestinationHostDescription": "L'indirizzo IP o il nome host della risorsa nella rete del sito.", "createInternalResourceDialogDestinationCidrDescription": "La gamma CIDR della risorsa sulla rete del sito.", "createInternalResourceDialogAlias": "Alias", "createInternalResourceDialogAliasDescription": "Un alias DNS interno opzionale per questa risorsa.", + "internalResourceDownstreamSchemeRequired": "Il metodo è richiesto per risorse HTTP", + "internalResourceHttpPortRequired": "Porta di destinazione richiesta per risorse HTTP", "siteConfiguration": "Configurazione", "siteAcceptClientConnections": "Accetta Connessioni Client", "siteAcceptClientConnectionsDescription": "Consenti ai dispositivi utente e ai client di accedere alle risorse di questo sito. Questo può essere modificato in seguito.", @@ -1994,7 +2189,7 @@ "description": "Server Pangolin self-hosted più affidabile e a bassa manutenzione con campanelli e fischietti extra", "introTitle": "Managed Self-Hosted Pangolin", "introDescription": "è un'opzione di distribuzione progettata per le persone che vogliono la semplicità e l'affidabilità extra mantenendo i loro dati privati e self-hosted.", - "introDetail": "Con questa opzione, esegui ancora il tuo nodo Pangolin — i tunnel, la terminazione SSL e il traffico rimangono tutti sul tuo server. La differenza è che la gestione e il monitoraggio sono gestiti attraverso il nostro cruscotto cloud, che sblocca una serie di vantaggi:", + "introDetail": "Con questa opzione, esegui ancora il tuo nodo Pangolin - i tunnel, la terminazione SSL e il traffico rimangono tutti sul tuo server. La differenza è che la gestione e il monitoraggio sono gestiti attraverso il nostro cruscotto cloud, che sblocca una serie di vantaggi:", "benefitSimplerOperations": { "title": "Operazioni più semplici", "description": "Non è necessario eseguire il proprio server di posta o impostare un avviso complesso. Otterrai controlli di salute e avvisi di inattività fuori dalla casella." @@ -2119,7 +2314,7 @@ "selectDomainForOrgAuthPage": "Seleziona un dominio per la pagina di autenticazione dell'organizzazione", "domainPickerProvidedDomain": "Dominio Fornito", "domainPickerFreeProvidedDomain": "Dominio Fornito Gratuito", - "domainPickerFreeDomainsPaidFeature": "I domini forniti sono una funzionalità a pagamento. Abbonati per ricevere un dominio incluso con il tuo piano — non è necessario portare il proprio.", + "domainPickerFreeDomainsPaidFeature": "I domini forniti sono una funzionalità a pagamento. Abbonati per ricevere un dominio incluso con il tuo piano - non è necessario portare il proprio.", "domainPickerVerified": "Verificato", "domainPickerUnverified": "Non Verificato", "domainPickerManual": "Manuale", @@ -2297,7 +2492,7 @@ "alerts": { "commercialUseDisclosure": { "title": "Trasparenza Di Utilizzo", - "description": "Seleziona il livello di licenza che rispecchia accuratamente il tuo utilizzo previsto. La Licenza Personale consente l'uso gratuito del Software per le attività commerciali individuali, non commerciali o su piccola scala con entrate lorde annue inferiori a $100.000 USD. Qualsiasi uso oltre questi limiti — compreso l'uso all'interno di un'azienda, organizzazione, o altro ambiente generatore di entrate — richiede una licenza Enterprise valida e il pagamento della tassa di licenza applicabile. Tutti gli utenti, siano essi personali o aziendali, devono rispettare i termini di licenza commerciale Fossorial." + "description": "Seleziona il livello di licenza che rispecchia accuratamente il tuo utilizzo previsto. La Licenza Personale consente l'uso gratuito del Software per le attività commerciali individuali, non commerciali o su piccola scala con entrate lorde annue inferiori a $100.000 USD. Qualsiasi uso oltre questi limiti - compreso l'uso all'interno di un'azienda, organizzazione, o altro ambiente generatore di entrate - richiede una licenza Enterprise valida e il pagamento della tassa di licenza applicabile. Tutti gli utenti, siano essi personali o aziendali, devono rispettare i termini di licenza commerciale Fossorial." }, "trialPeriodInformation": { "title": "Informazioni Periodo Di Prova", @@ -2429,6 +2624,7 @@ "validPassword": "Password Valida", "validEmail": "Valid email", "validSSO": "Valid SSO", + "connectedClient": "Cliente Connesso", "resourceBlocked": "Risorsa Bloccata", "droppedByRule": "Eliminato dalla regola", "noSessions": "Nessuna Sessione", @@ -2668,6 +2864,10 @@ "editInternalResourceDialogDestinationLabel": "Destinazione", "editInternalResourceDialogDestinationDescription": "Specifica l'indirizzo di destinazione per la risorsa interna. Può essere un hostname, indirizzo IP o un intervallo CIDR a seconda della modalità selezionata. Opzionalmente imposta un alias DNS interno per una più facile identificazione.", "editInternalResourceDialogPortRestrictionsDescription": "Limita l'accesso a porte TCP/UDP specifiche o consenti/blocca tutte le porte.", + "createInternalResourceDialogHttpConfiguration": "Configurazione HTTP", + "createInternalResourceDialogHttpConfigurationDescription": "Scegli il dominio che i clienti utilizzeranno per accedere a questa risorsa tramite HTTP o HTTPS.", + "editInternalResourceDialogHttpConfiguration": "Configurazione HTTP", + "editInternalResourceDialogHttpConfigurationDescription": "Scegli il dominio che i clienti utilizzeranno per accedere a questa risorsa tramite HTTP o HTTPS.", "editInternalResourceDialogTcp": "TCP", "editInternalResourceDialogUdp": "UDP", "editInternalResourceDialogIcmp": "ICMP", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "Torneremo presto! Il nostro sito è attualmente in manutenzione programmata.", "maintenancePageMessageDescription": "Messaggio dettagliato che spiega la manutenzione", "maintenancePageTimeTitle": "Tempo di Completamento Stimato (Opzionale)", + "privateMaintenanceScreenTitle": "Schermo segnaposto privato", + "privateMaintenanceScreenMessage": "Questo dominio è utilizzato su una risorsa privata. Connettiti usando il client Pangolin per accedere a questa risorsa.", "maintenanceTime": "es. 2 ore, 1 novembre alle 17:00", "maintenanceEstimatedTimeDescription": "Quando prevedi che la manutenzione sarà completata", "editDomain": "Modifica Dominio", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "Aggiungi Destinazione HTTP", "httpDestEditDescription": "Aggiorna la configurazione per questa destinazione di streaming di eventi HTTP.", "httpDestAddDescription": "Configura un nuovo endpoint HTTP per ricevere gli eventi della tua organizzazione.", + "S3DestEditTitle": "Modifica Destinazione", + "S3DestAddTitle": "Aggiungi Destinazione S3", + "S3DestEditDescription": "Aggiorna la configurazione per questa destinazione di streaming eventi S3.", + "S3DestAddDescription": "Configura un nuovo endpoint S3 per ricevere gli eventi della tua organizzazione.", + "datadogDestEditTitle": "Modifica Destinazione", + "datadogDestAddTitle": "Aggiungi Destinazione Datadog", + "datadogDestEditDescription": "Aggiorna la configurazione per questa destinazione di streaming eventi Datadog.", + "datadogDestAddDescription": "Configura un nuovo endpoint Datadog per ricevere gli eventi della tua organizzazione.", "httpDestTabSettings": "Impostazioni", "httpDestTabHeaders": "Intestazioni", "httpDestTabBody": "Corpo", @@ -2882,7 +3092,7 @@ "httpDestFormatJsonArrayTitle": "JSON Array", "httpDestFormatJsonArrayDescription": "Una richiesta per lotto, corpo è un array JSON. Compatibile con la maggior parte dei webhooks generici e Datadog.", "httpDestFormatNdjsonTitle": "NDJSON", - "httpDestFormatNdjsonDescription": "Una richiesta per lotto, corpo è newline-delimited JSON — un oggetto per linea, nessun array esterno. Richiesto da Splunk HEC, Elastic / OpenSearch, e Grafana Loki.", + "httpDestFormatNdjsonDescription": "Una richiesta per lotto, corpo è newline-delimited JSON - un oggetto per linea, nessun array esterno. Richiesto da Splunk HEC, Elastic / OpenSearch, e Grafana Loki.", "httpDestFormatSingleTitle": "Un Evento Per Richiesta", "httpDestFormatSingleDescription": "Invia un HTTP POST separato per ogni singolo evento. Usa solo per gli endpoint che non possono gestire i batch.", "httpDestLogTypesTitle": "Tipi Di Log", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "Destinazione creata con successo", "httpDestUpdateFailed": "Impossibile aggiornare la destinazione", "httpDestCreateFailed": "Impossibile creare la destinazione", + "followRedirects": "Segui i reindirizzamenti", + "followRedirectsDescription": "Segui automaticamente i reindirizzamenti HTTP per le richieste.", + "alertingErrorWebhookUrl": "Inserisci un URL valido per il webhook.", + "healthCheckStrategyHttp": "Convalida la connettività e controlla lo stato della risposta HTTP.", + "healthCheckStrategyTcp": "Verifica solo la connettività TCP, senza controllare la risposta.", + "healthCheckStrategySnmp": "Effettua una richiesta SNMP per controllare la salute di dispositivi di rete e infrastrutture.", + "healthCheckStrategyIcmp": "Utilizza richieste ICMP echo (ping) per verificare se una risorsa è raggiungibile e reattiva.", + "healthCheckTabStrategy": "Strategia", + "healthCheckTabConnection": "Connessione", + "healthCheckTabAdvanced": "Avanzato", + "healthCheckStrategyNotAvailable": "Questa strategia non è disponibile. Contatta le vendite per abilitare questa funzionalità.", + "uptime30d": "Uptime (30d)", "idpAddActionCreateNew": "Crea nuovo provider di identità", "idpAddActionImportFromOrg": "Importa da un'altra organizzazione", "idpImportDialogTitle": "Importa Provider di Identità", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "Questo non può essere annullato per questa organizzazione.", "idpUnassociatedDescription": "Provider di identità disassociato con successo da questa organizzazione", "idpUnassociateMenu": "Disassocia", - "idpDeleteAllOrgsMenu": "Elimina" + "idpDeleteAllOrgsMenu": "Elimina", + "publicIpEndpoint": "Endpoint", + "lastTriggeredAt": "Ultimo trigger", + "reject": "Rifiuta" } diff --git a/messages/ko-KR.json b/messages/ko-KR.json index cce7adeb8..c3e08dca4 100644 --- a/messages/ko-KR.json +++ b/messages/ko-KR.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "이 기능을 활성화하려면 영업팀에 연락하세요.", + "contactSalesBookDemo": "데모 예약하기", + "contactSalesOr": "또는", + "contactSalesContactUs": "문의하기", "setupCreate": "조직, 사이트 및 리소스를 생성합니다.", "headerAuthCompatibilityInfo": "인증 토큰이 없을 때 401 Unauthorized 응답을 강제하도록 설정합니다. 서버 챌린지 없이 자격 증명을 제공하지 않는 브라우저나 특정 HTTP 라이브러리에 필요합니다.", "headerAuthCompatibility": "확장된 호환성", @@ -19,6 +23,14 @@ "componentsInvalidKey": "유효하지 않거나 만료된 라이센스 키가 감지되었습니다. 모든 기능을 계속 사용하려면 라이센스 조건을 따르십시오.", "dismiss": "해제", "subscriptionViolationMessage": "현재 계획의 한계를 초과했습니다. 사이트, 사용자 또는 기타 리소스를 제거하여 계획 내에 머물도록 해결하세요.", + "trialBannerMessage": "시험 사용 기간이 {countdown} 안에 만료됩니다. 업그레이드하여 액세스를 유지하세요.", + "trialBannerExpired": "시험 사용 기간이 만료되었습니다. 지금 업그레이드하여 액세스를 복구하세요.", + "trialActive": "무료 체험 활성화됨", + "trialExpired": "체험 만료됨", + "trialHasEnded": "시험 사용 기간이 종료되었습니다.", + "trialDaysRemaining": "{count, plural, other {#일 남음}}", + "trialDaysLeftShort": "시험 사용 기간 종료까지 {days}일 남음", + "trialGoToBilling": "청구 페이지로 이동", "subscriptionViolationViewBilling": "청구 보기", "componentsLicenseViolation": "라이센스 위반: 이 서버는 {usedSites} 사이트를 사용하고 있으며, 이는 {maxSites} 사이트의 라이센스 한도를 초과합니다. 모든 기능을 계속 사용하려면 라이센스 조건을 따르십시오.", "componentsSupporterMessage": "{tier}로 판골린을 지원해 주셔서 감사합니다!", @@ -267,8 +279,11 @@ "orgMissing": "조직 ID가 누락되었습니다", "orgMissingMessage": "조직 ID 없이 초대장을 재생성할 수 없습니다.", "accessUsersManage": "사용자 관리", + "accessUserManage": "사용자 관리", "accessUsersDescription": "이 조직에 액세스할 사용자 초대 및 관리", "accessUsersSearch": "사용자 검색...", + "accessUsersRoleFilterCount": "{count, plural, other {# 역할}}", + "accessUsersRoleFilterClear": "역할 필터 지우기", "accessUserCreate": "사용자 생성", "accessUserRemove": "사용자 제거", "username": "사용자 이름", @@ -1257,6 +1272,7 @@ "actionViewLogs": "로그 보기", "noneSelected": "선택된 항목 없음", "orgNotFound2": "조직이 없습니다.", + "search": "검색…", "searchPlaceholder": "검색...", "emptySearchOptions": "옵션이 없습니다", "create": "생성", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "관리", "sidebarLogAndAnalytics": "로그 & 통계", "sidebarBluePrints": "청사진", + "sidebarAlerting": "알림", + "sidebarHealthChecks": "상태 확인", "sidebarOrganization": "조직", "sidebarManagement": "관리", "sidebarBillingAndLicenses": "결제 및 라이선스", "sidebarLogsAnalytics": "분석", + "alertingTitle": "알림", + "alertingDescription": "알림에 대한 소스, 트리거 및 작업 정의", + "alertingRules": "알림 규칙", + "alertingSearchRules": "규칙 검색…", + "alertingAddRule": "규칙 생성", + "alertingColumnSource": "소스", + "alertingColumnTrigger": "트리거", + "alertingColumnActions": "작업", + "alertingColumnEnabled": "활성화됨", + "alertingDeleteQuestion": "이 알림 규칙을 삭제하겠습니까.", + "alertingDeleteRule": "알림 규칙 삭제", + "alertingRuleDeleted": "알림 규칙 삭제됨", + "alertingRuleSaved": "알림 규칙 저장됨", + "alertingRuleSavedCreatedDescription": "새 알림 규칙이 생성되었습니다. 이 페이지에서 계속 편집할 수 있습니다.", + "alertingRuleSavedUpdatedDescription": "이 알림 규칙에 대한 변경 사항이 저장되었습니다.", + "alertingEditRule": "알림 규칙 편집", + "alertingCreateRule": "알림 규칙 생성", + "alertingRuleCredenzaDescription": "무엇을 감시할지, 언제 알릴지, 어떻게 알릴지를 선택하세요.", + "alertingRuleNamePlaceholder": "프로덕션 사이트 중단", + "alertingRuleEnabled": "규칙 활성화됨", + "alertingSectionSource": "소스", + "alertingSourceType": "소스 유형", + "alertingSourceSite": "사이트", + "alertingSourceHealthCheck": "상태 확인", + "alertingPickSites": "사이트들", + "alertingPickHealthChecks": "상태 확인들", + "alertingPickResources": "리소스들", + "alertingAllSites": "모든 사이트", + "alertingAllSitesDescription": "모든 사이트에서 알림 발동", + "alertingSpecificSites": "특정 사이트", + "alertingSpecificSitesDescription": "감시할 특정 사이트를 선택하세요", + "alertingAllHealthChecks": "모든 상태 확인", + "alertingAllHealthChecksDescription": "모든 상태 확인에 대한 알림 발동", + "alertingSpecificHealthChecks": "특정 상태 확인", + "alertingSpecificHealthChecksDescription": "감시할 특정 상태 확인을 선택하세요", + "alertingAllResources": "모든 리소스", + "alertingAllResourcesDescription": "모든 리소스에 대한 알림 발동", + "alertingSpecificResources": "특정 리소스", + "alertingSpecificResourcesDescription": "감시할 특정 리소스를 선택하세요", + "alertingSelectResources": "리소스 선택…", + "alertingResourcesSelected": "{count}개의 리소스 선택됨", + "alertingResourcesEmpty": "앞 10개의 결과에서 타겟이 있는 리소스 없음.", + "alertingSectionTrigger": "트리거", + "alertingTrigger": "언제 알림을 받을지", + "alertingTriggerSiteOnline": "사이트 온라인", + "alertingTriggerSiteOffline": "사이트 오프라인", + "alertingTriggerSiteToggle": "사이트 상태 변경", + "alertingTriggerHcHealthy": "상태 확인 정상", + "alertingTriggerHcUnhealthy": "상태 확인 비정상", + "alertingTriggerHcToggle": "상태 확인 상태 변경", + "alertingTriggerResourceHealthy": "리소스 정상", + "alertingTriggerResourceUnhealthy": "리소스 비정상", + "alertingSearchHealthChecks": "상태 확인 검색…", + "alertingHealthChecksEmpty": "사용 가능한 상태 확인이 없습니다.", + "alertingTriggerResourceToggle": "리소스 상태 변경", + "alertingSourceResource": "리소스", + "alertingSectionActions": "작업", + "alertingAddAction": "작업 추가", + "alertingActionNotify": "이메일", + "alertingActionNotifyDescription": "사용자 또는 역할에게 이메일 알림 전송", + "alertingActionWebhook": "웹훅", + "alertingActionWebhookDescription": "사용자 정의 엔드포인트로 HTTP 요청 보내기", + "alertingExternalIntegration": "외부 통합", + "alertingExternalPagerDutyDescription": "사고 관리를 위해 PagerDuty에 알림 보내기", + "alertingExternalOpsgenieDescription": "대기 중인 관리자로 Opsgenie에 알림 보내기", + "alertingExternalServiceNowDescription": "알림 이벤트로 ServiceNow 사고 생성", + "alertingExternalIncidentIoDescription": "알림 이벤트로 Incident.io 워크플로우 트리거", + "alertingActionType": "작업 유형", + "alertingNotifyUsers": "사용자들", + "alertingNotifyRoles": "역할들", + "alertingNotifyEmails": "이메일 주소들", + "alertingEmailPlaceholder": "이메일 추가 후 Enter 키를 누르세요", + "alertingWebhookMethod": "HTTP 메소드", + "alertingWebhookSecret": "서명 비밀 (선택 사항)", + "alertingWebhookSecretPlaceholder": "HMAC 비밀", + "alertingWebhookHeaders": "헤더들", + "alertingAddHeader": "헤더 추가", + "alertingSelectSites": "사이트 선택…", + "alertingSitesSelected": "{count}개의 사이트 선택됨", + "alertingSelectHealthChecks": "상태 확인 선택…", + "alertingHealthChecksSelected": "{count}개의 상태 확인 선택됨", + "alertingNoHealthChecks": "활성화된 상태 확인이 있는 타겟 없음", + "alertingHealthCheckStub": "상태 확인 소스 선택은 아직 연결되지 않았습니다 - 트리거 및 작업을 계속 구성할 수 있습니다.", + "alertingSelectUsers": "사용자 선택…", + "alertingUsersSelected": "{count}명의 사용자 선택됨", + "alertingSelectRoles": "역할 선택…", + "alertingRolesSelected": "{count}개의 역할 선택됨", + "alertingSummarySites": "사이트 ({count})", + "alertingSummaryAllSites": "모든 사이트", + "alertingSummaryHealthChecks": "상태 확인 ({count})", + "alertingSummaryAllHealthChecks": "모든 상태 확인", + "alertingSummaryResources": "리소스 ({count})", + "alertingSummaryAllResources": "모든 리소스", + "alertingErrorNameRequired": "이름을 입력하세요", + "alertingErrorActionsMin": "최소한 하나의 작업 추가", + "alertingErrorPickSites": "최소한 하나의 사이트 선택", + "alertingErrorPickHealthChecks": "최소한 하나의 상태 확인 선택", + "alertingErrorPickResources": "최소한 하나의 리소스 선택", + "alertingErrorTriggerSite": "사이트 트리거 선택", + "alertingErrorTriggerHealth": "상태 확인 트리거 선택", + "alertingErrorTriggerResource": "리소스 트리거 선택", + "alertingErrorNotifyRecipients": "사용자, 역할 또는 최소 하나의 이메일 선택", + "alertingConfigureSource": "소스 구성", + "alertingConfigureTrigger": "트리거 구성", + "alertingConfigureActions": "작업 구성", + "alertingBackToRules": "규칙으로 돌아가기", + "alertingRuleCooldown": "냉각 시간 (초)", + "alertingRuleCooldownDescription": "같은 규칙에 대해 반복된 알림 사이의 최소 시간. 매번 발생하려면 0으로 설정하세요.", + "alertingDraftBadge": "초안 - 이 규칙을 저장하려면 저장", + "alertingSidebarHint": "여기에서 편집하려면 캔버스의 단계를 클릭하세요.", + "alertingGraphCanvasTitle": "규칙 흐름", + "alertingGraphCanvasDescription": "소스, 트리거 및 작업의 시각적 개요입니다. 노드를 선택하여 패널에서 수정할 수 있습니다.", + "alertingNodeNotConfigured": "아직 구성되지 않음", + "alertingNodeActionsCount": "{count, plural, other {# 작업}}", + "alertingNodeRoleSource": "소스", + "alertingNodeRoleTrigger": "트리거", + "alertingNodeRoleAction": "작업", + "alertingTabRules": "알림 규칙", + "alertingTabHealthChecks": "상태 확인", + "alertingRulesBannerTitle": "알림 받기", + "alertingRulesBannerDescription": "각 규칙은 무엇을 감시할지(사이트, 상태 확인, 리소스), 언제 발동할지(예: 오프라인 또는 비정상), 이메일, 웹훅 또는 통합을 통해 팀에 어떻게 알릴지를 연결합니다. 이 목록을 사용하여 규칙을 생성, 활성화 및 관리하세요.", + "alertingHealthChecksBannerTitle": "건강 및 리소스 모니터링", + "alertingHealthChecksBannerDescription": "상태 확인은 한 번 정의한 HTTP 또는 TCP 모니터링입니다. 그런 다음 이를 알림 규칙의 소스로 사용하여 타겟이 정상 또는 비정상이 되었을 때 알림을 받을 수 있습니다. 리소스의 상태 확인도 여기에 나타납니다.", + "standaloneHcTableTitle": "상태 확인", + "standaloneHcSearchPlaceholder": "상태 확인 검색…", + "standaloneHcAddButton": "상태 확인 생성", + "standaloneHcCreateTitle": "상태 확인 생성", + "standaloneHcEditTitle": "상태 확인 편집", + "standaloneHcDescription": "알림 규칙에 사용할 HTTP 또는 TCP 상태 확인을 구성하세요.", + "standaloneHcNameLabel": "이름", + "standaloneHcNamePlaceholder": "My HTTP Monitor", + "standaloneHcDeleteTitle": "상태 확인 삭제", + "standaloneHcDeleteQuestion": "이 상태 확인을 삭제하겠습니까.", + "standaloneHcDeleted": "상태 확인 삭제됨", + "standaloneHcSaved": "상태 확인 저장됨", + "standaloneHcColumnHealth": "건강", + "standaloneHcColumnMode": "모드", + "standaloneHcColumnTarget": "타겟", + "standaloneHcHealthStateHealthy": "정상", + "standaloneHcHealthStateUnhealthy": "비정상", + "standaloneHcHealthStateUnknown": "알 수 없음", + "standaloneHcFilterAnySite": "모든 사이트", + "standaloneHcFilterAnyResource": "모든 리소스", + "standaloneHcFilterMode": "모드", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "핑", + "standaloneHcFilterHealth": "건강", + "standaloneHcFilterEnabled": "활성화됨", + "standaloneHcFilterEnabledOn": "활성화됨", + "standaloneHcFilterEnabledOff": "비활성화됨", + "standaloneHcFilterSiteIdFallback": "사이트 {id}", + "standaloneHcFilterResourceIdFallback": "리소스 {id}", "blueprints": "청사진", "blueprintsDescription": "선언적 구성을 적용하고 이전 실행을 봅니다", "blueprintAdd": "청사진 추가", @@ -1763,6 +1935,15 @@ "healthCheckIntervalMin": "확인 간격은 최소 5초여야 합니다.", "healthCheckTimeoutMin": "시간 초과는 최소 1초여야 합니다.", "healthCheckRetryMin": "재시도 횟수는 최소 1회여야 합니다.", + "healthCheckMode": "확인 모드", + "healthCheckStrategy": "전략", + "healthCheckModeDescription": "TCP 모드는 연결성만 확인합니다. HTTP 모드는 HTTP 응답을 확인합니다.", + "healthyThreshold": "건강 임계값", + "healthyThresholdDescription": "정상으로 표시되기 전에 연속 성공이 필요합니다.", + "unhealthyThreshold": "비정상 임계값", + "unhealthyThresholdDescription": "비정상으로 표시되기 전에 연속 실패가 필요합니다.", + "healthCheckHealthyThresholdMin": "정상 임계값은 최소 1 이상이어야 합니다", + "healthCheckUnhealthyThresholdMin": "비정상 임계값은 최소 1 이상이어야 합니다", "httpMethod": "HTTP 메소드", "selectHttpMethod": "HTTP 메소드 선택", "domainPickerSubdomainLabel": "서브도메인", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "포트", "editInternalResourceDialogModeHost": "호스트", "editInternalResourceDialogModeCidr": "CIDR", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "스킴", + "editInternalResourceDialogEnableSsl": "SSL 활성화", + "editInternalResourceDialogEnableSslDescription": "목적지로의 안전한 HTTPS 연결을 위한 SSL/TLS 암호화 활성화.", "editInternalResourceDialogDestination": "대상지", "editInternalResourceDialogDestinationHostDescription": "사이트 네트워크의 자원 IP 주소입니다.", "editInternalResourceDialogDestinationIPDescription": "사이트 네트워크의 자원 IP 또는 호스트 네임 주소입니다.", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "이름", "createInternalResourceDialogSite": "사이트", "selectSite": "사이트 선택...", + "multiSitesSelectorSitesCount": "{count, plural, other {# 사이트}}", "noSitesFound": "사이트를 찾을 수 없습니다.", "createInternalResourceDialogProtocol": "프로토콜", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "포트", "createInternalResourceDialogModeHost": "호스트", "createInternalResourceDialogModeCidr": "CIDR", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "스킴", + "createInternalResourceDialogScheme": "스킴", + "createInternalResourceDialogEnableSsl": "SSL 활성화", + "createInternalResourceDialogEnableSslDescription": "목적지로의 안전한 HTTPS 연결을 위한 SSL/TLS 암호화 활성화.", "createInternalResourceDialogDestination": "대상지", "createInternalResourceDialogDestinationHostDescription": "사이트 네트워크의 자원 IP 주소입니다.", "createInternalResourceDialogDestinationCidrDescription": "사이트 네트워크의 자원 IP 주소입니다.", "createInternalResourceDialogAlias": "별칭", "createInternalResourceDialogAliasDescription": "이 리소스에 대한 선택적 내부 DNS 별칭입니다.", + "internalResourceDownstreamSchemeRequired": "HTTP 리소스에 스킴이 필요합니다", + "internalResourceHttpPortRequired": "HTTP 리소스에 목적지 포트가 필요합니다", "siteConfiguration": "설정", "siteAcceptClientConnections": "클라이언트 연결 허용", "siteAcceptClientConnectionsDescription": "사용자 장치와 클라이언트가 이 사이트의 리소스에 접근할 수 있도록 허용하세요. 나중에 변경할 수 있습니다.", @@ -2119,7 +2314,7 @@ "selectDomainForOrgAuthPage": "조직 인증 페이지에 대한 도메인을 선택하세요.", "domainPickerProvidedDomain": "제공된 도메인", "domainPickerFreeProvidedDomain": "무료 제공된 도메인", - "domainPickerFreeDomainsPaidFeature": "제공된 도메인은 유료 기능입니다. 요금제에 도메인이 포함되도록 구독하세요. — 별도로 도메인을 준비할 필요 없습니다.", + "domainPickerFreeDomainsPaidFeature": "제공된 도메인은 유료 기능입니다. 요금제에 도메인이 포함되도록 구독하세요. - 별도로 도메인을 준비할 필요 없습니다.", "domainPickerVerified": "검증됨", "domainPickerUnverified": "검증되지 않음", "domainPickerManual": "수동", @@ -2297,7 +2492,7 @@ "alerts": { "commercialUseDisclosure": { "title": "사용 공개", - "description": "당신의 의도된 사용에 정확히 맞는 라이선스 등급을 선택하세요. 개인 라이선스는 연간 총 수익 100,000 USD 이하의 개인, 비상업적 또는 소규모 상업 활동을 위한 소프트웨어의 무료 사용을 허용합니다. 이러한 제한을 넘는 모든 사용 — 비즈니스, 조직 또는 기타 수익 창출 환경 내에서의 사용 — 은 유효한 엔터프라이즈 라이선스 및 해당 라이선스 수수료의 지불이 필요합니다. 개인 또는 기업 사용자는 모두 Fossorial 상용 라이선스 조건을 준수해야 합니다." + "description": "당신의 의도된 사용에 정확히 맞는 라이선스 등급을 선택하세요. 개인 라이선스는 연간 총 수익 100,000 USD 이하의 개인, 비상업적 또는 소규모 상업 활동을 위한 소프트웨어의 무료 사용을 허용합니다. 이러한 제한을 넘는 모든 사용 - 비즈니스, 조직 또는 기타 수익 창출 환경 내에서의 사용 - 은 유효한 엔터프라이즈 라이선스 및 해당 라이선스 수수료의 지불이 필요합니다. 개인 또는 기업 사용자는 모두 Fossorial 상용 라이선스 조건을 준수해야 합니다." }, "trialPeriodInformation": { "title": "시험 기간 정보", @@ -2429,6 +2624,7 @@ "validPassword": "유효한 비밀번호", "validEmail": "유효한 이메일", "validSSO": "유효한 SSO", + "connectedClient": "연결된 클라이언트", "resourceBlocked": "리소스 차단됨", "droppedByRule": "룰에 의해 드롭됨", "noSessions": "세션 없음", @@ -2668,6 +2864,10 @@ "editInternalResourceDialogDestinationLabel": "대상지", "editInternalResourceDialogDestinationDescription": "내부 리소스의 목적지 주소를 지정하세요. 선택한 모드에 따라 이 주소는 호스트명, IP 주소, 또는 CIDR 범위가 될 수 있습니다. 더욱 쉽게 식별할 수 있도록 내부 DNS 별칭을 설정할 수 있습니다.", "editInternalResourceDialogPortRestrictionsDescription": "특정 TCP/UDP 포트에 대한 접근을 제한하거나 모든 포트를 허용/차단하십시오.", + "createInternalResourceDialogHttpConfiguration": "HTTP 구성", + "createInternalResourceDialogHttpConfigurationDescription": "이 리소스에 HTTP 또는 HTTPS로 도달하기 위한 도메인을 선택하세요.", + "editInternalResourceDialogHttpConfiguration": "HTTP 구성", + "editInternalResourceDialogHttpConfigurationDescription": "이 리소스에 HTTP 또는 HTTPS로 도달하기 위한 도메인을 선택하세요.", "editInternalResourceDialogTcp": "TCP", "editInternalResourceDialogUdp": "UDP", "editInternalResourceDialogIcmp": "ICMP", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "곧 돌아오겠습니다! 사이트는 현재 예정된 유지보수를 진행 중입니다.", "maintenancePageMessageDescription": "유지보수를 설명하는 상세 메시지", "maintenancePageTimeTitle": "예상 완료 시간(선택 사항)", + "privateMaintenanceScreenTitle": "프라이빗 플레이스홀더 화면", + "privateMaintenanceScreenMessage": "이 도메인은 개인 리소스에서 사용 중입니다. Pangolin 클라이언트를 사용하여 이 리소스에 액세스하세요.", "maintenanceTime": "예: 2시간, 11월 1일 오후 5시", "maintenanceEstimatedTimeDescription": "유지보수가 완료될 것으로 예상되는 시간", "editDomain": "도메인 수정", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "HTTP 대상지 추가", "httpDestEditDescription": "이 HTTP 이벤트 스트리밍 대상지의 구성을 업데이트하세요.", "httpDestAddDescription": "조직의 이벤트 수신을 위한 새로운 HTTP 엔드포인트를 구성하세요.", + "S3DestEditTitle": "대상지 수정", + "S3DestAddTitle": "S3 대상지 추가", + "S3DestEditDescription": "이 S3 이벤트 스트리밍 대상지의 구성을 업데이트하세요.", + "S3DestAddDescription": "조직의 이벤트를 받기 위한 새로운 S3 엔드포인트를 구성하세요.", + "datadogDestEditTitle": "대상지 수정", + "datadogDestAddTitle": "Datadog 대상지 추가", + "datadogDestEditDescription": "이 Datadog 이벤트 스트리밍 대상지의 구성을 업데이트하세요.", + "datadogDestAddDescription": "조직의 이벤트를 받기 위한 새로운 Datadog 엔드포인트를 구성하세요.", "httpDestTabSettings": "설정", "httpDestTabHeaders": "헤더", "httpDestTabBody": "본문", @@ -2882,7 +3092,7 @@ "httpDestFormatJsonArrayTitle": "JSON 배열", "httpDestFormatJsonArrayDescription": "각 배치마다 요청 하나씩, 본문은 JSON 배열입니다. 대부분의 일반 웹훅 및 Datadog과 호환됩니다.", "httpDestFormatNdjsonTitle": "NDJSON", - "httpDestFormatNdjsonDescription": "각 배치마다 요청 하나씩, 본문은 줄 구분 JSON — 한 라인에 하나의 객체가 있으며 외부 배열이 없습니다. Splunk HEC, Elastic / OpenSearch, Grafana Loki에 필요합니다.", + "httpDestFormatNdjsonDescription": "각 배치마다 요청 하나씩, 본문은 줄 구분 JSON - 한 라인에 하나의 객체가 있으며 외부 배열이 없습니다. Splunk HEC, Elastic / OpenSearch, Grafana Loki에 필요합니다.", "httpDestFormatSingleTitle": "각 요청 당 하나의 이벤트", "httpDestFormatSingleDescription": "각 개별 이벤트에 대해 별도의 HTTP POST를 전송합니다. 배치를 처리할 수 없는 엔드포인트에만 사용하세요.", "httpDestLogTypesTitle": "로그 유형", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "대상지가 성공적으로 생성되었습니다", "httpDestUpdateFailed": "대상지를 업데이트하는 데 실패했습니다", "httpDestCreateFailed": "대상지를 생성하는 데 실패했습니다", + "followRedirects": "리디렉션 따라가기", + "followRedirectsDescription": "요청에 대해 HTTP 리디렉션을 자동으로 따라갑니다.", + "alertingErrorWebhookUrl": "웹훅의 유효한 URL을 입력하세요.", + "healthCheckStrategyHttp": "연결성을 확인하고 HTTP 응답 상태를 확인합니다.", + "healthCheckStrategyTcp": "응답을 검사하지 않고 TCP 연결성만 확인합니다.", + "healthCheckStrategySnmp": "네트워크 장비 및 인프라의 상태를 확인하기 위해 SNMP get 요청을 보냅니다.", + "healthCheckStrategyIcmp": "ICMP 에코 요청(핑)을 사용하여 리소스에 대한 접근 가능성을 확인합니다.", + "healthCheckTabStrategy": "전략", + "healthCheckTabConnection": "연결", + "healthCheckTabAdvanced": "고급", + "healthCheckStrategyNotAvailable": "이 전략은 사용할 수 없습니다. 기능을 활성화하려면 영업팀에 문의하세요.", + "uptime30d": "업타임 (30일)", "idpAddActionCreateNew": "새로운 아이덴티티 공급자 생성", "idpAddActionImportFromOrg": "다른 조직에서 가져오기", "idpImportDialogTitle": "아이덴티티 공급자 가져오기", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "이 조직에서 이것은 되돌릴 수 없습니다.", "idpUnassociatedDescription": "아이덴티티 공급자가 이 조직에서 성공적으로 연관 해제되었습니다", "idpUnassociateMenu": "연관 해제", - "idpDeleteAllOrgsMenu": "삭제" + "idpDeleteAllOrgsMenu": "삭제", + "publicIpEndpoint": "엔드포인트", + "lastTriggeredAt": "마지막 트리거", + "reject": "거부" } diff --git a/messages/nb-NO.json b/messages/nb-NO.json index ab9334ee3..4cf5159d8 100644 --- a/messages/nb-NO.json +++ b/messages/nb-NO.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "Kontakt salgsavdelingen for å aktivere denne funksjonen.", + "contactSalesBookDemo": "Bestill en demo", + "contactSalesOr": "eller", + "contactSalesContactUs": "kontakt oss", "setupCreate": "Opprett organisasjonen, nettstedet og ressursene", "headerAuthCompatibilityInfo": "Aktiver dette for å tvinge frem en 401 Uautorisert-respons når en autentiseringstoken mangler. Dette kreves for nettlesere eller spesifikke HTTP-biblioteker som ikke sender legitimasjon uten en serverutfordring.", "headerAuthCompatibility": "Utvidet kompatibilitet", @@ -19,6 +23,14 @@ "componentsInvalidKey": "Ugyldig eller utgått lisensnøkkel oppdaget. Følg lisensvilkårene for å fortsette å kunne bruke alle funksjonene.", "dismiss": "Avvis", "subscriptionViolationMessage": "Du er utenfor grensen for gjeldende plan. Rett problemet ved å fjerne nettsteder, brukere eller andre ressurser for å bli innenfor planen din.", + "trialBannerMessage": "Din prøveperiode utløper om {countdown}. Oppgrader for å beholde tilgangen.", + "trialBannerExpired": "Prøveperioden din har utløpt. Oppgrader nå for å gjenopprette tilgangen.", + "trialActive": "Gratis prøveversjon aktiv", + "trialExpired": "Prøveperioden er utløpt", + "trialHasEnded": "Din prøveperiode har avsluttet.", + "trialDaysRemaining": "{count, plural, one {# dag igjen} other {# dager igjen}}", + "trialDaysLeftShort": "{days}d igjen av prøveperioden", + "trialGoToBilling": "Gå til faktureringssiden", "subscriptionViolationViewBilling": "Vis fakturering", "componentsLicenseViolation": "Lisens Brudd: Denne serveren bruker {usedSites} områder som overskrider den lisensierte grenser av {maxSites} områder. Følg lisensvilkårene for å fortsette å kunne bruke alle funksjonene.", "componentsSupporterMessage": "Takk for at du støtter Pangolin som en {tier}!", @@ -267,8 +279,11 @@ "orgMissing": "Organisasjons-ID Mangler", "orgMissingMessage": "Kan ikke regenerere invitasjon uten en organisasjons-ID.", "accessUsersManage": "Administrer brukere", + "accessUserManage": "Administrer brukere", "accessUsersDescription": "Inviter og behandle brukere med tilgang til denne organisasjonen", "accessUsersSearch": "Søk etter brukere...", + "accessUsersRoleFilterCount": "{count, plural, one {# rolle} other {# roller}}", + "accessUsersRoleFilterClear": "Fjern rollesøkefiltre", "accessUserCreate": "Opprett bruker", "accessUserRemove": "Fjern bruker", "username": "Brukernavn", @@ -1257,6 +1272,7 @@ "actionViewLogs": "Vis logger", "noneSelected": "Ingen valgt", "orgNotFound2": "Ingen organisasjoner funnet.", + "search": "Søk…", "searchPlaceholder": "Søk...", "emptySearchOptions": "Ingen valg funnet", "create": "Opprett", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "Administrer", "sidebarLogAndAnalytics": "Logg og analyser", "sidebarBluePrints": "Tegninger", + "sidebarAlerting": "Varsling", + "sidebarHealthChecks": "Helsekontroller", "sidebarOrganization": "Organisasjon", "sidebarManagement": "Administrasjon", "sidebarBillingAndLicenses": "Fakturering & lisenser", "sidebarLogsAnalytics": "Analyser", + "alertingTitle": "Varsling", + "alertingDescription": "Definer kilder, triggere og handlinger for varsler", + "alertingRules": "Varslingsregler", + "alertingSearchRules": "Søk i regler…", + "alertingAddRule": "Opprett regel", + "alertingColumnSource": "Kilde", + "alertingColumnTrigger": "Utløser", + "alertingColumnActions": "Handlinger", + "alertingColumnEnabled": "Aktivert", + "alertingDeleteQuestion": "Vennligst bekreft at du vil slette denne varslingsregelen.", + "alertingDeleteRule": "Slett varslingsregel", + "alertingRuleDeleted": "Varslingsregel slettet", + "alertingRuleSaved": "Varslingsregel lagret", + "alertingRuleSavedCreatedDescription": "Din nye varslingsregel ble opprettet. Du kan fortsette å redigere den på denne siden.", + "alertingRuleSavedUpdatedDescription": "Endringene dine i denne varslingsregelen ble lagret.", + "alertingEditRule": "Rediger varslingsregel", + "alertingCreateRule": "Opprett varslingsregel", + "alertingRuleCredenzaDescription": "Velg hva som skal overvåkes, når det skal varsles, og hvordan du vil bli informert", + "alertingRuleNamePlaceholder": "Produksjonsside nede", + "alertingRuleEnabled": "Regel aktivert", + "alertingSectionSource": "Kilde", + "alertingSourceType": "Kildetype", + "alertingSourceSite": "Område", + "alertingSourceHealthCheck": "Helsekontroll", + "alertingPickSites": "Områder", + "alertingPickHealthChecks": "Helsekontroller", + "alertingPickResources": "Ressurser", + "alertingAllSites": "Alle områder", + "alertingAllSitesDescription": "Varsler for alle områder", + "alertingSpecificSites": "Spesifikke områder", + "alertingSpecificSitesDescription": "Velg spesifikke områder for overvåking", + "alertingAllHealthChecks": "Alle helsekontroller", + "alertingAllHealthChecksDescription": "Varsler for alle helsekontroller", + "alertingSpecificHealthChecks": "Spesifikke helsekontroller", + "alertingSpecificHealthChecksDescription": "Velg spesifikke helsekontroller for overvåking", + "alertingAllResources": "Alle ressurser", + "alertingAllResourcesDescription": "Varsler for alle ressurser", + "alertingSpecificResources": "Spesifikke ressurser", + "alertingSpecificResourcesDescription": "Velg spesifikke ressurser for overvåking", + "alertingSelectResources": "Velg ressurser…", + "alertingResourcesSelected": "{count} ressurser valgt", + "alertingResourcesEmpty": "No resources with targets in the first 10 results.", + "alertingSectionTrigger": "Utløser", + "alertingTrigger": "Når skal det varsles", + "alertingTriggerSiteOnline": "Nettsted er online", + "alertingTriggerSiteOffline": "Nettsted er offline", + "alertingTriggerSiteToggle": "Endringer i nettstedstatus", + "alertingTriggerHcHealthy": "Helsekontroll sunn", + "alertingTriggerHcUnhealthy": "Helsekontroll usunn", + "alertingTriggerHcToggle": "Endringer i helsekontrollstatus", + "alertingTriggerResourceHealthy": "Ressurs sunn", + "alertingTriggerResourceUnhealthy": "Ressurs usunn", + "alertingSearchHealthChecks": "Søk i helsekontroller…", + "alertingHealthChecksEmpty": "Ingen tilgjengelige helsekontroller.", + "alertingTriggerResourceToggle": "Endringer i ressursstatus", + "alertingSourceResource": "Ressurs", + "alertingSectionActions": "Handlinger", + "alertingAddAction": "Legg til handling", + "alertingActionNotify": "E-post", + "alertingActionNotifyDescription": "Send e-postvarsler til brukere eller roller", + "alertingActionWebhook": "Webhook", + "alertingActionWebhookDescription": "Send en HTTP-forespørsel til et tilpasset endepunkt", + "alertingExternalIntegration": "Ekstern integrasjon", + "alertingExternalPagerDutyDescription": "Send varsler til PagerDuty for hendelseshåndtering", + "alertingExternalOpsgenieDescription": "Rute varsler til Opsgenie for vakt håndtering", + "alertingExternalServiceNowDescription": "Opprett ServiceNow hendelser fra varslingseventer", + "alertingExternalIncidentIoDescription": "Utløs Incident.io arbeidsflyter fra varsels begivenheter", + "alertingActionType": "Handlings type", + "alertingNotifyUsers": "Brukere", + "alertingNotifyRoles": "Roller", + "alertingNotifyEmails": "E-postadresser", + "alertingEmailPlaceholder": "Legg til e-post og trykk Enter", + "alertingWebhookMethod": "HTTP-metode", + "alertingWebhookSecret": "Signeringshemmelig (valgfritt)", + "alertingWebhookSecretPlaceholder": "HMAC-hemmelig", + "alertingWebhookHeaders": "Overskrifter", + "alertingAddHeader": "Legg til header", + "alertingSelectSites": "Velg områder…", + "alertingSitesSelected": "{count} områder valgt", + "alertingSelectHealthChecks": "Velg helsekontroller…", + "alertingHealthChecksSelected": "{count} helsekontroller valgt", + "alertingNoHealthChecks": "Ingen mål med helsekontroller aktivert", + "alertingHealthCheckStub": "Valg av helsekontrollkilde er ikke sluttført ennå - du kan fortsatt konfigurere triggere og handlinger.", + "alertingSelectUsers": "Velg brukere…", + "alertingUsersSelected": "{count} brukere valgt", + "alertingSelectRoles": "Velg roller…", + "alertingRolesSelected": "{count} roller valgt", + "alertingSummarySites": "Områder ({count})", + "alertingSummaryAllSites": "Alle områder", + "alertingSummaryHealthChecks": "Helsekontroller ({count})", + "alertingSummaryAllHealthChecks": "Alle helsekoner", + "alertingSummaryResources": "Ressurser ({count})", + "alertingSummaryAllResources": "Alle ressurser", + "alertingErrorNameRequired": "Skriv inn et navn", + "alertingErrorActionsMin": "Legg til minst én handling", + "alertingErrorPickSites": "Velg minst ett område", + "alertingErrorPickHealthChecks": "Velg minst én helsekontroll", + "alertingErrorPickResources": "Velg minst én ressurs", + "alertingErrorTriggerSite": "Velg en triggetjeneste for nettsted", + "alertingErrorTriggerHealth": "Velg en triggetjeneste for helsekontroll", + "alertingErrorTriggerResource": "Velg en triggetjeneste for ressurs", + "alertingErrorNotifyRecipients": "Velg brukere, roller, eller minst én e-post", + "alertingConfigureSource": "Konfigurer kilde", + "alertingConfigureTrigger": "Konfigurer trigger", + "alertingConfigureActions": "Konfigurer handlinger", + "alertingBackToRules": "Tilbake til regler", + "alertingRuleCooldown": "Nedkjøling (sekunder)", + "alertingRuleCooldownDescription": "Minimum tid mellom gjentatte varsler for samme regel. Sett til 0 for å skyte hver gang.", + "alertingDraftBadge": "Utkast - lagre for å lagre denne regelen", + "alertingSidebarHint": "Klikk på et steg på lerretet for å redigere det her.", + "alertingGraphCanvasTitle": "Regel Flyt", + "alertingGraphCanvasDescription": "Visuell oversikt over kilde, trigger og handlinger. Velg en node for å redigere den i panelet.", + "alertingNodeNotConfigured": "Ikke konfigurert ennå", + "alertingNodeActionsCount": "{count, plural, one {# handling} other {# handlinger}}", + "alertingNodeRoleSource": "Kilde", + "alertingNodeRoleTrigger": "Utløser", + "alertingNodeRoleAction": "Handling", + "alertingTabRules": "Varslingsregler", + "alertingTabHealthChecks": "Helsekontroller", + "alertingRulesBannerTitle": "Bli varslet", + "alertingRulesBannerDescription": "Hver regel binder sammen hva som skal overvåkes (et område, helsekontroll eller ressurs), når det skal varsles (for eksempel offline eller usunn), og hvordan varsle teamet ditt via e-post, webhooks eller integrasjoner. Bruk denne listen for å opprette, aktivere og administrere disse reglene.", + "alertingHealthChecksBannerTitle": "Overvåk helse & ressurser", + "alertingHealthChecksBannerDescription": "Helsekontroller er HTTP- eller TCP-monitorer du definerer én gang. Du kan deretter bruke dem som kilder i varslingsregler slik at du blir varslet når et mål blir sunt eller usunt. Helsekontroller på ressurser vises også her.", + "standaloneHcTableTitle": "Helsekontroller", + "standaloneHcSearchPlaceholder": "Søk i helsekontroller…", + "standaloneHcAddButton": "Opprett helsekontroll", + "standaloneHcCreateTitle": "Opprett helsekontroll", + "standaloneHcEditTitle": "Rediger helsekontroll", + "standaloneHcDescription": "Konfigurer en HTTP- eller TCP-helsekontroll for bruk i varslingsregler.", + "standaloneHcNameLabel": "Navn", + "standaloneHcNamePlaceholder": "Min HTTP-monitor", + "standaloneHcDeleteTitle": "Slett helsekontroll", + "standaloneHcDeleteQuestion": "Vennligst bekreft at du vil slette denne helsekontrollen.", + "standaloneHcDeleted": "Helsekontroll slettet", + "standaloneHcSaved": "Helsekontroll lagret", + "standaloneHcColumnHealth": "Helse", + "standaloneHcColumnMode": "Modus", + "standaloneHcColumnTarget": "Mål", + "standaloneHcHealthStateHealthy": "Sunn", + "standaloneHcHealthStateUnhealthy": "Usunn", + "standaloneHcHealthStateUnknown": "Ukjent", + "standaloneHcFilterAnySite": "Alle områder", + "standaloneHcFilterAnyResource": "Alle ressurser", + "standaloneHcFilterMode": "Modus", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "Ping", + "standaloneHcFilterHealth": "Helse", + "standaloneHcFilterEnabled": "Aktivert", + "standaloneHcFilterEnabledOn": "Aktivert", + "standaloneHcFilterEnabledOff": "Deaktivert", + "standaloneHcFilterSiteIdFallback": "Område {id}", + "standaloneHcFilterResourceIdFallback": "Ressurs {id}", "blueprints": "Tegninger", "blueprintsDescription": "Bruk deklarative konfigurasjoner og vis tidligere kjøringer", "blueprintAdd": "Legg til blåkopi", @@ -1763,6 +1935,15 @@ "healthCheckIntervalMin": "Sjekkeintervallet må være minst 5 sekunder", "healthCheckTimeoutMin": "Timeout må være minst 1 sekund", "healthCheckRetryMin": "Forsøk på nytt må være minst 1", + "healthCheckMode": "Sjekk modus", + "healthCheckStrategy": "Strategi", + "healthCheckModeDescription": "TCP-modus verifiserer kun tilkobling. HTTP-modus validerer HTTP-responsen.", + "healthyThreshold": "Sunnhets terskel", + "healthyThresholdDescription": "Suksesser på rad som kreves før man markerer som sunn.", + "unhealthyThreshold": "Usunn terskel", + "unhealthyThresholdDescription": "Feil på rad som kreves før man markerer som usunn.", + "healthCheckHealthyThresholdMin": "Sunnhet terskel må være minst 1", + "healthCheckUnhealthyThresholdMin": "Usunn terskel må være minst 1", "httpMethod": "HTTP-metode", "selectHttpMethod": "Velg HTTP-metode", "domainPickerSubdomainLabel": "Underdomene", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "Port", "editInternalResourceDialogModeHost": "Vert", "editInternalResourceDialogModeCidr": "CIDR", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "Skjema", + "editInternalResourceDialogEnableSsl": "Aktiver SSL", + "editInternalResourceDialogEnableSslDescription": "Aktiver SSL/TLS-kryptering for sikre HTTPS-tilkoblinger til destinasjonen.", "editInternalResourceDialogDestination": "Destinasjon", "editInternalResourceDialogDestinationHostDescription": "IP-adressen eller vertsnavnet til ressursen på nettstedets nettverk.", "editInternalResourceDialogDestinationIPDescription": "IP eller vertsnavn til ressursen på nettstedets nettverk.", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "Navn", "createInternalResourceDialogSite": "Område", "selectSite": "Velg område...", + "multiSitesSelectorSitesCount": "{count, plural, one {# sted} other {# steder}}", "noSitesFound": "Ingen områder funnet.", "createInternalResourceDialogProtocol": "Protokoll", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "Port", "createInternalResourceDialogModeHost": "Vert", "createInternalResourceDialogModeCidr": "CIDR", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "Skjema", + "createInternalResourceDialogScheme": "Skjema", + "createInternalResourceDialogEnableSsl": "Aktiver SSL", + "createInternalResourceDialogEnableSslDescription": "Aktiver SSL/TLS-kryptering for sikre HTTPS-tilkoblinger til destinasjonen.", "createInternalResourceDialogDestination": "Destinasjon", "createInternalResourceDialogDestinationHostDescription": "IP-adressen eller vertsnavnet til ressursen på nettstedets nettverk.", "createInternalResourceDialogDestinationCidrDescription": "CIDR-rekkevidden til ressursen på nettstedets nettverk.", "createInternalResourceDialogAlias": "Alias", "createInternalResourceDialogAliasDescription": "Et valgfritt internt DNS-alias for denne ressursen.", + "internalResourceDownstreamSchemeRequired": "Skjema er påkrevd for HTTP-ressurser", + "internalResourceHttpPortRequired": "Destinasjonsport er nødvendig for HTTP-ressurser", "siteConfiguration": "Konfigurasjon", "siteAcceptClientConnections": "Godta klientforbindelser", "siteAcceptClientConnectionsDescription": "Tillat brukere og klienter å få tilgang til ressurser på denne siden. Dette kan endres senere.", @@ -2429,6 +2624,7 @@ "validPassword": "Gyldig passord", "validEmail": "Valid email", "validSSO": "Valid SSO", + "connectedClient": "Tilkoblet klient", "resourceBlocked": "Ressurs blokkert", "droppedByRule": "Legg i regelen", "noSessions": "Ingen økter", @@ -2668,6 +2864,10 @@ "editInternalResourceDialogDestinationLabel": "Destinasjon", "editInternalResourceDialogDestinationDescription": "Spesifiser destinasjonsadressen for den interne ressursen. Dette kan være et vertsnavn, IP-adresse eller CIDR-sjikt avhengig av valgt modus. Valgfrie oppsett av intern DNS-alias for enklere identifikasjon.", "editInternalResourceDialogPortRestrictionsDescription": "Begrens tilgang til spesifikke TCP/UDP-porter eller tillate/blokkere alle porter.", + "createInternalResourceDialogHttpConfiguration": "HTTP-konfigurasjon", + "createInternalResourceDialogHttpConfigurationDescription": "Velg domenet klienter vil bruke for å nå denne ressursen via HTTP eller HTTPS.", + "editInternalResourceDialogHttpConfiguration": "HTTP-konfigurasjon", + "editInternalResourceDialogHttpConfigurationDescription": "Velg domenet klienter vil bruke for å nå denne ressursen via HTTP eller HTTPS.", "editInternalResourceDialogTcp": "TCP", "editInternalResourceDialogUdp": "UDP", "editInternalResourceDialogIcmp": "ICMP", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "Vi kommer snart tilbake! Vårt nettsted gjennomgår for øyeblikket planlagt vedlikehold.", "maintenancePageMessageDescription": "Detaljert beskjed som forklarer vedlikeholdet", "maintenancePageTimeTitle": "Estimert ferdigstillelsestid (Valgfritt)", + "privateMaintenanceScreenTitle": "Privat plassholder skjerm", + "privateMaintenanceScreenMessage": "Dette domenet brukes på en privatressurs. Koble til ved å bruke Pangolin-klienten for å få tilgang til denne ressursen.", "maintenanceTime": "f.eks. 2 timer, 1. november kl. 17:00", "maintenanceEstimatedTimeDescription": "Når du forventer at vedlikeholdet er ferdigstilt", "editDomain": "Rediger domene", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "Legg til HTTP-destinasjon", "httpDestEditDescription": "Oppdater konfigurasjonen for denne HTTP-hendelsesstrømmedestinasjonen.", "httpDestAddDescription": "Konfigurer et nytt HTTP endepunkt for å motta organisasjonens hendelser.", + "S3DestEditTitle": "Rediger destinasjon", + "S3DestAddTitle": "Legg til S3 destinasjon", + "S3DestEditDescription": "Oppdatere konfigurasjonen for denne S3-hendelsesstrømmingsdestinasjonen.", + "S3DestAddDescription": "Konfigurer et nytt S3-endepunkt for å motta organisasjonens hendelser.", + "datadogDestEditTitle": "Rediger destinasjon", + "datadogDestAddTitle": "Legg til Datadog destinasjon", + "datadogDestEditDescription": "Oppdatere konfigurasjonen for denne Datadog-hendelsesstrømmingsdestinasjonen.", + "datadogDestAddDescription": "Konfigurer et nytt Datadog-endepunkt for å motta organisasjonens hendelser.", "httpDestTabSettings": "Innstillinger", "httpDestTabHeaders": "Overskrifter", "httpDestTabBody": "Innhold", @@ -2882,7 +3092,7 @@ "httpDestFormatJsonArrayTitle": "JSON liste", "httpDestFormatJsonArrayDescription": "Én forespørsel per batch, innholdet er en JSON-liste. Kompatibel med de mest generiske webhooks og Datadog.", "httpDestFormatNdjsonTitle": "NDJSON", - "httpDestFormatNdjsonDescription": "Én forespørsel per sats, innholdet er nytt avgrenset JSON — et objekt per linje, ingen ytterarray. Kreves av Splunk HEC, Elastisk/OpenSearch, og Grafana Loki.", + "httpDestFormatNdjsonDescription": "Én forespørsel per sats, innholdet er nytt avgrenset JSON - et objekt per linje, ingen ytterarray. Kreves av Splunk HEC, Elastisk/OpenSearch, og Grafana Loki.", "httpDestFormatSingleTitle": "En hendelse per forespørsel", "httpDestFormatSingleDescription": "Sender en separat HTTP POST for hver enkelt hendelse. Bruk bare for endepunkter som ikke kan håndtere batcher.", "httpDestLogTypesTitle": "Logg typer", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "Målet er opprettet", "httpDestUpdateFailed": "Kunne ikke oppdatere destinasjon", "httpDestCreateFailed": "Kan ikke opprette mål", + "followRedirects": "Følg videresendinger", + "followRedirectsDescription": "Følg automatisk HTTP-videresendinger for forespørsler.", + "alertingErrorWebhookUrl": "Vennligst skriv inn en gyldig URL for webhooken.", + "healthCheckStrategyHttp": "Validerer tilkobling og sjekker HTTP-responsstatus.", + "healthCheckStrategyTcp": "Bekrefter kun TCP-tilkobling, uten å inspisere responsen.", + "healthCheckStrategySnmp": "Utfører en SNMP get-forespørsel for å sjekke helsen til nettverksenheter og infrastruktur.", + "healthCheckStrategyIcmp": "Bruker ICMP ekko forespørsler (ping) for å sjekke om en ressurs er tilgjengelig og responsiv.", + "healthCheckTabStrategy": "Strategi", + "healthCheckTabConnection": "Tilkobling", + "healthCheckTabAdvanced": "Avansert", + "healthCheckStrategyNotAvailable": "Denne strategien er ikke tilgjengelig. Vennligst kontakt salgsavdelingen for å aktivere denne funksjonen.", + "uptime30d": "Oppetid (30d)", "idpAddActionCreateNew": "Opprett ny identitetsleverandør", "idpAddActionImportFromOrg": "Importer fra en annen organisasjon", "idpImportDialogTitle": "Importer identitetsleverandør", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "Dette kan ikke angres for denne organisasjonen.", "idpUnassociatedDescription": "Identitetsleverandør er vellykket frakoblet fra denne organisasjonen", "idpUnassociateMenu": "Frakoble", - "idpDeleteAllOrgsMenu": "Slett" + "idpDeleteAllOrgsMenu": "Slett", + "publicIpEndpoint": "Endepunkt", + "lastTriggeredAt": "Siste utløste", + "reject": "Avvis" } diff --git a/messages/nl-NL.json b/messages/nl-NL.json index 403113ff3..855ae603d 100644 --- a/messages/nl-NL.json +++ b/messages/nl-NL.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "Neem contact op met de verkoopafdeling om deze functie in te schakelen.", + "contactSalesBookDemo": "Boek een demo", + "contactSalesOr": "of", + "contactSalesContactUs": "neem contact met ons op", "setupCreate": "Maak de organisatie, site en bronnen aan", "headerAuthCompatibilityInfo": "Schakel dit in om een 401 Niet Geautoriseerd antwoord af te dwingen wanneer een authenticatietoken ontbreekt. Dit is vereist voor browsers of specifieke HTTP-bibliotheken die geen referenties verzenden zonder een serveruitdaging.", "headerAuthCompatibility": "Uitgebreide compatibiliteit", @@ -19,6 +23,14 @@ "componentsInvalidKey": "Ongeldige of verlopen licentiesleutels gedetecteerd. Volg de licentievoorwaarden om alle functies te blijven gebruiken.", "dismiss": "Uitschakelen", "subscriptionViolationMessage": "U overschrijdt uw huidige abonnement. Corrigeer het probleem door sites, gebruikers of andere bronnen te verwijderen om binnen uw plan te blijven.", + "trialBannerMessage": "Uw proefversie verloopt over {countdown}. Upgrade om toegang te behouden.", + "trialBannerExpired": "Uw proefperiode is verlopen. Upgrade nu om toegang te herstellen.", + "trialActive": "Gratis proefversie actief", + "trialExpired": "Proefversie verlopen", + "trialHasEnded": "Uw proefperiode is geëindigd.", + "trialDaysRemaining": "{count, plural, one {# dag resterend} other {# dagen resterend}}", + "trialDaysLeftShort": "{days}d over in proefversie", + "trialGoToBilling": "Ga naar factureringspagina", "subscriptionViolationViewBilling": "Facturering bekijken", "componentsLicenseViolation": "Licentie overtreding: Deze server gebruikt {usedSites} sites die de gelicentieerde limiet van {maxSites} sites overschrijden. Volg de licentievoorwaarden om door te gaan met het gebruik van alle functies.", "componentsSupporterMessage": "Bedankt voor het ondersteunen van Pangolin als {tier}!", @@ -267,8 +279,11 @@ "orgMissing": "Organisatie-ID ontbreekt", "orgMissingMessage": "Niet in staat om de uitnodiging te regenereren zonder organisatie-ID.", "accessUsersManage": "Gebruikers beheren", + "accessUserManage": "Beheer gebruiker", "accessUsersDescription": "Nodig uit en beheer gebruikers met toegang tot deze organisatie", "accessUsersSearch": "Gebruikers zoeken...", + "accessUsersRoleFilterCount": "{count, plural, one {# rol} other {# rollen}}", + "accessUsersRoleFilterClear": "Rolfilters wissen", "accessUserCreate": "Gebruiker aanmaken", "accessUserRemove": "Gebruiker verwijderen", "username": "Gebruikersnaam", @@ -1257,6 +1272,7 @@ "actionViewLogs": "Logboeken bekijken", "noneSelected": "Niet geselecteerd", "orgNotFound2": "Geen organisaties gevonden.", + "search": "Zoeken…", "searchPlaceholder": "Zoeken...", "emptySearchOptions": "Geen opties gevonden", "create": "Aanmaken", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "Beheren", "sidebarLogAndAnalytics": "Log & Analytics", "sidebarBluePrints": "Blauwdrukken", + "sidebarAlerting": "Waarschuwingen", + "sidebarHealthChecks": "Gezondheidscontroles", "sidebarOrganization": "Organisatie", "sidebarManagement": "Beheer", "sidebarBillingAndLicenses": "Facturatie & Licenties", "sidebarLogsAnalytics": "Analyses", + "alertingTitle": "Waarschuwingen", + "alertingDescription": "Definieer bronnen, triggers en acties voor meldingen", + "alertingRules": "Waarschuwingsregels", + "alertingSearchRules": "Zoek regels…", + "alertingAddRule": "Regel aanmaken", + "alertingColumnSource": "Bron", + "alertingColumnTrigger": "Trigger", + "alertingColumnActions": "Acties", + "alertingColumnEnabled": "Ingeschakeld", + "alertingDeleteQuestion": "Bevestig alstublieft dat u deze waarschuwingsregel wilt verwijderen.", + "alertingDeleteRule": "Verwijder waarschuwingsregel", + "alertingRuleDeleted": "Waarschuwingsregel verwijderd", + "alertingRuleSaved": "Waarschuwingsregel opgeslagen", + "alertingRuleSavedCreatedDescription": "Uw nieuwe waarschuwingsregel is aangemaakt. U kunt deze op deze pagina blijven bewerken.", + "alertingRuleSavedUpdatedDescription": "Uw wijzigingen in deze waarschuwingsregel zijn opgeslagen.", + "alertingEditRule": "Bewerk waarschuwingsregel", + "alertingCreateRule": "Waarschuwingsregel aanmaken", + "alertingRuleCredenzaDescription": "Kies wat te bekijken, wanneer het moet gebeuren en hoe te waarschuwen", + "alertingRuleNamePlaceholder": "Productiesite offline", + "alertingRuleEnabled": "Regel ingeschakeld", + "alertingSectionSource": "Bron", + "alertingSourceType": "Brontype", + "alertingSourceSite": "Site", + "alertingSourceHealthCheck": "Gezondheidscontrole", + "alertingPickSites": "Sites", + "alertingPickHealthChecks": "Gezondheidscontroles", + "alertingPickResources": "Bronnen", + "alertingAllSites": "Alle sites", + "alertingAllSitesDescription": "Waarschuwing voor elke site", + "alertingSpecificSites": "Specifieke sites", + "alertingSpecificSitesDescription": "Kies specifieke sites om in de gaten te houden", + "alertingAllHealthChecks": "Alle Gezondheidscontroles", + "alertingAllHealthChecksDescription": "Waarschuwing voor elke gezondheidscontrole", + "alertingSpecificHealthChecks": "Specifieke Gezondheidscontroles", + "alertingSpecificHealthChecksDescription": "Kies specifieke gezondheidscontroles om in de gaten te houden", + "alertingAllResources": "Alle bronnen", + "alertingAllResourcesDescription": "Waarschuwing voor elke bron", + "alertingSpecificResources": "Specifieke bronnen", + "alertingSpecificResourcesDescription": "Kies specifieke bronnen om in de gaten te houden", + "alertingSelectResources": "Selecteer bronnen…", + "alertingResourcesSelected": "{count} bronnen geselecteerd", + "alertingResourcesEmpty": "Geen bronnen met doelen in de eerste 10 resultaten.", + "alertingSectionTrigger": "Trigger", + "alertingTrigger": "Wanneer te waarschuwen", + "alertingTriggerSiteOnline": "Site online", + "alertingTriggerSiteOffline": "Site offline", + "alertingTriggerSiteToggle": "Site status wijzigt", + "alertingTriggerHcHealthy": "Gezondheidscontrole gezond", + "alertingTriggerHcUnhealthy": "Gezondheidscontrole ongezond", + "alertingTriggerHcToggle": "Gezondheidscontrole status verandert", + "alertingTriggerResourceHealthy": "Bron gezond", + "alertingTriggerResourceUnhealthy": "Bron ongezond", + "alertingSearchHealthChecks": "Zoek gezondheidscontroles…", + "alertingHealthChecksEmpty": "Geen gezondheidscontroles beschikbaar.", + "alertingTriggerResourceToggle": "Bronstatus wijzigt", + "alertingSourceResource": "Bron", + "alertingSectionActions": "Acties", + "alertingAddAction": "Actie toevoegen", + "alertingActionNotify": "E-mail", + "alertingActionNotifyDescription": "Stuur e-mailmeldingen naar gebruikers of rollen", + "alertingActionWebhook": "Webhook", + "alertingActionWebhookDescription": "Stuur een HTTP-verzoek naar een aangepast eindpunt", + "alertingExternalIntegration": "Externe integratie", + "alertingExternalPagerDutyDescription": "Stuur waarschuwingen naar PagerDuty voor incidentbeheer", + "alertingExternalOpsgenieDescription": "Routeer waarschuwingen naar Opsgenie voor wachtdienstbeheer", + "alertingExternalServiceNowDescription": "Maak ServiceNow-incidenten aan vanuit waarschuwingsgebeurtenissen", + "alertingExternalIncidentIoDescription": "Trigger Incident.io workflows van waarschuwingsgebeurtenissen", + "alertingActionType": "Actietype", + "alertingNotifyUsers": "Gebruikers", + "alertingNotifyRoles": "Rollen", + "alertingNotifyEmails": "E-mailadressen", + "alertingEmailPlaceholder": "Voeg e-mail toe en druk op Enter", + "alertingWebhookMethod": "HTTP-methode", + "alertingWebhookSecret": "Ondertekengeheim (optioneel)", + "alertingWebhookSecretPlaceholder": "HMAC-geheim", + "alertingWebhookHeaders": "Headers", + "alertingAddHeader": "Header toevoegen", + "alertingSelectSites": "Selecteer sites…", + "alertingSitesSelected": "{count} sites geselecteerd", + "alertingSelectHealthChecks": "Selecteer gezondheidscontroles…", + "alertingHealthChecksSelected": "{count} gezondheidscontroles geselecteerd", + "alertingNoHealthChecks": "Geen doelen met ingeschakelde gezondheidscontroles", + "alertingHealthCheckStub": "Gezondheidscontrole brondeselectie is nog niet gekoppeld - u kunt nog steeds triggers en acties configureren.", + "alertingSelectUsers": "Selecteer gebruikers…", + "alertingUsersSelected": "{count} gebruikers geselecteerd", + "alertingSelectRoles": "Selecteer rollen…", + "alertingRolesSelected": "{count} rollen geselecteerd", + "alertingSummarySites": "Sites ({count})", + "alertingSummaryAllSites": "Alle sites", + "alertingSummaryHealthChecks": "Gezondheidscontroles ({count})", + "alertingSummaryAllHealthChecks": "Alle gezondheidscontroles", + "alertingSummaryResources": "Bronnen ({count})", + "alertingSummaryAllResources": "Alle bronnen", + "alertingErrorNameRequired": "Voer een naam in", + "alertingErrorActionsMin": "Voeg minimaal één actie toe", + "alertingErrorPickSites": "Selecteer minimaal één site", + "alertingErrorPickHealthChecks": "Selecteer minimaal één gezondheidscontrole", + "alertingErrorPickResources": "Selecteer minimaal één bron", + "alertingErrorTriggerSite": "Kies een site-trigger", + "alertingErrorTriggerHealth": "Kies een gezondheidscontrole-trigger", + "alertingErrorTriggerResource": "Kies een bron-trigger", + "alertingErrorNotifyRecipients": "Kies gebruikers, rollen of ten minste één e-mail", + "alertingConfigureSource": "Bron configureren", + "alertingConfigureTrigger": "Trigger configureren", + "alertingConfigureActions": "Acties configureren", + "alertingBackToRules": "Terug naar regels", + "alertingRuleCooldown": "Aflkoelperiode (seconden)", + "alertingRuleCooldownDescription": "Minimale tijd tussen herhaalwaarschuwingen voor dezelfde regel. Zet op 0 om elke keer te laten vuren.", + "alertingDraftBadge": "Concept - opslaan om deze regel op te slaan", + "alertingSidebarHint": "Klik op een stap in het canvas om deze hier te bewerken.", + "alertingGraphCanvasTitle": "Regelstroom", + "alertingGraphCanvasDescription": "Visueel overzicht van bron, trigger en acties. Selecteer een node om deze in het paneel te bewerken.", + "alertingNodeNotConfigured": "Nog niet geconfigureerd", + "alertingNodeActionsCount": "{count, plural, one {# actie} other {# acties}}", + "alertingNodeRoleSource": "Bron", + "alertingNodeRoleTrigger": "Trigger", + "alertingNodeRoleAction": "Actie", + "alertingTabRules": "Waarschuwingsregels", + "alertingTabHealthChecks": "Gezondheidscontroles", + "alertingRulesBannerTitle": "Meldingen ontvangen", + "alertingRulesBannerDescription": "Elke regel koppelt wat te bekijken (een site, gezondheidscontrole of bron), wanneer te vuren (bijvoorbeeld offline of ongezond), en hoe uw team te waarschuwen via e-mail, webhooks of integraties. Gebruik deze lijst om die regels te maken, in te schakelen en te beheren.", + "alertingHealthChecksBannerTitle": "Gezondheid & bronnen bewaken", + "alertingHealthChecksBannerDescription": "Gezondheidscontroles zijn HTTP- of TCP-monitoren die u één keer definieert. U kunt ze vervolgens als bronnen in waarschuwingsregels gebruiken, zodat u meldingen krijgt wanneer een doelwit gezond of ongezond wordt. Gezondheidscontroles van bronnen verschijnen ook hier.", + "standaloneHcTableTitle": "Gezondheidscontroles", + "standaloneHcSearchPlaceholder": "Zoek gezondheidscontroles…", + "standaloneHcAddButton": "Gezondheidscontrole aanmaken", + "standaloneHcCreateTitle": "Gezondheidscontrole aanmaken", + "standaloneHcEditTitle": "Gezondheidscontrole bewerken", + "standaloneHcDescription": "Configureer een HTTP- of TCP-gezondheidscontrole voor gebruik in waarschuwingsregels.", + "standaloneHcNameLabel": "Naam", + "standaloneHcNamePlaceholder": "Mijn HTTP-monitor", + "standaloneHcDeleteTitle": "Gezondheidscontrole verwijderen", + "standaloneHcDeleteQuestion": "Bevestig alstublieft dat u deze gezondheidscontrole wilt verwijderen.", + "standaloneHcDeleted": "Gezondheidscontrole verwijderd", + "standaloneHcSaved": "Gezondheidscontrole opgeslagen", + "standaloneHcColumnHealth": "Gezondheid", + "standaloneHcColumnMode": "Modus", + "standaloneHcColumnTarget": "Doelwit", + "standaloneHcHealthStateHealthy": "Gezond", + "standaloneHcHealthStateUnhealthy": "Ongezond", + "standaloneHcHealthStateUnknown": "Onbekend", + "standaloneHcFilterAnySite": "Alle sites", + "standaloneHcFilterAnyResource": "Alle bronnen", + "standaloneHcFilterMode": "Modus", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "Ping", + "standaloneHcFilterHealth": "Gezondheid", + "standaloneHcFilterEnabled": "Ingeschakeld", + "standaloneHcFilterEnabledOn": "Ingeschakeld", + "standaloneHcFilterEnabledOff": "Uitgeschakeld", + "standaloneHcFilterSiteIdFallback": "Site {id}", + "standaloneHcFilterResourceIdFallback": "Bron {id}", "blueprints": "Blauwdrukken", "blueprintsDescription": "Gebruik declaratieve configuraties en bekijk vorige uitvoeringen.", "blueprintAdd": "Blauwdruk toevoegen", @@ -1763,6 +1935,15 @@ "healthCheckIntervalMin": "Controle interval moet minimaal 5 seconden zijn", "healthCheckTimeoutMin": "Timeout moet minimaal 1 seconde zijn", "healthCheckRetryMin": "Herhaal pogingen moet minimaal 1 zijn", + "healthCheckMode": "Controlemodus", + "healthCheckStrategy": "Strategie", + "healthCheckModeDescription": "TCP-modus verifieert alleen connectiviteit. HTTP-modus valideert de HTTP-respons.", + "healthyThreshold": "Gezonde drempel", + "healthyThresholdDescription": "Opeenvolgende successen vereist voordat gemarkeerd wordt als gezond.", + "unhealthyThreshold": "Ongezonde drempel", + "unhealthyThresholdDescription": "Opeenvolgende fouten vereist voordat gemarkeerd wordt als ongezond.", + "healthCheckHealthyThresholdMin": "Gezonde drempel moet minimaal 1 zijn", + "healthCheckUnhealthyThresholdMin": "Ongezonde drempel moet minimaal 1 zijn", "httpMethod": "HTTP-methode", "selectHttpMethod": "Selecteer HTTP-methode", "domainPickerSubdomainLabel": "Subdomein", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "Poort", "editInternalResourceDialogModeHost": "Hostnaam", "editInternalResourceDialogModeCidr": "CIDR", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "Schema", + "editInternalResourceDialogEnableSsl": "SSL inschakelen", + "editInternalResourceDialogEnableSslDescription": "Schakel SSL/TLS-encryptie in voor beveiligde HTTPS-verbindingen met de bestemming.", "editInternalResourceDialogDestination": "Bestemming", "editInternalResourceDialogDestinationHostDescription": "Het IP-adres of de hostnaam van de bron op het netwerk van de site.", "editInternalResourceDialogDestinationIPDescription": "Het IP of hostnaam adres van de bron op het netwerk van de site.", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "Naam", "createInternalResourceDialogSite": "Site", "selectSite": "Selecteer site...", + "multiSitesSelectorSitesCount": "{count, plural, one {# site} other {# sites}}", "noSitesFound": "Geen sites gevonden.", "createInternalResourceDialogProtocol": "Protocol", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "Poort", "createInternalResourceDialogModeHost": "Hostnaam", "createInternalResourceDialogModeCidr": "CIDR", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "Schema", + "createInternalResourceDialogScheme": "Schema", + "createInternalResourceDialogEnableSsl": "SSL inschakelen", + "createInternalResourceDialogEnableSslDescription": "Schakel SSL/TLS-encryptie in voor beveiligde HTTPS-verbindingen met de bestemming.", "createInternalResourceDialogDestination": "Bestemming", "createInternalResourceDialogDestinationHostDescription": "Het IP-adres of de hostnaam van de bron op het netwerk van de site.", "createInternalResourceDialogDestinationCidrDescription": "Het CIDR-bereik van het document op het netwerk van de site.", "createInternalResourceDialogAlias": "Alias", "createInternalResourceDialogAliasDescription": "Een optionele interne DNS-alias voor dit document.", + "internalResourceDownstreamSchemeRequired": "Schema is vereist voor HTTP-bronnen", + "internalResourceHttpPortRequired": "Bestemmingspoort is vereist voor HTTP-bronnen", "siteConfiguration": "Configuratie", "siteAcceptClientConnections": "Accepteer clientverbindingen", "siteAcceptClientConnectionsDescription": "Sta gebruikersapparaten en clients toegang toe tot bronnen op deze site. Dit kan later worden gewijzigd.", @@ -2119,7 +2314,7 @@ "selectDomainForOrgAuthPage": "Selecteer een domein voor de authenticatiepagina van de organisatie", "domainPickerProvidedDomain": "Opgegeven domein", "domainPickerFreeProvidedDomain": "Gratis verstrekt domein", - "domainPickerFreeDomainsPaidFeature": "Geleverde domeinen zijn een betaalde functie. Abonneer je om een domein bij je plan te krijgen — je hoeft er zelf geen mee te brengen.", + "domainPickerFreeDomainsPaidFeature": "Geleverde domeinen zijn een betaalde functie. Abonneer je om een domein bij je plan te krijgen - je hoeft er zelf geen mee te brengen.", "domainPickerVerified": "Geverifieerd", "domainPickerUnverified": "Ongeverifieerd", "domainPickerManual": "Handleiding", @@ -2429,6 +2624,7 @@ "validPassword": "Geldig wachtwoord", "validEmail": "Valid email", "validSSO": "Valid SSO", + "connectedClient": "Verbonden Client", "resourceBlocked": "Bron geblokkeerd", "droppedByRule": "Achtergelaten door regel", "noSessions": "Geen sessies", @@ -2668,6 +2864,10 @@ "editInternalResourceDialogDestinationLabel": "Bestemming", "editInternalResourceDialogDestinationDescription": "Specificeer het bestemmingsadres voor de interne bron. Dit kan een hostnaam, IP-adres of CIDR-bereik zijn, afhankelijk van de geselecteerde modus. Stel optioneel een interne DNS-alias in voor eenvoudigere identificatie.", "editInternalResourceDialogPortRestrictionsDescription": "Beperk toegang tot specifieke TCP/UDP-poorten of sta alle poorten toe/blokkeer.", + "createInternalResourceDialogHttpConfiguration": "HTTP-configuratie", + "createInternalResourceDialogHttpConfigurationDescription": "Kies het domein dat cliënten zullen gebruiken om deze bron via HTTP of HTTPS te bereiken.", + "editInternalResourceDialogHttpConfiguration": "HTTP-configuratie", + "editInternalResourceDialogHttpConfigurationDescription": "Kies het domein dat cliënten zullen gebruiken om deze bron via HTTP of HTTPS te bereiken.", "editInternalResourceDialogTcp": "TCP", "editInternalResourceDialogUdp": "UDP", "editInternalResourceDialogIcmp": "ICMP", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "We keren snel terug! Onze site ondergaat momenteel gepland onderhoud.", "maintenancePageMessageDescription": "Gedetailleerd bericht dat het onderhoud uitlegt", "maintenancePageTimeTitle": "Geschatte voltooiingstijd (optioneel)", + "privateMaintenanceScreenTitle": "Privéscherm maintenance screen", + "privateMaintenanceScreenMessage": "Dit domein wordt gebruikt op een privébron. Verbind met de Pangolin client om toegang te krijgen tot deze bron.", "maintenanceTime": "bijv. 2 uur, 1 nov om 17:00", "maintenanceEstimatedTimeDescription": "Wanneer u verwacht dat het onderhoud voltooid is", "editDomain": "Domein bewerken", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "Voeg HTTP bestemming toe", "httpDestEditDescription": "Werk de configuratie voor deze HTTP-event streaming bestemming bij.", "httpDestAddDescription": "Configureer een nieuw HTTP-eindpunt om de gebeurtenissen van uw organisatie te ontvangen.", + "S3DestEditTitle": "Bestemming bewerken", + "S3DestAddTitle": "S3-bestemming toevoegen", + "S3DestEditDescription": "Werk de configuratie bij voor deze S3-gebeurtenisstreamingbestemming.", + "S3DestAddDescription": "Configureer een nieuw S3-eindpunt om de gebeurtenissen van uw organisatie te ontvangen.", + "datadogDestEditTitle": "Bestemming bewerken", + "datadogDestAddTitle": "Datadog-bestemming toevoegen", + "datadogDestEditDescription": "Werk de configuratie bij voor deze Datadog-gebeurtenisstreamingbestemming.", + "datadogDestAddDescription": "Configureer een nieuw Datadog-eindpunt om de gebeurtenissen van uw organisatie te ontvangen.", "httpDestTabSettings": "Instellingen", "httpDestTabHeaders": "Kopteksten", "httpDestTabBody": "Lichaam", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "Bestemming succesvol aangemaakt", "httpDestUpdateFailed": "Bijwerken bestemming mislukt", "httpDestCreateFailed": "Aanmaken bestemming mislukt", + "followRedirects": "Volg omleidingen", + "followRedirectsDescription": "Volg automatisch HTTP-omleidingen voor verzoeken.", + "alertingErrorWebhookUrl": "Voer een geldige URL voor de webhook in.", + "healthCheckStrategyHttp": "Valideert connectiviteit en controleert de HTTP-responsstatus.", + "healthCheckStrategyTcp": "Verifieert alleen TCP-connectiviteit zonder de respons te inspecteren.", + "healthCheckStrategySnmp": "Maakt een SNMP-verzoek om de gezondheid van netwerkapparaten en infrastructuur te controleren.", + "healthCheckStrategyIcmp": "Gebruikt ICMP-verzoeken (pings) om te controleren of een bron bereikbaar en responsief is.", + "healthCheckTabStrategy": "Strategie", + "healthCheckTabConnection": "Verbinding", + "healthCheckTabAdvanced": "Geavanceerd", + "healthCheckStrategyNotAvailable": "Deze strategie is niet beschikbaar. Neem contact op met sales om deze functie in te schakelen.", + "uptime30d": "Beschikbaarheid (30d)", "idpAddActionCreateNew": "Nieuwe identiteitsprovider aanmaken", "idpAddActionImportFromOrg": "Importeer vanuit een andere organisatie", "idpImportDialogTitle": "Importeer Identiteitsprovider", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "Dit kan niet ongedaan worden gemaakt voor deze organisatie.", "idpUnassociatedDescription": "Identiteitsprovider succesvol losgekoppeld van deze organisatie", "idpUnassociateMenu": "Ontkoppelen", - "idpDeleteAllOrgsMenu": "Verwijderen" + "idpDeleteAllOrgsMenu": "Verwijderen", + "publicIpEndpoint": "Eindpunt", + "lastTriggeredAt": "Laatste Trigger", + "reject": "Afwijzen" } diff --git a/messages/pl-PL.json b/messages/pl-PL.json index d6a454120..1fc66fadb 100644 --- a/messages/pl-PL.json +++ b/messages/pl-PL.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "Skontaktuj się z działem sprzedaży, aby włączyć tę funkcję.", + "contactSalesBookDemo": "Umów się na demo", + "contactSalesOr": "lub", + "contactSalesContactUs": "skontaktuj się z nami", "setupCreate": "Utwórz organizację, witrynę i zasoby", "headerAuthCompatibilityInfo": "Włącz to, aby wymusić odpowiedź Unauthorized 401, gdy brakuje tokena uwierzytelniania. Jest to wymagane dla przeglądarek lub określonych bibliotek HTTP, które nie wysyłają poświadczeń bez wyzwania serwera.", "headerAuthCompatibility": "Rozszerzona kompatybilność", @@ -19,6 +23,14 @@ "componentsInvalidKey": "Wykryto nieprawidłowe lub wygasłe klucze licencyjne. Postępuj zgodnie z warunkami licencji, aby kontynuować korzystanie ze wszystkich funkcji.", "dismiss": "Odrzuć", "subscriptionViolationMessage": "Nie masz ograniczeń dla aktualnego planu. Popraw problem poprzez usunięcie stron, użytkowników lub innych zasobów, aby pozostać w swoim planie.", + "trialBannerMessage": "Twój okres próbny wygasa za {countdown}. Uaktualnij, aby zachować dostęp.", + "trialBannerExpired": "Twój okres próbny wygasł. Uaktualnij teraz, aby przywrócić dostęp.", + "trialActive": "Okres próbny aktywny", + "trialExpired": "Okres próbny wygasł", + "trialHasEnded": "Twój okres próbny dobiegł końca.", + "trialDaysRemaining": "{count, plural, one {# dzień pozostaje} few {# dni pozostają} many {# dni pozostaje} other {# dni pozostają}}", + "trialDaysLeftShort": "Pozostało {days}d próbny", + "trialGoToBilling": "Przejdź do strony rozliczeń", "subscriptionViolationViewBilling": "Zobacz rozliczenie", "componentsLicenseViolation": "Naruszenie licencji: Ten serwer używa stron {usedSites} , które przekraczają limit licencyjny stron {maxSites} . Postępuj zgodnie z warunkami licencji, aby kontynuować korzystanie ze wszystkich funkcji.", "componentsSupporterMessage": "Dziękujemy za wsparcie Pangolina jako {tier}!", @@ -267,8 +279,11 @@ "orgMissing": "Brak ID organizacji", "orgMissingMessage": "Nie można ponownie wygenerować zaproszenia bez ID organizacji.", "accessUsersManage": "Zarządzaj użytkownikami", + "accessUserManage": "Zarządzaj użytkownikiem", "accessUsersDescription": "Zaproś użytkowników z dostępem do tej organizacji i zarządzaj nimi", "accessUsersSearch": "Szukaj użytkowników...", + "accessUsersRoleFilterCount": "{count, plural, one {# rola} few {# role} many {# ról} other {# ról}}", + "accessUsersRoleFilterClear": "Wyczyść filtry ról", "accessUserCreate": "Utwórz użytkownika", "accessUserRemove": "Usuń użytkownika", "username": "Nazwa użytkownika", @@ -1257,6 +1272,7 @@ "actionViewLogs": "Zobacz dzienniki", "noneSelected": "Nie wybrano", "orgNotFound2": "Nie znaleziono organizacji.", + "search": "Szukaj…", "searchPlaceholder": "Szukaj...", "emptySearchOptions": "Nie znaleziono opcji", "create": "Utwórz", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "Zarządzaj", "sidebarLogAndAnalytics": "Dziennik & Analityka", "sidebarBluePrints": "Schematy", + "sidebarAlerting": "Alarmowanie", + "sidebarHealthChecks": "Kontrole zdrowia", "sidebarOrganization": "Organizacja", "sidebarManagement": "Zarządzanie", "sidebarBillingAndLicenses": "Płatność i licencje", "sidebarLogsAnalytics": "Analityka", + "alertingTitle": "Alarmowanie", + "alertingDescription": "Zdefiniuj źródła, ustawienia, i działania dla powiadomień", + "alertingRules": "Reguły alarmowe", + "alertingSearchRules": "Szukaj reguł…", + "alertingAddRule": "Utwórz Regułę", + "alertingColumnSource": "Źródło", + "alertingColumnTrigger": "Ustawienie", + "alertingColumnActions": "Akcje", + "alertingColumnEnabled": "Włączone", + "alertingDeleteQuestion": "Potwierdź, że chcesz usunąć tę regułę alarmową.", + "alertingDeleteRule": "Usuń regułę alarmową", + "alertingRuleDeleted": "Reguła alarmowa usunięta", + "alertingRuleSaved": "Reguła alarmowa zapisana", + "alertingRuleSavedCreatedDescription": "Nowa reguła alarmowa została utworzona. Możesz ją kontynuować edytować na tej stronie.", + "alertingRuleSavedUpdatedDescription": "Twoje zmiany w tej regule alarmowej zostały zapisane.", + "alertingEditRule": "Edytuj regułę alarmową", + "alertingCreateRule": "Utwórz regułę alarmową", + "alertingRuleCredenzaDescription": "Wybierz, co obserwować, kiedy uruchamiać i jak powiadamiać.", + "alertingRuleNamePlaceholder": "Strona produkcyjna w dół", + "alertingRuleEnabled": "Reguła włączona", + "alertingSectionSource": "Źródło", + "alertingSourceType": "Typ źródła", + "alertingSourceSite": "Witryna", + "alertingSourceHealthCheck": "Kontrola zdrowia", + "alertingPickSites": "Witryny", + "alertingPickHealthChecks": "Kontrole zdrowia", + "alertingPickResources": "Zasoby", + "alertingAllSites": "Wszystkie witryny", + "alertingAllSitesDescription": "Alarm uruchomiony dla dowolnej witryny", + "alertingSpecificSites": "Określone witryny", + "alertingSpecificSitesDescription": "Wybierz określone witryny do obserwacji", + "alertingAllHealthChecks": "Wszystkie Kontrole Zdrowia", + "alertingAllHealthChecksDescription": "Alarm uruchomiony dla dowolnej kontroli zdrowia", + "alertingSpecificHealthChecks": "Określone Kontrole Zdrowia", + "alertingSpecificHealthChecksDescription": "Wybierz określone kontrole zdrowia do obserwacji", + "alertingAllResources": "Wszystkie zasoby", + "alertingAllResourcesDescription": "Alarm uruchomiony dla dowolnego zasobu", + "alertingSpecificResources": "Określone Zasoby", + "alertingSpecificResourcesDescription": "Wybierz określone zasoby do obserwacji", + "alertingSelectResources": "Wybierz zasoby…", + "alertingResourcesSelected": "{count} zasobów wybrano", + "alertingResourcesEmpty": "Brak zasobów z celami w pierwszych 10 wynikach.", + "alertingSectionTrigger": "Ustawienie", + "alertingTrigger": "Kiedy alarmować", + "alertingTriggerSiteOnline": "Strona online", + "alertingTriggerSiteOffline": "Strona offline", + "alertingTriggerSiteToggle": "Status strony zmienia się", + "alertingTriggerHcHealthy": "Kontrola zdrowia zdrowa", + "alertingTriggerHcUnhealthy": "Kontrola zdrowia niezdrowa", + "alertingTriggerHcToggle": "Status kontroli zdrowia zmienia się", + "alertingTriggerResourceHealthy": "Zasób zdrowy", + "alertingTriggerResourceUnhealthy": "Zasób niezdrowy", + "alertingSearchHealthChecks": "Szukaj kontroli zdrowia…", + "alertingHealthChecksEmpty": "Brak dostępnych kontroli zdrowia.", + "alertingTriggerResourceToggle": "Zmiany statusu zasobu", + "alertingSourceResource": "Zasób", + "alertingSectionActions": "Akcje", + "alertingAddAction": "Dodaj Akcję", + "alertingActionNotify": "E-mail", + "alertingActionNotifyDescription": "Wyślij powiadomienia e-mail do użytkowników lub ról", + "alertingActionWebhook": "Webhook", + "alertingActionWebhookDescription": "Wyślij żądanie HTTP do niestandardowego punktu końcowego", + "alertingExternalIntegration": "Integracja Zewnętrzna", + "alertingExternalPagerDutyDescription": "Przesyłaj alerty do PagerDuty do zarządzania incydentami", + "alertingExternalOpsgenieDescription": "Kieruj alerty do Opsgenie dla zarządzania dyżurem", + "alertingExternalServiceNowDescription": "Twórz incydenty ServiceNow z alertów", + "alertingExternalIncidentIoDescription": "Wyzwalaj przepływy Incident.io z alertów", + "alertingActionType": "Typ akcji", + "alertingNotifyUsers": "Użytkownicy", + "alertingNotifyRoles": "Role", + "alertingNotifyEmails": "Adres e-mail", + "alertingEmailPlaceholder": "Dodaj e-mail i naciśnij Enter", + "alertingWebhookMethod": "Metoda HTTP", + "alertingWebhookSecret": "Sekret podpisu (opcjonalny)", + "alertingWebhookSecretPlaceholder": "Sekret HMAC", + "alertingWebhookHeaders": "Nagłówki", + "alertingAddHeader": "Dodaj nagłówek", + "alertingSelectSites": "Wybierz witryny…", + "alertingSitesSelected": "{count} witryny wybrano", + "alertingSelectHealthChecks": "Wybierz wyniki zdrowia…", + "alertingHealthChecksSelected": "{count} wyniki zdrowia wybrane", + "alertingNoHealthChecks": "Brak celów z aktywowanymi kontrolami zdrowia", + "alertingHealthCheckStub": "Wybór źródła kontroli zdrowia jeszcze nie skonfigurowany - możesz nadal skonfigurować wyzwalacze i akcje.", + "alertingSelectUsers": "Wybierz użytkowników…", + "alertingUsersSelected": "{count} użytkowników wybrano", + "alertingSelectRoles": "Wybierz role…", + "alertingRolesSelected": "{count} ról wybrano", + "alertingSummarySites": "Witryny ({count})", + "alertingSummaryAllSites": "Wszystkie witryny", + "alertingSummaryHealthChecks": "Kontrole zdrowia ({count})", + "alertingSummaryAllHealthChecks": "Wszystkie kontrole zdrowia", + "alertingSummaryResources": "Zasoby ({count})", + "alertingSummaryAllResources": "Wszystkie zasoby", + "alertingErrorNameRequired": "Wprowadź nazwę", + "alertingErrorActionsMin": "Dodaj co najmniej jedną akcję", + "alertingErrorPickSites": "Wybierz co najmniej jedną witrynę", + "alertingErrorPickHealthChecks": "Wybierz co najmniej jedną kontrolę zdrowia", + "alertingErrorPickResources": "Wybierz co najmniej jeden zasób", + "alertingErrorTriggerSite": "Wybierz wyzwalacz witryny", + "alertingErrorTriggerHealth": "Wybierz wyzwalacz kontroli zdrowia", + "alertingErrorTriggerResource": "Wybierz wyzwalacz zasobu", + "alertingErrorNotifyRecipients": "Wybierz użytkowników, role lub co najmniej jeden e-mail", + "alertingConfigureSource": "Skonfiguruj źródło", + "alertingConfigureTrigger": "Skonfiguruj wyzwalacz", + "alertingConfigureActions": "Skonfiguruj akcje", + "alertingBackToRules": "Powrót do reguł", + "alertingRuleCooldown": "Czas ochłodzenia (sekundy)", + "alertingRuleCooldownDescription": "Minimalny czas między powtórzonymi alarmami dla tej samej reguły. Ustaw na 0, aby wyzwalać za każdym razem.", + "alertingDraftBadge": "Szkic - zapisz, aby zachować tę regułę", + "alertingSidebarHint": "Kliknij krok na kanwie, aby edytować go tutaj.", + "alertingGraphCanvasTitle": "Przepływ reguł", + "alertingGraphCanvasDescription": "Wizualny podgląd źródła, wyzwalacza i akcji. Wybierz węzeł, aby edytować go w panelu.", + "alertingNodeNotConfigured": "Nie skonfigurowano jeszcze", + "alertingNodeActionsCount": "{count, plural, one {# akcja} few {# akcje} many {# akcji} other {# akcji}}", + "alertingNodeRoleSource": "Źródło", + "alertingNodeRoleTrigger": "Wyzwalacz", + "alertingNodeRoleAction": "Akcja", + "alertingTabRules": "Reguły Alarmowe", + "alertingTabHealthChecks": "Kontrole Zdrowia", + "alertingRulesBannerTitle": "Otrzymaj Powiadomienie", + "alertingRulesBannerDescription": "Każda reguła wiąże ze sobą co obserwować (np. witryna, kontrola zdrowia czy zasób), kiedy uruchomić (np. offline lub niezdrowy), oraz jak powiadomić zespół przez e-mail, webhooks lub integracje. Użyj tej listy, aby utworzyć, włączyć i zarządzać tymi regułami.", + "alertingHealthChecksBannerTitle": "Monitor Zdrowia i Zasobów", + "alertingHealthChecksBannerDescription": "Kontrole zdrowia to monitory HTTP lub TCP, które definiujesz raz. Następnie możesz używać ich jako źródeł w regułach alarmowych, aby otrzymywać powiadomienia, kiedy cel stanie się zdrowy lub niezdrowy. Kontrole zdrowia w zasobach również pojawiają się tutaj.", + "standaloneHcTableTitle": "Kontrole Zdrowia", + "standaloneHcSearchPlaceholder": "Szukaj kontroli zdrowia…", + "standaloneHcAddButton": "Utwórz Kontrolę Zdrowia", + "standaloneHcCreateTitle": "Utwórz Kontrolę Zdrowia", + "standaloneHcEditTitle": "Edytuj Kontrolę Zdrowia", + "standaloneHcDescription": "Skonfiguruj kontrolę zdrowia HTTP lub TCP do wykorzystania w regułach alarmowych.", + "standaloneHcNameLabel": "Nazwa", + "standaloneHcNamePlaceholder": "Mój Monitor HTTP", + "standaloneHcDeleteTitle": "Usuń kontrolę zdrowia", + "standaloneHcDeleteQuestion": "Potwierdź, że chcesz usunąć tę kontrolę zdrowia.", + "standaloneHcDeleted": "Kontrola zdrowia usunięta", + "standaloneHcSaved": "Kontrola zdrowia zapisana", + "standaloneHcColumnHealth": "Zdrowie", + "standaloneHcColumnMode": "Tryb", + "standaloneHcColumnTarget": "Cel", + "standaloneHcHealthStateHealthy": "Zdrowy", + "standaloneHcHealthStateUnhealthy": "Niezdrowy", + "standaloneHcHealthStateUnknown": "Nieznany", + "standaloneHcFilterAnySite": "Wszystkie witryny", + "standaloneHcFilterAnyResource": "Wszystkie zasoby", + "standaloneHcFilterMode": "Tryb", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "Ping", + "standaloneHcFilterHealth": "Zdrowie", + "standaloneHcFilterEnabled": "Włączone", + "standaloneHcFilterEnabledOn": "Włączone", + "standaloneHcFilterEnabledOff": "Wyłączone", + "standaloneHcFilterSiteIdFallback": "Witryna {id}", + "standaloneHcFilterResourceIdFallback": "Zasób {id}", "blueprints": "Schematy", "blueprintsDescription": "Zastosuj konfiguracje deklaracyjne i wyświetl poprzednie operacje", "blueprintAdd": "Dodaj schemat", @@ -1763,6 +1935,15 @@ "healthCheckIntervalMin": "Interwał sprawdzania musi wynosić co najmniej 5 sekund", "healthCheckTimeoutMin": "Limit czasu musi wynosić co najmniej 1 sekundę", "healthCheckRetryMin": "Liczba prób ponowienia musi wynosić co najmniej 1", + "healthCheckMode": "Tryb kontroli", + "healthCheckStrategy": "Strategia", + "healthCheckModeDescription": "Tryb TCP weryfikuje tylko łączność. Tryb HTTP ocenia odpowiedź HTTP.", + "healthyThreshold": "Próg zdrowia", + "healthyThresholdDescription": "Wymagane sukcesy pod rząd, zanim oznaczy się jako zdrowe.", + "unhealthyThreshold": "Próg niezdrowia", + "unhealthyThresholdDescription": "Wymagane niepowodzenia z rzędu, zanim oznaczy się jako niezdrowe.", + "healthCheckHealthyThresholdMin": "Próg zdrowia musi wynosić co najmniej 1", + "healthCheckUnhealthyThresholdMin": "Próg niezdrowia musi wynosić co najmniej 1", "httpMethod": "Metoda HTTP", "selectHttpMethod": "Wybierz metodę HTTP", "domainPickerSubdomainLabel": "Poddomena", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "Port", "editInternalResourceDialogModeHost": "Host", "editInternalResourceDialogModeCidr": "CIDR", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "Schemat", + "editInternalResourceDialogEnableSsl": "Włącz SSL", + "editInternalResourceDialogEnableSslDescription": "Włącz szyfrowanie SSL/TLS dla bezpiecznych połączeń HTTPS z miejscem docelowym.", "editInternalResourceDialogDestination": "Miejsce docelowe", "editInternalResourceDialogDestinationHostDescription": "Adres IP lub nazwa hosta zasobu w sieci witryny.", "editInternalResourceDialogDestinationIPDescription": "Adres IP lub nazwa hosta zasobu w sieci witryny.", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "Nazwa", "createInternalResourceDialogSite": "Witryna", "selectSite": "Wybierz stronę...", + "multiSitesSelectorSitesCount": "{count, plural, one {# witryna} few {# witryny} many {# witryn} other {# witryn}}", "noSitesFound": "Nie znaleziono stron.", "createInternalResourceDialogProtocol": "Protokół", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "Port", "createInternalResourceDialogModeHost": "Host", "createInternalResourceDialogModeCidr": "CIDR", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "Schemat", + "createInternalResourceDialogScheme": "Schemat", + "createInternalResourceDialogEnableSsl": "Włącz SSL", + "createInternalResourceDialogEnableSslDescription": "Włącz szyfrowanie SSL/TLS dla bezpiecznych połączeń HTTPS z miejscem docelowym.", "createInternalResourceDialogDestination": "Miejsce docelowe", "createInternalResourceDialogDestinationHostDescription": "Adres IP lub nazwa hosta zasobu w sieci witryny.", "createInternalResourceDialogDestinationCidrDescription": "Zakres CIDR zasobu w sieci witryny.", "createInternalResourceDialogAlias": "Alias", "createInternalResourceDialogAliasDescription": "Opcjonalny wewnętrzny alias DNS dla tego zasobu.", + "internalResourceDownstreamSchemeRequired": "Schemat jest wymagany dla zasobów HTTP", + "internalResourceHttpPortRequired": "Port docelowy jest wymagany dla zasobów HTTP", "siteConfiguration": "Konfiguracja", "siteAcceptClientConnections": "Akceptuj połączenia klienta", "siteAcceptClientConnectionsDescription": "Zezwalaj urządzeniom i klientom na dostęp do zasobów na tej stronie. Może to zostać zmienione później.", @@ -1994,7 +2189,7 @@ "description": "Większa niezawodność i niska konserwacja serwera Pangolin z dodatkowymi dzwonkami i sygnałami", "introTitle": "Zarządzany samowystarczalny Pangolin", "introDescription": "jest opcją wdrażania zaprojektowaną dla osób, które chcą prostoty i dodatkowej niezawodności, przy jednoczesnym utrzymaniu swoich danych prywatnych i samodzielnych.", - "introDetail": "Z tą opcją nadal obsługujesz swój własny węzeł Pangolin — tunele, zakończenie SSL i ruch na Twoim serwerze. Różnica polega na tym, że zarządzanie i monitorowanie odbywa się za pomocą naszej tablicy rozdzielczej, która odblokowuje szereg korzyści:", + "introDetail": "Z tą opcją nadal obsługujesz swój własny węzeł Pangolin - tunele, zakończenie SSL i ruch na Twoim serwerze. Różnica polega na tym, że zarządzanie i monitorowanie odbywa się za pomocą naszej tablicy rozdzielczej, która odblokowuje szereg korzyści:", "benefitSimplerOperations": { "title": "Uproszczone operacje", "description": "Nie ma potrzeby uruchamiania własnego serwera pocztowego lub ustawiania skomplikowanych powiadomień. Będziesz mieć kontrolę zdrowia i powiadomienia o przestoju." @@ -2119,7 +2314,7 @@ "selectDomainForOrgAuthPage": "Wybierz domenę dla strony uwierzytelniania organizacji", "domainPickerProvidedDomain": "Dostarczona domena", "domainPickerFreeProvidedDomain": "Darmowa oferowana domena", - "domainPickerFreeDomainsPaidFeature": "Dostarczane domeny to funkcja płatna. Subskrybuj, aby uzyskać domenę w ramach swojego planu — nie ma potrzeby przynoszenia własnej.", + "domainPickerFreeDomainsPaidFeature": "Dostarczane domeny to funkcja płatna. Subskrybuj, aby uzyskać domenę w ramach swojego planu - nie ma potrzeby przynoszenia własnej.", "domainPickerVerified": "Zweryfikowano", "domainPickerUnverified": "Niezweryfikowane", "domainPickerManual": "Podręcznik", @@ -2429,6 +2624,7 @@ "validPassword": "Prawidłowe hasło", "validEmail": "Valid email", "validSSO": "Valid SSO", + "connectedClient": "Połączony Klient", "resourceBlocked": "Zasób zablokowany", "droppedByRule": "Upuszczone przez regułę", "noSessions": "Brak sesji", @@ -2668,6 +2864,10 @@ "editInternalResourceDialogDestinationLabel": "Miejsce docelowe", "editInternalResourceDialogDestinationDescription": "Określ adres docelowy dla wewnętrznego zasobu. Może to być nazwa hosta, adres IP lub zakres CIDR, w zależności od wybranego trybu. Opcjonalnie ustaw wewnętrzny alias DNS dla łatwiejszej identyfikacji.", "editInternalResourceDialogPortRestrictionsDescription": "Ogranicz dostęp do konkretnych portów TCP/UDP lub zezwól/zablokuj wszystkie porty.", + "createInternalResourceDialogHttpConfiguration": "Konfiguracja HTTP", + "createInternalResourceDialogHttpConfigurationDescription": "Wybierz domenę, której klienci będą używać, aby dotrzeć do tego zasobu przez HTTP lub HTTPS.", + "editInternalResourceDialogHttpConfiguration": "Konfiguracja HTTP", + "editInternalResourceDialogHttpConfigurationDescription": "Wybierz domenę, której klienci będą używać, aby dotrzeć do tego zasobu przez HTTP lub HTTPS.", "editInternalResourceDialogTcp": "TCP", "editInternalResourceDialogUdp": "UDP", "editInternalResourceDialogIcmp": "ICMP", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "Wrócimy wkrótce! Nasza strona przechodzi obecnie zaplanowaną konserwację.", "maintenancePageMessageDescription": "Szczegółowy komunikat wyjaśniający konserwację", "maintenancePageTimeTitle": "Szacowany czas zakończenia (opcjonalnie)", + "privateMaintenanceScreenTitle": "Ekraan prywatnego utrzymania", + "privateMaintenanceScreenMessage": "Ta domena jest wykorzystywana na prywatnym zasobie. Połącz się za pomocą klienta Pangolin, aby uzyskać dostęp do tego zasobu.", "maintenanceTime": "np. 2 godziny, 1 listopad o 17:00", "maintenanceEstimatedTimeDescription": "Kiedy oczekujesz zakończenia konserwacji", "editDomain": "Edytuj domenę", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "Dodaj cel HTTP", "httpDestEditDescription": "Aktualizuj konfigurację dla tego celu przesyłania strumieniowego zdarzeń HTTP.", "httpDestAddDescription": "Skonfiguruj nowy punkt końcowy HTTP, aby otrzymywać wydarzenia organizacji.", + "S3DestEditTitle": "Edytuj Miejsce Docelowe", + "S3DestAddTitle": "Dodaj Miejsce Docelowe S3", + "S3DestEditDescription": "Zaktualizuj konfigurację dla tego miejsca docelowego strumieniowego zdarzeń S3.", + "S3DestAddDescription": "Skonfiguruj nowy punkt końcowy S3, aby odbierać zdarzenia Twojej organizacji.", + "datadogDestEditTitle": "Edytuj Miejsce Docelowe", + "datadogDestAddTitle": "Dodaj Miejsce Docelowe Datadog", + "datadogDestEditDescription": "Zaktualizuj konfigurację dla tego miejsca docelowego strumieniowego zdarzeń Datadog.", + "datadogDestAddDescription": "Skonfiguruj nowy punkt końcowy Datadog, aby odbierać zdarzenia Twojej organizacji.", "httpDestTabSettings": "Ustawienia", "httpDestTabHeaders": "Nagłówki", "httpDestTabBody": "Ciało", @@ -2882,7 +3092,7 @@ "httpDestFormatJsonArrayTitle": "Tablica JSON", "httpDestFormatJsonArrayDescription": "Jedna prośba na partię, treść jest tablicą JSON. Kompatybilna z najbardziej ogólnymi webhookami i Datadog.", "httpDestFormatNdjsonTitle": "NDJSON", - "httpDestFormatNdjsonDescription": "Jedno żądanie na partię, ciałem jest plik JSON rozdzielony na newline-delimited — jeden obiekt na wiersz, bez tablicy zewnętrznej. Wymagane przez Splunk HEC, Elastic / OpenSesearch i Grafana Loki.", + "httpDestFormatNdjsonDescription": "Jedno żądanie na partię, ciałem jest plik JSON rozdzielony na newline-delimited - jeden obiekt na wiersz, bez tablicy zewnętrznej. Wymagane przez Splunk HEC, Elastic / OpenSesearch i Grafana Loki.", "httpDestFormatSingleTitle": "Jedno wydarzenie na żądanie", "httpDestFormatSingleDescription": "Wysyła oddzielny POST HTTP dla każdego zdarzenia. Użyj tylko dla punktów końcowych, które nie mogą obsługiwać partii.", "httpDestLogTypesTitle": "Typy logów", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "Cel został utworzony pomyślnie", "httpDestUpdateFailed": "Nie udało się zaktualizować miejsca docelowego", "httpDestCreateFailed": "Nie udało się utworzyć miejsca docelowego", + "followRedirects": "Podążaj za przekierowaniami", + "followRedirectsDescription": "Automatycznie podążaj za przekierowaniami HTTP dla żądań.", + "alertingErrorWebhookUrl": "Proszę wprowadzić poprawny URL dla web hooka.", + "healthCheckStrategyHttp": "Weryfikuje łączność i sprawdza status odpowiedzi HTTP.", + "healthCheckStrategyTcp": "Weryfikuje wyłącznie łączność TCP, bez sprawdzania odpowiedzi.", + "healthCheckStrategySnmp": "Wykonuje żądanie SNMP get w celu sprawdzenia stanu urządzeń sieciowych i infrastruktury.", + "healthCheckStrategyIcmp": "Używa żądań ICMP echo (pingów), aby sprawdzić, czy zasób jest dostępny i reagujący.", + "healthCheckTabStrategy": "Strategia", + "healthCheckTabConnection": "Łączenie", + "healthCheckTabAdvanced": "Zaawansowane", + "healthCheckStrategyNotAvailable": "Strategia ta nie jest dostępna. Skontaktuj się z działem sprzedaży, aby włączyć tę funkcję.", + "uptime30d": "Czas działania (30d)", "idpAddActionCreateNew": "Utwórz nowego dostawcę tożsamości", "idpAddActionImportFromOrg": "Importuj z innej organizacji", "idpImportDialogTitle": "Importuj dostawcę tożsamości", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "Tego nie można cofnąć dla tej organizacji.", "idpUnassociatedDescription": "Dostawca tożsamości pomyślnie odłączony od tej organizacji", "idpUnassociateMenu": "Odłącz", - "idpDeleteAllOrgsMenu": "Usuń" + "idpDeleteAllOrgsMenu": "Usuń", + "publicIpEndpoint": "Koniec punktu pracy", + "lastTriggeredAt": "Ostatnie Wyzwolenie", + "reject": "Odrzuć" } diff --git a/messages/pt-PT.json b/messages/pt-PT.json index 86ee54d61..949f06ac6 100644 --- a/messages/pt-PT.json +++ b/messages/pt-PT.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "Contacte vendas para ativar esta funcionalidade.", + "contactSalesBookDemo": "Agende uma demonstração", + "contactSalesOr": "ou", + "contactSalesContactUs": "contacte-nos", "setupCreate": "Criar a organização, o site e os recursos", "headerAuthCompatibilityInfo": "Habilite isso para forçar uma resposta 401 Unauthorized quando um token de autenticação estiver faltando. Isso é necessário para navegadores ou bibliotecas HTTP específicas que não enviam credenciais sem um desafio do servidor.", "headerAuthCompatibility": "Compatibilidade Estendida", @@ -19,6 +23,14 @@ "componentsInvalidKey": "Chaves de licença inválidas ou expiradas detectadas. Siga os termos da licença para continuar usando todos os recursos.", "dismiss": "Rejeitar", "subscriptionViolationMessage": "Você está além dos seus limites para o seu plano atual. Corrija o problema removendo sites, usuários, ou outros recursos para ficar em seu plano.", + "trialBannerMessage": "Sua avaliação termina em {countdown}. Faça o upgrade para manter o acesso.", + "trialBannerExpired": "Sua avaliação expirou. Faça o upgrade agora para restaurar o acesso.", + "trialActive": "Avaliação Gratuita Ativa", + "trialExpired": "Avaliação Expirada", + "trialHasEnded": "Sua avaliação terminou.", + "trialDaysRemaining": "{count, plural, one {# dia restante} other {# dias restantes}}", + "trialDaysLeftShort": "{days}d restante na avaliação", + "trialGoToBilling": "Ir para a página de faturamento", "subscriptionViolationViewBilling": "Ver faturamento", "componentsLicenseViolation": "Violação de Licença: Este servidor está usando sites {usedSites} que excedem o limite licenciado de sites {maxSites} . Siga os termos da licença para continuar usando todos os recursos.", "componentsSupporterMessage": "Obrigado por apoiar o Pangolin como um {tier}!", @@ -267,8 +279,11 @@ "orgMissing": "ID da Organização Ausente", "orgMissingMessage": "Não é possível regenerar o convite sem um ID de organização.", "accessUsersManage": "Gerir Utilizadores", + "accessUserManage": "Gerir Utilizador", "accessUsersDescription": "Convidar e gerenciar usuários com acesso a esta organização", "accessUsersSearch": "Procurar utilizadores...", + "accessUsersRoleFilterCount": "{count, plural, one {# função} other {# funções}}", + "accessUsersRoleFilterClear": "Limpar filtros de funções", "accessUserCreate": "Criar Usuário", "accessUserRemove": "Remover utilizador", "username": "Usuário:", @@ -1257,6 +1272,7 @@ "actionViewLogs": "Visualizar registros", "noneSelected": "Nenhum selecionado", "orgNotFound2": "Nenhuma organização encontrada.", + "search": "Pesquisar…", "searchPlaceholder": "Buscar...", "emptySearchOptions": "Nenhuma opção encontrada", "create": "Criar", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "Gerir", "sidebarLogAndAnalytics": "Registo & Análise", "sidebarBluePrints": "Diagramas", + "sidebarAlerting": "Alertas", + "sidebarHealthChecks": "Verificações de Saúde", "sidebarOrganization": "Organização", "sidebarManagement": "Gestão", "sidebarBillingAndLicenses": "Faturamento e Licenças", "sidebarLogsAnalytics": "Análises", + "alertingTitle": "Alertas", + "alertingDescription": "Defina fontes, gatilhos e ações para notificações", + "alertingRules": "Regras de alerta", + "alertingSearchRules": "Pesquisar regras…", + "alertingAddRule": "Criar Regra", + "alertingColumnSource": "Fonte", + "alertingColumnTrigger": "Gatilho", + "alertingColumnActions": "Ações", + "alertingColumnEnabled": "Ativado", + "alertingDeleteQuestion": "Por favor, confirme que deseja excluir esta regra de alerta.", + "alertingDeleteRule": "Excluir regra de alerta", + "alertingRuleDeleted": "Regra de alerta excluída", + "alertingRuleSaved": "Regra de alerta salva", + "alertingRuleSavedCreatedDescription": "Sua nova regra de alerta foi criada. Você pode continuar editando-a nesta página.", + "alertingRuleSavedUpdatedDescription": "As suas alterações para esta regra de alerta foram salvas.", + "alertingEditRule": "Editar Regra de Alerta", + "alertingCreateRule": "Criar Regra de Alerta", + "alertingRuleCredenzaDescription": "Escolha o que observar, quando disparar e como notificar", + "alertingRuleNamePlaceholder": "Site de produção fora do ar", + "alertingRuleEnabled": "Regra ativada", + "alertingSectionSource": "Fonte", + "alertingSourceType": "Tipo de Fonte", + "alertingSourceSite": "Site", + "alertingSourceHealthCheck": "Verificação de Saúde", + "alertingPickSites": "Sites", + "alertingPickHealthChecks": "Verificações de Saúde", + "alertingPickResources": "Recursos", + "alertingAllSites": "Todos os Sites", + "alertingAllSitesDescription": "Alerta disparado para qualquer site", + "alertingSpecificSites": "Sites Específicos", + "alertingSpecificSitesDescription": "Escolha sites específicos para observar", + "alertingAllHealthChecks": "Todas as Verificações de Saúde", + "alertingAllHealthChecksDescription": "Alerta disparado para qualquer verificação de saúde", + "alertingSpecificHealthChecks": "Verificações de Saúde Específicas", + "alertingSpecificHealthChecksDescription": "Escolha verificações de saúde específicas para observar", + "alertingAllResources": "Todos os Recursos", + "alertingAllResourcesDescription": "Alerta disparado para qualquer recurso", + "alertingSpecificResources": "Recursos Específicos", + "alertingSpecificResourcesDescription": "Escolha recursos específicos para observar", + "alertingSelectResources": "Selecionar recursos…", + "alertingResourcesSelected": "{count} recursos selecionados", + "alertingResourcesEmpty": "Nenhum recurso com alvos nos primeiros 10 resultados.", + "alertingSectionTrigger": "Gatilho", + "alertingTrigger": "Quando alertar", + "alertingTriggerSiteOnline": "Site online", + "alertingTriggerSiteOffline": "Site offline", + "alertingTriggerSiteToggle": "Status do site muda", + "alertingTriggerHcHealthy": "Verificação de saúde saudável", + "alertingTriggerHcUnhealthy": "Verificação de saúde não saudável", + "alertingTriggerHcToggle": "Status da verificação de saúde muda", + "alertingTriggerResourceHealthy": "Recurso saudável", + "alertingTriggerResourceUnhealthy": "Recurso não saudável", + "alertingSearchHealthChecks": "Pesquisar verificações de saúde…", + "alertingHealthChecksEmpty": "Nenhuma verificação de saúde disponível.", + "alertingTriggerResourceToggle": "Status do recurso muda", + "alertingSourceResource": "Recurso", + "alertingSectionActions": "Ações", + "alertingAddAction": "Adicionar Ação", + "alertingActionNotify": "E-mail", + "alertingActionNotifyDescription": "Enviar notificações por e-mail para usuários ou funções", + "alertingActionWebhook": "Webhook", + "alertingActionWebhookDescription": "Envie uma solicitação HTTP para um endpoint personalizado", + "alertingExternalIntegration": "Integração Externa", + "alertingExternalPagerDutyDescription": "Envie alertas para PagerDuty para gerenciamento de incidentes", + "alertingExternalOpsgenieDescription": "Direcione alertas para Opsgenie para gestão de plantão", + "alertingExternalServiceNowDescription": "Crie incidentes do ServiceNow a partir de eventos de alerta", + "alertingExternalIncidentIoDescription": "Dispare fluxos de trabalho do Incident.io a partir de eventos de alerta", + "alertingActionType": "Tipo de Ação", + "alertingNotifyUsers": "Utilizadores", + "alertingNotifyRoles": "Papéis", + "alertingNotifyEmails": "Endereços de e-mail", + "alertingEmailPlaceholder": "Adicione o e-mail e pressione Enter", + "alertingWebhookMethod": "Método HTTP", + "alertingWebhookSecret": "Segredo de assinatura (opcional)", + "alertingWebhookSecretPlaceholder": "Segredo HMAC", + "alertingWebhookHeaders": "Cabeçalhos", + "alertingAddHeader": "Adicionar cabeçalho", + "alertingSelectSites": "Selecionar sites…", + "alertingSitesSelected": "{count} sites selecionados", + "alertingSelectHealthChecks": "Selecionar verificações de saúde…", + "alertingHealthChecksSelected": "{count} verificações de saúde selecionadas", + "alertingNoHealthChecks": "Nenhum alvo com verificações de saúde ativadas", + "alertingHealthCheckStub": "A seleção da fonte de verificação de saúde ainda não está configurada - você ainda pode configurar gatilhos e ações.", + "alertingSelectUsers": "Selecionar utilizadores…", + "alertingUsersSelected": "{count} utilizadores selecionados", + "alertingSelectRoles": "Selecionar funções…", + "alertingRolesSelected": "{count} funções selecionadas", + "alertingSummarySites": "Sites ({count})", + "alertingSummaryAllSites": "Todos os sites", + "alertingSummaryHealthChecks": "Verificações de saúde ({count})", + "alertingSummaryAllHealthChecks": "Todas as verificações de saúde", + "alertingSummaryResources": "Recursos ({count})", + "alertingSummaryAllResources": "Todos os recursos", + "alertingErrorNameRequired": "Digite um nome", + "alertingErrorActionsMin": "Adicione pelo menos uma ação", + "alertingErrorPickSites": "Selecione pelo menos um site", + "alertingErrorPickHealthChecks": "Selecione pelo menos uma verificação de saúde", + "alertingErrorPickResources": "Selecione pelo menos um recurso", + "alertingErrorTriggerSite": "Escolha um gatilho de site", + "alertingErrorTriggerHealth": "Escolha um gatilho de verificação de saúde", + "alertingErrorTriggerResource": "Escolha um gatilho de recurso", + "alertingErrorNotifyRecipients": "Escolha utilizadores, funções ou pelo menos um e-mail", + "alertingConfigureSource": "Configurar Fonte", + "alertingConfigureTrigger": "Configurar Gatilho", + "alertingConfigureActions": "Configurar Ações", + "alertingBackToRules": "Voltar às Regras", + "alertingRuleCooldown": "Tempo de Resfriamento (segundos)", + "alertingRuleCooldownDescription": "Tempo mínimo entre alertas repetidos para a mesma regra. Defina para 0 para disparar todas as vezes.", + "alertingDraftBadge": "Rascunho - salvar para armazenar esta regra", + "alertingSidebarHint": "Clique em um passo na tela para editá-lo aqui.", + "alertingGraphCanvasTitle": "Fluxo de Regras", + "alertingGraphCanvasDescription": "Visão geral visual de fonte, gatilho e ações. Selecione um nó para editá-lo no painel.", + "alertingNodeNotConfigured": "Ainda não configurado", + "alertingNodeActionsCount": "{count, plural, one {# ação} other {# ações}}", + "alertingNodeRoleSource": "Fonte", + "alertingNodeRoleTrigger": "Gatilho", + "alertingNodeRoleAction": "Ação", + "alertingTabRules": "Regras de Alerta", + "alertingTabHealthChecks": "Verificações de Saúde", + "alertingRulesBannerTitle": "Seja Notificado", + "alertingRulesBannerDescription": "Cada regra une o que observar (um site, verificação de saúde ou recurso), quando disparar (por exemplo, offline ou não saudável) e como notificar sua equipe por e-mail, webhooks ou integrações. Use esta lista para criar, ativar e gerenciar essas regras.", + "alertingHealthChecksBannerTitle": "Monitorar Saúde & Recursos", + "alertingHealthChecksBannerDescription": "As verificações de saúde são monitores HTTP ou TCP que você define uma vez. Você pode, então, usá-los como fontes em regras de alerta, para ser notificado quando um alvo se tornar saudável ou não saudável. As verificações de saúde em recursos também aparecem aqui.", + "standaloneHcTableTitle": "Verificações de Saúde", + "standaloneHcSearchPlaceholder": "Pesquisar verificações de saúde…", + "standaloneHcAddButton": "Criar Verificação de Saúde", + "standaloneHcCreateTitle": "Criar Verificação de Saúde", + "standaloneHcEditTitle": "Editar Verificação de Saúde", + "standaloneHcDescription": "Configure uma verificação de saúde HTTP ou TCP para uso em regras de alerta.", + "standaloneHcNameLabel": "Nome", + "standaloneHcNamePlaceholder": "Meu Monitor HTTP", + "standaloneHcDeleteTitle": "Excluir verificação de saúde", + "standaloneHcDeleteQuestion": "Por favor, confirme que deseja excluir esta verificação de saúde.", + "standaloneHcDeleted": "Verificação de saúde excluída", + "standaloneHcSaved": "Verificação de saúde salva", + "standaloneHcColumnHealth": "Saúde", + "standaloneHcColumnMode": "Modo", + "standaloneHcColumnTarget": "Alvo", + "standaloneHcHealthStateHealthy": "Saudável", + "standaloneHcHealthStateUnhealthy": "Não Saudável", + "standaloneHcHealthStateUnknown": "Desconhecido", + "standaloneHcFilterAnySite": "Todos os sites", + "standaloneHcFilterAnyResource": "Todos os recursos", + "standaloneHcFilterMode": "Modo", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "Ping", + "standaloneHcFilterHealth": "Saúde", + "standaloneHcFilterEnabled": "Ativado", + "standaloneHcFilterEnabledOn": "Ativado", + "standaloneHcFilterEnabledOff": "Desativado", + "standaloneHcFilterSiteIdFallback": "Site {id}", + "standaloneHcFilterResourceIdFallback": "Recurso {id}", "blueprints": "Diagramas", "blueprintsDescription": "Aplicar configurações declarativas e ver execuções anteriores", "blueprintAdd": "Adicionar Diagrama", @@ -1763,6 +1935,15 @@ "healthCheckIntervalMin": "O intervalo de verificação deve ser de pelo menos 5 segundos", "healthCheckTimeoutMin": "O tempo limite deve ser de pelo menos 1 segundo", "healthCheckRetryMin": "As tentativas de repetição devem ser pelo menos 1", + "healthCheckMode": "Modo de Verificação", + "healthCheckStrategy": "Estratégia", + "healthCheckModeDescription": "Modo TCP verifica apenas a conectividade. Modo HTTP valida a resposta HTTP.", + "healthyThreshold": "Limite de Saúde", + "healthyThresholdDescription": "Sucessos consecutivos necessários antes de marcar como saudável.", + "unhealthyThreshold": "Limite de Não Saúde", + "unhealthyThresholdDescription": "Falhas consecutivas necessárias antes de marcar como não saudável.", + "healthCheckHealthyThresholdMin": "Limite de saúde deve ser pelo menos 1", + "healthCheckUnhealthyThresholdMin": "Limite de não saúde deve ser pelo menos 1", "httpMethod": "Método HTTP", "selectHttpMethod": "Selecionar método HTTP", "domainPickerSubdomainLabel": "Subdomínio", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "Porta", "editInternalResourceDialogModeHost": "Servidor", "editInternalResourceDialogModeCidr": "CIDR", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "Esquema", + "editInternalResourceDialogEnableSsl": "Ativar SSL", + "editInternalResourceDialogEnableSslDescription": "Ativar criptografia SSL/TLS para conexões HTTPS seguras com o destino.", "editInternalResourceDialogDestination": "Destino", "editInternalResourceDialogDestinationHostDescription": "O endereço IP ou o nome do host do recurso na rede do site.", "editInternalResourceDialogDestinationIPDescription": "O IP ou endereço do hostname do recurso na rede do site.", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "Nome", "createInternalResourceDialogSite": "Site", "selectSite": "Selecionar site...", + "multiSitesSelectorSitesCount": "{count, plural, one {# site} other {# sites}}", "noSitesFound": "Nenhum site encontrado.", "createInternalResourceDialogProtocol": "Protocolo", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "Porta", "createInternalResourceDialogModeHost": "Servidor", "createInternalResourceDialogModeCidr": "CIDR", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "Esquema", + "createInternalResourceDialogScheme": "Esquema", + "createInternalResourceDialogEnableSsl": "Ativar SSL", + "createInternalResourceDialogEnableSslDescription": "Ativar criptografia SSL/TLS para conexões HTTPS seguras com o destino.", "createInternalResourceDialogDestination": "Destino", "createInternalResourceDialogDestinationHostDescription": "O endereço IP ou o nome do host do recurso na rede do site.", "createInternalResourceDialogDestinationCidrDescription": "A faixa CIDR do recurso na rede do site.", "createInternalResourceDialogAlias": "Alias", "createInternalResourceDialogAliasDescription": "Um alias de DNS interno opcional para este recurso.", + "internalResourceDownstreamSchemeRequired": "Esquema é obrigatório para recursos HTTP", + "internalResourceHttpPortRequired": "Porta de destino é obrigatória para recursos HTTP", "siteConfiguration": "Configuração", "siteAcceptClientConnections": "Aceitar Conexões de Clientes", "siteAcceptClientConnectionsDescription": "Permitir que dispositivos de usuário e clientes acessem recursos neste site. Isso pode ser alterado mais tarde.", @@ -1994,7 +2189,7 @@ "description": "Servidor Pangolin auto-hospedado mais confiável e com baixa manutenção com sinos extras e assobiamentos", "introTitle": "Pangolin Auto-Hospedado Gerenciado", "introDescription": "é uma opção de implantação projetada para pessoas que querem simplicidade e confiança adicional, mantendo os seus dados privados e auto-hospedados.", - "introDetail": "Com esta opção, você ainda roda seu próprio nó Pangolin — seus túneis, terminação SSL e tráfego todos permanecem no seu servidor. A diferença é que a gestão e a monitorização são geridos através do nosso painel de nuvem, que desbloqueia vários benefícios:", + "introDetail": "Com esta opção, você ainda roda seu próprio nó Pangolin - seus túneis, terminação SSL e tráfego todos permanecem no seu servidor. A diferença é que a gestão e a monitorização são geridos através do nosso painel de nuvem, que desbloqueia vários benefícios:", "benefitSimplerOperations": { "title": "Operações simples", "description": "Não é necessário executar o seu próprio servidor de e-mail ou configurar um alerta complexo. Você receberá fora de caixa verificações de saúde e alertas de tempo de inatividade." @@ -2119,7 +2314,7 @@ "selectDomainForOrgAuthPage": "Selecione um domínio para a página de autenticação da organização", "domainPickerProvidedDomain": "Domínio fornecido", "domainPickerFreeProvidedDomain": "Domínio fornecido grátis", - "domainPickerFreeDomainsPaidFeature": "Os domínios fornecidos são um recurso pago. Assine para obter um domínio incluído no seu plano — não há necessidade de trazer o seu próprio.", + "domainPickerFreeDomainsPaidFeature": "Os domínios fornecidos são um recurso pago. Assine para obter um domínio incluído no seu plano - não há necessidade de trazer o seu próprio.", "domainPickerVerified": "Verificada", "domainPickerUnverified": "Não verificado", "domainPickerManual": "Manual", @@ -2297,7 +2492,7 @@ "alerts": { "commercialUseDisclosure": { "title": "Divulgação de uso", - "description": "Selecione o nível de licença que reflete corretamente seu uso pretendido. A Licença Pessoal permite o uso livre do Software para atividades comerciais individuais, não comerciais ou em pequena escala com rendimento bruto anual inferior a 100.000 USD. Qualquer uso além destes limites — incluindo uso dentro de um negócio, organização, ou outro ambiente gerador de receitas — requer uma Licença Enterprise válida e o pagamento da taxa aplicável de licenciamento. Todos os usuários, pessoais ou empresariais, devem cumprir os Termos da Licença Comercial Fossorial." + "description": "Selecione o nível de licença que reflete corretamente seu uso pretendido. A Licença Pessoal permite o uso livre do Software para atividades comerciais individuais, não comerciais ou em pequena escala com rendimento bruto anual inferior a 100.000 USD. Qualquer uso além destes limites - incluindo uso dentro de um negócio, organização, ou outro ambiente gerador de receitas - requer uma Licença Enterprise válida e o pagamento da taxa aplicável de licenciamento. Todos os usuários, pessoais ou empresariais, devem cumprir os Termos da Licença Comercial Fossorial." }, "trialPeriodInformation": { "title": "Informações do Período de Avaliação", @@ -2429,6 +2624,7 @@ "validPassword": "Senha válida", "validEmail": "Valid email", "validSSO": "Valid SSO", + "connectedClient": "Cliente Conectado", "resourceBlocked": "Recurso bloqueado", "droppedByRule": "Derrubado pela regra", "noSessions": "Sem Sessões", @@ -2668,6 +2864,10 @@ "editInternalResourceDialogDestinationLabel": "Destino", "editInternalResourceDialogDestinationDescription": "Especifique o endereço de destino para o recurso interno. Isso pode ser um nome de host, endereço IP ou intervalo CIDR, dependendo do modo selecionado. Opcionalmente, defina um alias interno de DNS para facilitar a identificação.", "editInternalResourceDialogPortRestrictionsDescription": "Restrinja o acesso a portas TCP/UDP específicas ou permita/bloqueie todas as portas.", + "createInternalResourceDialogHttpConfiguration": "Configuração HTTP", + "createInternalResourceDialogHttpConfigurationDescription": "Escolha o domínio que os clientes usarão para acessar este recurso via HTTP ou HTTPS.", + "editInternalResourceDialogHttpConfiguration": "Configuração HTTP", + "editInternalResourceDialogHttpConfigurationDescription": "Escolha o domínio que os clientes usarão para acessar este recurso via HTTP ou HTTPS.", "editInternalResourceDialogTcp": "TCP", "editInternalResourceDialogUdp": "UDP", "editInternalResourceDialogIcmp": "ICMP", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "Voltaremos em breve! Nosso site está passando por manutenção programada.", "maintenancePageMessageDescription": "Mensagem detalhada explicando a manutenção", "maintenancePageTimeTitle": "Hora de Conclusão Estimada (Opcional)", + "privateMaintenanceScreenTitle": "Tela de Placeholder Privada", + "privateMaintenanceScreenMessage": "Este domínio está sendo usado em um recurso privado. Por favor, conecte-se usando o cliente Pangolin para acessar este recurso.", "maintenanceTime": "por exemplo, 2 horas, 1 de Nov às 17h00", "maintenanceEstimatedTimeDescription": "Quando você espera que a manutenção seja concluída", "editDomain": "Editar Domínio", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "Adicionar Destino HTTP", "httpDestEditDescription": "Atualizar a configuração para este destino de transmissão de eventos HTTP.", "httpDestAddDescription": "Configure um novo ponto de extremidade HTTP para receber eventos da sua organização.", + "S3DestEditTitle": "Editar Destino", + "S3DestAddTitle": "Adicionar Destino S3", + "S3DestEditDescription": "Atualize a configuração para este destino de streaming de eventos S3.", + "S3DestAddDescription": "Configure um novo endpoint S3 para receber os eventos da sua organização.", + "datadogDestEditTitle": "Editar Destino", + "datadogDestAddTitle": "Adicionar Destino Datadog", + "datadogDestEditDescription": "Atualize a configuração para este destino de streaming de eventos Datadog.", + "datadogDestAddDescription": "Configure um novo endpoint Datadog para receber os eventos da sua organização.", "httpDestTabSettings": "Confirgurações", "httpDestTabHeaders": "Cabeçalhos", "httpDestTabBody": "Conteúdo", @@ -2882,7 +3092,7 @@ "httpDestFormatJsonArrayTitle": "Matriz JSON", "httpDestFormatJsonArrayDescription": "Um pedido por lote, o corpo é um array JSON. Compatível com a maioria dos webhooks genéricos e Datadog.", "httpDestFormatNdjsonTitle": "NDJSON", - "httpDestFormatNdjsonDescription": "Um pedido por lote, o corpo é um JSON delimitado por nova-linha — um objeto por linha, sem array exterior. Requerido pelo Splunk HEC, Elástico / OpenSearch, e Grafana Loki.", + "httpDestFormatNdjsonDescription": "Um pedido por lote, o corpo é um JSON delimitado por nova-linha - um objeto por linha, sem array exterior. Requerido pelo Splunk HEC, Elástico / OpenSearch, e Grafana Loki.", "httpDestFormatSingleTitle": "Um Evento por Requisição", "httpDestFormatSingleDescription": "Envia um POST HTTP separado para cada evento. Utilize apenas para endpoints que não podem manipular lotes.", "httpDestLogTypesTitle": "Tipos de log", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "Destino criado com sucesso", "httpDestUpdateFailed": "Falha ao atualizar destino", "httpDestCreateFailed": "Falha ao criar destino", + "followRedirects": "Seguir Redirecionamentos", + "followRedirectsDescription": "Siga automaticamente os redirecionamentos HTTP para requisições.", + "alertingErrorWebhookUrl": "Por favor, insira um URL válido para o webhook.", + "healthCheckStrategyHttp": "Valida conectividade e verifica o status da resposta HTTP.", + "healthCheckStrategyTcp": "Verifica apenas conectividade TCP, sem inspecionar a resposta.", + "healthCheckStrategySnmp": "Faz uma solicitação SNMP para verificar a saúde dos dispositivos e infraestruturas de rede.", + "healthCheckStrategyIcmp": "Usa solicitações de eco ICMP (pings) para verificar se um recurso é acessível e responsivo.", + "healthCheckTabStrategy": "Estratégia", + "healthCheckTabConnection": "Conexão", + "healthCheckTabAdvanced": "Avançado", + "healthCheckStrategyNotAvailable": "Esta estratégia não está disponível. Por favor, contacte vendas para ativar esta funcionalidade.", + "uptime30d": "Uptime (30d)", "idpAddActionCreateNew": "Criar novo provedor de identidade", "idpAddActionImportFromOrg": "Importar de outra organização", "idpImportDialogTitle": "Importar Provedor de Identidade", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "Isso não pode ser desfeito para esta organização.", "idpUnassociatedDescription": "Provedor de identidade desassociado desta organização com sucesso", "idpUnassociateMenu": "Desassociar", - "idpDeleteAllOrgsMenu": "Excluir" + "idpDeleteAllOrgsMenu": "Excluir", + "publicIpEndpoint": "Endpoint", + "lastTriggeredAt": "Último Gatilho", + "reject": "Rejeitar" } diff --git a/messages/ru-RU.json b/messages/ru-RU.json index 30596846a..d5496e660 100644 --- a/messages/ru-RU.json +++ b/messages/ru-RU.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "Свяжитесь с отделом продаж, чтобы включить эту функцию.", + "contactSalesBookDemo": "Записаться на демонстрацию", + "contactSalesOr": "или", + "contactSalesContactUs": "свяжитесь с нами", "setupCreate": "Создать организацию, сайт и ресурсы", "headerAuthCompatibilityInfo": "Включите это, чтобы принудительно вернуть ответ 401 Unauthorized, если отсутствует токен аутентификации. Это требуется для браузеров или определенных библиотек HTTP, которые не отправляют учетные данные без запроса сервера.", "headerAuthCompatibility": "Дополнительная совместимость", @@ -19,6 +23,14 @@ "componentsInvalidKey": "Обнаружены недействительные или просроченные лицензионные ключи. Соблюдайте условия лицензии для использования всех функций.", "dismiss": "Отменить", "subscriptionViolationMessage": "Вы превысили лимиты для вашего текущего плана. Исправьте проблему, удалив сайты, пользователей или другие ресурсы, чтобы остаться в пределах вашего плана.", + "trialBannerMessage": "Ваш пробный период истекает через {countdown}. Обновите, чтобы сохранить доступ.", + "trialBannerExpired": "Ваш пробный период истек. Обновите сейчас, чтобы восстановить доступ.", + "trialActive": "Бесплатный пробный период активен", + "trialExpired": "Пробный период истек", + "trialHasEnded": "Ваш пробный период окончен.", + "trialDaysRemaining": "{count, plural, one {# день остался} few {# дня осталось} many {# дней осталось} other {# дней осталось}}", + "trialDaysLeftShort": "Осталось {days}д в пробном периоде", + "trialGoToBilling": "Перейти на страницу выставления счетов", "subscriptionViolationViewBilling": "Просмотр биллинга", "componentsLicenseViolation": "Нарушение лицензии: Сервер использует {usedSites} сайтов, что превышает лицензионный лимит в {maxSites} сайтов. Соблюдайте условия лицензии для использования всех функций.", "componentsSupporterMessage": "Спасибо за поддержку Pangolin в качестве {tier}!", @@ -56,7 +68,7 @@ "siteManageSites": "Управление сайтами", "siteDescription": "Создание и управление сайтами, чтобы включить подключение к приватным сетям", "sitesBannerTitle": "Подключить любую сеть", - "sitesBannerDescription": "Сайт — это соединение с удаленной сетью, которое позволяет Pangolin предоставлять доступ к ресурсам, будь они общедоступными или частными, пользователям в любом месте. Установите сетевой коннектор сайта (Newt) там, где можно запустить исполняемый файл или контейнер, чтобы установить соединение.", + "sitesBannerDescription": "Сайт - это соединение с удаленной сетью, которое позволяет Pangolin предоставлять доступ к ресурсам, будь они общедоступными или частными, пользователям в любом месте. Установите сетевой коннектор сайта (Newt) там, где можно запустить исполняемый файл или контейнер, чтобы установить соединение.", "sitesBannerButtonText": "Установить сайт", "approvalsBannerTitle": "Одобрить или запретить доступ к устройству", "approvalsBannerDescription": "Просмотрите и подтвердите или отклоните запросы на доступ к устройству от пользователей. Когда требуется подтверждение устройства, пользователи должны получить одобрение администратора, прежде чем их устройства смогут подключиться к ресурсам вашей организации.", @@ -163,7 +175,7 @@ "proxyResourceTitle": "Управление публичными ресурсами", "proxyResourceDescription": "Создание и управление ресурсами, которые доступны через веб-браузер", "proxyResourcesBannerTitle": "Общедоступный доступ через веб", - "proxyResourcesBannerDescription": "Общедоступные ресурсы — это прокси-по HTTPS или TCP/UDP, доступные любому пользователю в Интернете через веб-браузер. В отличие от частных ресурсов, они не требуют программного обеспечения на стороне клиента и могут включать политики доступа на основе идентификации и контекста.", + "proxyResourcesBannerDescription": "Общедоступные ресурсы - это прокси-по HTTPS или TCP/UDP, доступные любому пользователю в Интернете через веб-браузер. В отличие от частных ресурсов, они не требуют программного обеспечения на стороне клиента и могут включать политики доступа на основе идентификации и контекста.", "clientResourceTitle": "Управление приватными ресурсами", "clientResourceDescription": "Создание и управление ресурсами, которые доступны только через подключенный клиент", "privateResourcesBannerTitle": "Частный доступ с нулевым доверием", @@ -267,8 +279,11 @@ "orgMissing": "Отсутствует ID организации", "orgMissingMessage": "Невозможно восстановить приглашение без ID организации.", "accessUsersManage": "Управление пользователями", + "accessUserManage": "Управление пользователем", "accessUsersDescription": "Пригласить и управлять пользователями с доступом к этой организации", "accessUsersSearch": "Поиск пользователей...", + "accessUsersRoleFilterCount": "{count, plural, one {# роль} few {# роли} many {# ролей} other {# роли}}", + "accessUsersRoleFilterClear": "Очистить фильтры ролей", "accessUserCreate": "Создать пользователя", "accessUserRemove": "Удалить пользователя", "username": "Имя пользователя", @@ -371,7 +386,7 @@ "provisioningKeysUpdated": "Ключ подготовки обновлен", "provisioningKeysUpdatedDescription": "Ваши изменения были сохранены.", "provisioningKeysBannerTitle": "Ключи подготовки сайта", - "provisioningKeysBannerDescription": "Создайте ключ настройки и используйте его с соединителем Newt для автоматического создания сайтов при первом запуске — нет необходимости настраивать отдельные учетные данные для каждого сайта.", + "provisioningKeysBannerDescription": "Создайте ключ настройки и используйте его с соединителем Newt для автоматического создания сайтов при первом запуске - нет необходимости настраивать отдельные учетные данные для каждого сайта.", "provisioningKeysBannerButtonText": "Узнать больше", "pendingSitesBannerTitle": "Ожидающие сайты", "pendingSitesBannerDescription": "Сайты, подключающиеся с помощью ключа настройки, отображаются здесь для проверки.", @@ -1257,6 +1272,7 @@ "actionViewLogs": "Просмотр журналов", "noneSelected": "Ничего не выбрано", "orgNotFound2": "Организации не найдены.", + "search": "Поиск…", "searchPlaceholder": "Поиск...", "emptySearchOptions": "Опции не найдены", "create": "Создать", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "Управление", "sidebarLogAndAnalytics": "Журнал и аналитика", "sidebarBluePrints": "Чертежи", + "sidebarAlerting": "Оповещения", + "sidebarHealthChecks": "Проверки здоровья", "sidebarOrganization": "Организация", "sidebarManagement": "Управление", "sidebarBillingAndLicenses": "Биллинг и лицензии", "sidebarLogsAnalytics": "Статистика", + "alertingTitle": "Оповещения", + "alertingDescription": "Определите источники, триггеры и действия для уведомлений", + "alertingRules": "Правила оповещений", + "alertingSearchRules": "Поиск правил…", + "alertingAddRule": "Создать правило", + "alertingColumnSource": "Источник", + "alertingColumnTrigger": "Триггер", + "alertingColumnActions": "Действия", + "alertingColumnEnabled": "Включено", + "alertingDeleteQuestion": "Пожалуйста, подтвердите удаление этого правила оповещений.", + "alertingDeleteRule": "Удалить правило оповещений", + "alertingRuleDeleted": "Правило оповещений удалено", + "alertingRuleSaved": "Правило оповещений сохранено", + "alertingRuleSavedCreatedDescription": "Ваше новое правило оповещений создано. Вы можете продолжать редактировать его на этой странице.", + "alertingRuleSavedUpdatedDescription": "Ваши изменения в этом правиле оповещений были сохранены.", + "alertingEditRule": "Редактировать правило оповещений", + "alertingCreateRule": "Создать правило оповещений", + "alertingRuleCredenzaDescription": "Выберите, что отслеживать, когда срабатывать и как уведомлять", + "alertingRuleNamePlaceholder": "Рабочий сайт не доступен", + "alertingRuleEnabled": "Правило включено", + "alertingSectionSource": "Источник", + "alertingSourceType": "Тип источника", + "alertingSourceSite": "Сайт", + "alertingSourceHealthCheck": "Проверка здоровья", + "alertingPickSites": "Сайты", + "alertingPickHealthChecks": "Проверки здоровья", + "alertingPickResources": "Ресурсы", + "alertingAllSites": "Все сайты", + "alertingAllSitesDescription": "Оповещение срабатывает на любом сайте", + "alertingSpecificSites": "Конкретные сайты", + "alertingSpecificSitesDescription": "Выберите конкретные сайты для отслеживания", + "alertingAllHealthChecks": "Все проверки здоровья", + "alertingAllHealthChecksDescription": "Оповещение срабатывает на любой проверке здоровья", + "alertingSpecificHealthChecks": "Конкретные проверки здоровья", + "alertingSpecificHealthChecksDescription": "Выберите конкретные проверки здоровья для отслеживания", + "alertingAllResources": "Все ресурсы", + "alertingAllResourcesDescription": "Оповещение срабатывает на любом ресурсе", + "alertingSpecificResources": "Конкретные ресурсы", + "alertingSpecificResourcesDescription": "Выберите конкретные ресурсы для отслеживания", + "alertingSelectResources": "Выберите ресурсы…", + "alertingResourcesSelected": "Выбрано {count} ресурсов", + "alertingResourcesEmpty": "Нет ресурсов с целью в первых 10 результатах.", + "alertingSectionTrigger": "Триггер", + "alertingTrigger": "Когда оповестить", + "alertingTriggerSiteOnline": "Сайт онлайн", + "alertingTriggerSiteOffline": "Сайт офлайн", + "alertingTriggerSiteToggle": "Статус сайта изменяется", + "alertingTriggerHcHealthy": "Проверка здоровья успешна", + "alertingTriggerHcUnhealthy": "Проверка здоровья не успешна", + "alertingTriggerHcToggle": "Статус проверки здоровья изменяется", + "alertingTriggerResourceHealthy": "Ресурс в нормальном состоянии", + "alertingTriggerResourceUnhealthy": "Ресурс в ненормальном состоянии", + "alertingSearchHealthChecks": "Поиск проверок здоровья…", + "alertingHealthChecksEmpty": "Нет доступных проверок здоровья.", + "alertingTriggerResourceToggle": "Статус ресурса изменяется", + "alertingSourceResource": "Ресурс", + "alertingSectionActions": "Действия", + "alertingAddAction": "Добавить действие", + "alertingActionNotify": "Электронная почта", + "alertingActionNotifyDescription": "Отправляйте email уведомления пользователям или ролям", + "alertingActionWebhook": "Веб-хук", + "alertingActionWebhookDescription": "Отправьте HTTP-запрос на пользовательскую конечную точку", + "alertingExternalIntegration": "Внешняя интеграция", + "alertingExternalPagerDutyDescription": "Отправляйте оповещения в PagerDuty для управления инцидентами", + "alertingExternalOpsgenieDescription": "Маршрутизируйте оповещения в Opsgenie для управления дежурной службой", + "alertingExternalServiceNowDescription": "Создавайте инциденты ServiceNow из событий оповещений", + "alertingExternalIncidentIoDescription": "Запускайте рабочие процессы Incident.io из событий оповещений", + "alertingActionType": "Тип действия", + "alertingNotifyUsers": "Пользователи", + "alertingNotifyRoles": "Роли", + "alertingNotifyEmails": "Email адреса", + "alertingEmailPlaceholder": "Добавьте email и нажмите Enter", + "alertingWebhookMethod": "HTTP метод", + "alertingWebhookSecret": "Секрет подписания (необязательно)", + "alertingWebhookSecretPlaceholder": "HMAC секрет", + "alertingWebhookHeaders": "Заголовки", + "alertingAddHeader": "Добавить заголовок", + "alertingSelectSites": "Выберите сайты…", + "alertingSitesSelected": "Выбрано {count} сайтов", + "alertingSelectHealthChecks": "Выберите проверки здоровья…", + "alertingHealthChecksSelected": "Выбрано {count} проверок здоровья", + "alertingNoHealthChecks": "Цели без включенных проверок здоровья отсутствуют", + "alertingHealthCheckStub": "Выбор источника проверки здоровья ещё не подключён - вы все ещё можете настроить триггеры и действия.", + "alertingSelectUsers": "Выберите пользователей…", + "alertingUsersSelected": "Выбрано {count} пользователей", + "alertingSelectRoles": "Выберите роли…", + "alertingRolesSelected": "Выбрано {count} ролей", + "alertingSummarySites": "Сайты ({count})", + "alertingSummaryAllSites": "Все сайты", + "alertingSummaryHealthChecks": "Проверки здоровья ({count})", + "alertingSummaryAllHealthChecks": "Все проверки здоровья", + "alertingSummaryResources": "Ресурсы ({count})", + "alertingSummaryAllResources": "Все ресурсы", + "alertingErrorNameRequired": "Введите название", + "alertingErrorActionsMin": "Добавьте как минимум одно действие", + "alertingErrorPickSites": "Выберите как минимум один сайт", + "alertingErrorPickHealthChecks": "Выберите как минимум одну проверку здоровья", + "alertingErrorPickResources": "Выберите как минимум один ресурс", + "alertingErrorTriggerSite": "Выберите триггер сайта", + "alertingErrorTriggerHealth": "Выберите триггер проверки здоровья", + "alertingErrorTriggerResource": "Выберите триггер ресурса", + "alertingErrorNotifyRecipients": "Выберите пользователей, роли или как минимум один email", + "alertingConfigureSource": "Настроить источник", + "alertingConfigureTrigger": "Настроить триггер", + "alertingConfigureActions": "Настроить действия", + "alertingBackToRules": "Назад к правилам", + "alertingRuleCooldown": "Охлаждение (секунды)", + "alertingRuleCooldownDescription": "Минимальное время между повторными оповещениями для одного и того же правила. Установите 0 для каждого вызова.", + "alertingDraftBadge": "Черновик - сохраните, чтобы сохранить это правило", + "alertingSidebarHint": "Кликните по шагу на холсте, чтобы редактировать его здесь.", + "alertingGraphCanvasTitle": "Поток правил", + "alertingGraphCanvasDescription": "Визуальный обзор источника, триггера и действий. Выберите узел, чтобы редактировать его в панели.", + "alertingNodeNotConfigured": "Ещё не настроено", + "alertingNodeActionsCount": "{count, plural, one {# действие} few {# действия} many {# действий} other {# действий}}", + "alertingNodeRoleSource": "Источник", + "alertingNodeRoleTrigger": "Триггер", + "alertingNodeRoleAction": "Действие", + "alertingTabRules": "Правила оповещений", + "alertingTabHealthChecks": "Проверки здоровья", + "alertingRulesBannerTitle": "Получить уведомление", + "alertingRulesBannerDescription": "Каждое правило объединяет, что отслеживать (сайт, проверка состояния или ресурс), когда срабатывать (например, оффлайн или нарушение), и как уведомлять вашу команду через email, вебхуки или интеграции. Используйте этот список для создания, включения и управления этими правилами.", + "alertingHealthChecksBannerTitle": "Мониторинг здоровья и ресурсов", + "alertingHealthChecksBannerDescription": "Проверки здоровья — это HTTP или TCP мониторы, которые вы определяете один раз. Затем вы можете использовать их в правилах оповещений, чтобы получать уведомления, когда цель становится здоровой или нездоровой. Проверки здоровья для ресурсов также появляются здесь.", + "standaloneHcTableTitle": "Проверки здоровья", + "standaloneHcSearchPlaceholder": "Поиск проверок здоровья…", + "standaloneHcAddButton": "Создать проверку здоровья", + "standaloneHcCreateTitle": "Создать проверку здоровья", + "standaloneHcEditTitle": "Редактировать проверку здоровья", + "standaloneHcDescription": "Настройте проверку здоровья HTTP или TCP для использования в правилах оповещений.", + "standaloneHcNameLabel": "Имя", + "standaloneHcNamePlaceholder": "Мой HTTP монитор", + "standaloneHcDeleteTitle": "Удалить проверку здоровья", + "standaloneHcDeleteQuestion": "Пожалуйста, подтвердите удаление этой проверки здоровья.", + "standaloneHcDeleted": "Проверка здоровья удалена", + "standaloneHcSaved": "Проверка здоровья сохранена", + "standaloneHcColumnHealth": "Здоровье", + "standaloneHcColumnMode": "Режим", + "standaloneHcColumnTarget": "Цель", + "standaloneHcHealthStateHealthy": "Здоровый", + "standaloneHcHealthStateUnhealthy": "Нездоровый", + "standaloneHcHealthStateUnknown": "Неизвестно", + "standaloneHcFilterAnySite": "Все сайты", + "standaloneHcFilterAnyResource": "Все ресурсы", + "standaloneHcFilterMode": "Режим", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "Пинг", + "standaloneHcFilterHealth": "Здоровье", + "standaloneHcFilterEnabled": "Включено", + "standaloneHcFilterEnabledOn": "Включено", + "standaloneHcFilterEnabledOff": "Отключено", + "standaloneHcFilterSiteIdFallback": "Сайт {id}", + "standaloneHcFilterResourceIdFallback": "Ресурс {id}", "blueprints": "Чертежи", "blueprintsDescription": "Применить декларирующие конфигурации и просмотреть предыдущие запуски", "blueprintAdd": "Добавить чертёж", @@ -1763,6 +1935,15 @@ "healthCheckIntervalMin": "Интервал проверки должен составлять не менее 5 секунд", "healthCheckTimeoutMin": "Тайм-аут должен составлять не менее 1 секунды", "healthCheckRetryMin": "Количество попыток должно быть не менее 1", + "healthCheckMode": "Режим проверки", + "healthCheckStrategy": "Стратегия", + "healthCheckModeDescription": "Режим TCP проверяет только возможность подключения. Режим HTTP проверяет ответ HTTP.", + "healthyThreshold": "Порог здорового состояния", + "healthyThresholdDescription": "Последовательные успехи, необходимые перед тем, как пометить как здоровый.", + "unhealthyThreshold": "Порог нездорового состояния", + "unhealthyThresholdDescription": "Последовательные неудачи, необходимые перед тем, как пометить как нездоровый.", + "healthCheckHealthyThresholdMin": "Порог здорового состояния должен быть не менее 1", + "healthCheckUnhealthyThresholdMin": "Порог нездорового состояния должен быть не менее 1", "httpMethod": "HTTP метод", "selectHttpMethod": "Выберите HTTP метод", "domainPickerSubdomainLabel": "Поддомен", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "Порт", "editInternalResourceDialogModeHost": "Хост", "editInternalResourceDialogModeCidr": "СИДР", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "Схема", + "editInternalResourceDialogEnableSsl": "Включить SSL", + "editInternalResourceDialogEnableSslDescription": "Включите шифрование SSL/TLS для защищенных HTTPS соединений с конечной точкой.", "editInternalResourceDialogDestination": "Пункт назначения", "editInternalResourceDialogDestinationHostDescription": "IP адрес или имя хоста ресурса в сети сайта.", "editInternalResourceDialogDestinationIPDescription": "IP или адрес хоста ресурса в сети сайта.", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "Имя", "createInternalResourceDialogSite": "Сайт", "selectSite": "Выберите сайт...", + "multiSitesSelectorSitesCount": "{count, plural, one {# сайт} few {# сайта} many {# сайтов} other {# сайтов}}", "noSitesFound": "Сайты не найдены.", "createInternalResourceDialogProtocol": "Протокол", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "Порт", "createInternalResourceDialogModeHost": "Хост", "createInternalResourceDialogModeCidr": "СИДР", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "Схема", + "createInternalResourceDialogScheme": "Схема", + "createInternalResourceDialogEnableSsl": "Включить SSL", + "createInternalResourceDialogEnableSslDescription": "Включите SSL/TLS шифрование для защищенных HTTPS соединений с конечной точкой.", "createInternalResourceDialogDestination": "Пункт назначения", "createInternalResourceDialogDestinationHostDescription": "IP адрес или имя хоста ресурса в сети сайта.", "createInternalResourceDialogDestinationCidrDescription": "Диапазон CIDR ресурса в сети сайта.", "createInternalResourceDialogAlias": "Alias", "createInternalResourceDialogAliasDescription": "Дополнительный внутренний DNS псевдоним для этого ресурса.", + "internalResourceDownstreamSchemeRequired": "Схема обязательна для HTTP ресурсов", + "internalResourceHttpPortRequired": "Порт назначения обязателен для HTTP ресурсов", "siteConfiguration": "Конфигурация", "siteAcceptClientConnections": "Принимать подключения клиентов", "siteAcceptClientConnectionsDescription": "Разрешить пользовательским устройствам и клиентам доступ к ресурсам на этом сайте. Это может быть изменено позже.", @@ -1994,7 +2189,7 @@ "description": "Более надежный и низко обслуживаемый сервер Pangolin с дополнительными колокольнями и свистками", "introTitle": "Управляемый Само-Хост Панголина", "introDescription": "- это вариант развертывания, предназначенный для людей, которые хотят простоты и надёжности, сохраняя при этом свои данные конфиденциальными и самостоятельными.", - "introDetail": "С помощью этой опции вы по-прежнему используете узел Pangolin — туннели, SSL, и весь остающийся на вашем сервере. Разница заключается в том, что управление и мониторинг осуществляются через нашу панель инструментов из облака, которая открывает ряд преимуществ:", + "introDetail": "С помощью этой опции вы по-прежнему используете узел Pangolin - туннели, SSL, и весь остающийся на вашем сервере. Разница заключается в том, что управление и мониторинг осуществляются через нашу панель инструментов из облака, которая открывает ряд преимуществ:", "benefitSimplerOperations": { "title": "Более простые операции", "description": "Не нужно запускать свой собственный почтовый сервер или настроить комплексное оповещение. Вы будете получать проверки состояния здоровья и оповещения о неисправностях из коробки." @@ -2119,7 +2314,7 @@ "selectDomainForOrgAuthPage": "Выберите домен для страницы аутентификации организации", "domainPickerProvidedDomain": "Домен предоставлен", "domainPickerFreeProvidedDomain": "Бесплатный домен", - "domainPickerFreeDomainsPaidFeature": "Предоставленные домены являются платной функцией. Подпишитесь, чтобы получить домен, включенный в ваш план — не нужно приносить свой собственный.", + "domainPickerFreeDomainsPaidFeature": "Предоставленные домены являются платной функцией. Подпишитесь, чтобы получить домен, включенный в ваш план - не нужно приносить свой собственный.", "domainPickerVerified": "Подтверждено", "domainPickerUnverified": "Не подтверждено", "domainPickerManual": "Ручной", @@ -2297,7 +2492,7 @@ "alerts": { "commercialUseDisclosure": { "title": "Раскрытие", - "description": "Выберите уровень лицензии, который точно отражает ваше предполагаемое использование. Личная Лицензия разрешает свободное использование Программного Обеспечения для частной, некоммерческой или малой коммерческой деятельности с годовым валовым доходом до $100 000 USD. Любое использование сверх этих пределов — включая использование в бизнесе, организацию, или другой приносящей доход среде — требует действительной лицензии предприятия и уплаты соответствующей лицензионной платы. Все пользователи, будь то Личные или Предприятия, обязаны соблюдать условия коммерческой лицензии Fossoral." + "description": "Выберите уровень лицензии, который точно отражает ваше предполагаемое использование. Личная Лицензия разрешает свободное использование Программного Обеспечения для частной, некоммерческой или малой коммерческой деятельности с годовым валовым доходом до $100 000 USD. Любое использование сверх этих пределов - включая использование в бизнесе, организацию, или другой приносящей доход среде - требует действительной лицензии предприятия и уплаты соответствующей лицензионной платы. Все пользователи, будь то Личные или Предприятия, обязаны соблюдать условия коммерческой лицензии Fossoral." }, "trialPeriodInformation": { "title": "Информация о пробном периоде", @@ -2429,6 +2624,7 @@ "validPassword": "Допустимый пароль", "validEmail": "Valid email", "validSSO": "Valid SSO", + "connectedClient": "Подключенный клиент", "resourceBlocked": "Ресурс заблокирован", "droppedByRule": "Отброшено по правилам", "noSessions": "Нет сессий", @@ -2668,6 +2864,10 @@ "editInternalResourceDialogDestinationLabel": "Пункт назначения", "editInternalResourceDialogDestinationDescription": "Укажите адрес назначения для внутреннего ресурса. Это может быть имя хоста, IP-адрес или диапазон CIDR в зависимости от выбранного режима. При необходимости установите внутренний DNS-алиас для облегчения идентификации.", "editInternalResourceDialogPortRestrictionsDescription": "Ограничьте доступ к определенным TCP/UDP-портам или разрешите/заблокируйте все порты.", + "createInternalResourceDialogHttpConfiguration": "Конфигурация HTTP", + "createInternalResourceDialogHttpConfigurationDescription": "Выберите домен, который клиенты будут использовать для доступа к этому ресурсу через HTTP или HTTPS.", + "editInternalResourceDialogHttpConfiguration": "Конфигурация HTTP", + "editInternalResourceDialogHttpConfigurationDescription": "Выберите домен, который клиенты будут использовать для доступа к этому ресурсу через HTTP или HTTPS.", "editInternalResourceDialogTcp": "TCP", "editInternalResourceDialogUdp": "UDP", "editInternalResourceDialogIcmp": "ICMP", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "Мы скоро вернемся! Наш сайт в настоящее время проходит плановое техническое обслуживание.", "maintenancePageMessageDescription": "Подробное сообщение, объясняющее обслуживание", "maintenancePageTimeTitle": "Предполагаемое время завершения (необязательно)", + "privateMaintenanceScreenTitle": "Экраны частной заглушки", + "privateMaintenanceScreenMessage": "Этот домен используется на частном ресурсе. Пожалуйста, подключитесь с помощью клиента Pangolin для доступа к этому ресурсу.", "maintenanceTime": "например, 2 часа, 1 ноября в 5:00 вечера", "maintenanceEstimatedTimeDescription": "Когда вы ожидаете завершения обслуживания", "editDomain": "Редактировать домен", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "Добавить HTTP адрес", "httpDestEditDescription": "Обновление конфигурации для этого HTTP события потокового назначения.", "httpDestAddDescription": "Настройте новую HTTP-конечную точку для получения событий вашей организации.", + "S3DestEditTitle": "Редактировать пункт назначения", + "S3DestAddTitle": "Добавить S3 пункт назначения", + "S3DestEditDescription": "Обновите конфигурацию для этого S3 пункта назначения потоковых событий.", + "S3DestAddDescription": "Настройте новую S3 конечную точку для получения событий вашей организации.", + "datadogDestEditTitle": "Редактировать пункт назначения", + "datadogDestAddTitle": "Добавить пункт назначения Datadog", + "datadogDestEditDescription": "Обновите конфигурацию для этого пункта назначения потоковых событий Datadog.", + "datadogDestAddDescription": "Настройте новую конечную точку Datadog для получения событий вашей организации.", "httpDestTabSettings": "Настройки", "httpDestTabHeaders": "Заголовки", "httpDestTabBody": "Тело", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "Адрес назначения успешно создан", "httpDestUpdateFailed": "Не удалось обновить место назначения", "httpDestCreateFailed": "Не удалось создать место назначения", + "followRedirects": "Следовать за перенаправлениями", + "followRedirectsDescription": "Автоматически следуйте HTTP перенаправлениям для запросов.", + "alertingErrorWebhookUrl": "Пожалуйста, введите корректный URL для вебхука.", + "healthCheckStrategyHttp": "Проверяет возможность подключения и проверяет статус HTTP ответа.", + "healthCheckStrategyTcp": "Проверяет только подключение TCP, не инспектируя ответ.", + "healthCheckStrategySnmp": "Выполняет SNMP get-запрос, чтобы проверить состояние сетевых устройств и инфраструктуры.", + "healthCheckStrategyIcmp": "Использует эхо-запросы ICMP (ping), чтобы проверить, доступен ли и отзывчив ли ресурс.", + "healthCheckTabStrategy": "Стратегия", + "healthCheckTabConnection": "Подключение", + "healthCheckTabAdvanced": "Дополнительно", + "healthCheckStrategyNotAvailable": "Эта стратегия недоступна. Пожалуйста, свяжитесь с отделом продаж для включения этой функции.", + "uptime30d": "Время работы (30 дней)", "idpAddActionCreateNew": "Создать нового поставщика удостоверений", "idpAddActionImportFromOrg": "Импортировать из другой организации", "idpImportDialogTitle": "Импортировать поставщика удостоверений", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "Это не может быть отменено для этой организации.", "idpUnassociatedDescription": "Поставщик удостоверений успешно рассоединен с этой организацией", "idpUnassociateMenu": "Рассоединить", - "idpDeleteAllOrgsMenu": "Удалить" + "idpDeleteAllOrgsMenu": "Удалить", + "publicIpEndpoint": "Конечная точка", + "lastTriggeredAt": "Последний триггер", + "reject": "Отклонить" } diff --git a/messages/tr-TR.json b/messages/tr-TR.json index 3055d6597..b7b3c877c 100644 --- a/messages/tr-TR.json +++ b/messages/tr-TR.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "Bu özelliği etkinleştirmek için satış ekibiyle iletişime geçin.", + "contactSalesBookDemo": "Demo ayırt", + "contactSalesOr": "veya", + "contactSalesContactUs": "bize ulaşın", "setupCreate": "Organizasyonu, siteyi ve kaynakları oluşturun", "headerAuthCompatibilityInfo": "Kimlik doğrulama belirteci eksik olduğunda 401 Yetkisiz yanıtı zorlamak için bunu etkinleştirin. Bu, sunucu sorunu olmadan kimlik bilgilerini göndermeyen tarayıcılar veya belirli HTTP kütüphaneleri için gereklidir.", "headerAuthCompatibility": "Genişletilmiş Uyumluluk", @@ -19,6 +23,14 @@ "componentsInvalidKey": "Geçersiz veya süresi dolmuş lisans anahtarları tespit edildi. Tüm özellikleri kullanmaya devam etmek için lisans koşullarına uyun.", "dismiss": "Kapat", "subscriptionViolationMessage": "Geçerli planınız için limitlerinizi aştınız. Planınız dahilinde kalmak için siteleri, kullanıcıları veya diğer kaynakları kaldırarak sorunu düzeltin.", + "trialBannerMessage": "Deneme süreniz {countdown} içinde sona eriyor. Erişimi sürdürmek için yükseltin.", + "trialBannerExpired": "Deneme süreniz sona erdi. Erişimi geri yüklemek için şimdi yükseltin.", + "trialActive": "Ücretsiz Deneme Aktif", + "trialExpired": "Deneme Süresi Doldu", + "trialHasEnded": "Deneme süreniz sona erdi.", + "trialDaysRemaining": "{count, plural, one {# gün kaldı} other {# gün kaldı}}", + "trialDaysLeftShort": "Deneme süresi için {days}g kaldı", + "trialGoToBilling": "Fatura sayfasına git", "subscriptionViolationViewBilling": "Faturalamayı görüntüle", "componentsLicenseViolation": "Lisans İhlali: Bu sunucu, lisanslı sınırı olan {maxSites} sitesini aşarak {usedSites} site kullanmaktadır. Tüm özellikleri kullanmaya devam etmek için lisans koşullarına uyun.", "componentsSupporterMessage": "Pangolin'e {tier} olarak destek olduğunuz için teşekkür ederiz!", @@ -267,8 +279,11 @@ "orgMissing": "Organizasyon Kimliği Eksik", "orgMissingMessage": "Organizasyon kimliği olmadan daveti yeniden oluşturmanız mümkün değildir.", "accessUsersManage": "Kullanıcıları Yönet", + "accessUserManage": "Kullanıcıyı Yönet", "accessUsersDescription": "Bu organizasyona erişimi olan kullanıcıları davet edin ve yönetin", "accessUsersSearch": "Kullanıcıları ara...", + "accessUsersRoleFilterCount": "{count, plural, one {# rol} other {# roller}}", + "accessUsersRoleFilterClear": "Rol filtrelerini temizle", "accessUserCreate": "Kullanıcı Oluştur", "accessUserRemove": "Kullanıcıyı Kaldır", "username": "Kullanıcı Adı", @@ -1257,6 +1272,7 @@ "actionViewLogs": "Kayıtları Görüntüle", "noneSelected": "Hiçbiri seçili değil", "orgNotFound2": "Hiçbir organizasyon bulunamadı.", + "search": "Ara…", "searchPlaceholder": "Ara...", "emptySearchOptions": "Seçenek bulunamadı", "create": "Oluştur", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "Yönet", "sidebarLogAndAnalytics": "Kayıt & Analiz", "sidebarBluePrints": "Planlar", + "sidebarAlerting": "Uyarı", + "sidebarHealthChecks": "Sağlık kontrolleri", "sidebarOrganization": "Organizasyon", "sidebarManagement": "Yönetim", "sidebarBillingAndLicenses": "Faturalandırma & Lisanslar", "sidebarLogsAnalytics": "Analitik", + "alertingTitle": "Uyarı", + "alertingDescription": "Bildirimler için kaynakları, tetikleyicileri ve eylemleri tanımlayın", + "alertingRules": "Uyarı kuralları", + "alertingSearchRules": "Kuralları ara…", + "alertingAddRule": "Kural Oluştur", + "alertingColumnSource": "Kaynak", + "alertingColumnTrigger": "Tetikle", + "alertingColumnActions": "İşlemler", + "alertingColumnEnabled": "Etkin", + "alertingDeleteQuestion": "Bu uyarı kuralını silmek istediğinizi onaylayın lütfen.", + "alertingDeleteRule": "Uyarı kuralını sil", + "alertingRuleDeleted": "Uyarı kuralı silindi", + "alertingRuleSaved": "Uyarı kuralı kaydedildi", + "alertingRuleSavedCreatedDescription": "Yeni uyarı kuralınız oluşturuldu. Bu sayfada düzenlemeye devam edebilirsiniz.", + "alertingRuleSavedUpdatedDescription": "Bu uyarı kuralındaki değişiklikleriniz kaydedildi.", + "alertingEditRule": "Uyarı Kuralını Düzenle", + "alertingCreateRule": "Uyarı Kuralı Oluştur", + "alertingRuleCredenzaDescription": "Ne izlenecek, ne zaman tetiklenecek ve nasıl bildirilecek, bunları seçin", + "alertingRuleNamePlaceholder": "Üretim sitesi kapalı", + "alertingRuleEnabled": "Kural etkinleştirildi", + "alertingSectionSource": "Kaynak", + "alertingSourceType": "Kaynak türü", + "alertingSourceSite": "Site", + "alertingSourceHealthCheck": "Sağlık kontrolü", + "alertingPickSites": "Siteler", + "alertingPickHealthChecks": "Sağlık kontrolleri", + "alertingPickResources": "Kaynaklar", + "alertingAllSites": "Tüm Siteler", + "alertingAllSitesDescription": "Herhangi bir site için uyarı tetiklenir", + "alertingSpecificSites": "Belirli Siteler", + "alertingSpecificSitesDescription": "İzlemek için belirli siteleri seçin", + "alertingAllHealthChecks": "Tüm Sağlık Kontrolleri", + "alertingAllHealthChecksDescription": "Herhangi bir sağlık kontrolü için uyarı tetiklenir", + "alertingSpecificHealthChecks": "Belirli Sağlık Kontrolleri", + "alertingSpecificHealthChecksDescription": "İzlemek için belirli sağlık kontrollerini seçin", + "alertingAllResources": "Tüm Kaynaklar", + "alertingAllResourcesDescription": "Herhangi bir kaynak için uyarı tetiklenir", + "alertingSpecificResources": "Belirli Kaynaklar", + "alertingSpecificResourcesDescription": "İzlemek için belirli kaynakları seçin", + "alertingSelectResources": "Kaynakları seçin…", + "alertingResourcesSelected": "{count} kaynak seçildi", + "alertingResourcesEmpty": "İlk 10 sonuçta hedefleri olan kaynak yok.", + "alertingSectionTrigger": "Tetikle", + "alertingTrigger": "Uyarı zamanı", + "alertingTriggerSiteOnline": "Site çevrimiçi", + "alertingTriggerSiteOffline": "Site çevrimdışı", + "alertingTriggerSiteToggle": "Site durumu değişiyor", + "alertingTriggerHcHealthy": "Sağlık kontrolü sağlıklı", + "alertingTriggerHcUnhealthy": "Sağlık kontrolü sağlıksız", + "alertingTriggerHcToggle": "Sağlık kontrolü durumu değişiyor", + "alertingTriggerResourceHealthy": "Kaynak sağlıklı", + "alertingTriggerResourceUnhealthy": "Kaynak sağlıksız", + "alertingSearchHealthChecks": "Sağlık kontrollerini ara…", + "alertingHealthChecksEmpty": "Mevcut sağlık kontrolü yok.", + "alertingTriggerResourceToggle": "Kaynak durumu değişiyor", + "alertingSourceResource": "Kaynak", + "alertingSectionActions": "İşlemler", + "alertingAddAction": "Eylem Ekle", + "alertingActionNotify": "E-posta", + "alertingActionNotifyDescription": "Kullanıcılara veya role e-posta bildirimleri gönder", + "alertingActionWebhook": "Webhook", + "alertingActionWebhookDescription": "Özel bir uç noktaya HTTP isteği gönderin", + "alertingExternalIntegration": "Harici Entegrasyon", + "alertingExternalPagerDutyDescription": "Olay yönetimi için uyarıları PagerDuty'ye gönderin", + "alertingExternalOpsgenieDescription": "Nöbetçi yönetimi için uyarıları Opsgenie'ye yönlendirin", + "alertingExternalServiceNowDescription": "Uyarı olaylarından ServiceNow olayları oluşturun", + "alertingExternalIncidentIoDescription": "Uyarı olaylarından Incident.io iş akışlarını tetikleyin", + "alertingActionType": "Eylem türü", + "alertingNotifyUsers": "Kullanıcılar", + "alertingNotifyRoles": "Roller", + "alertingNotifyEmails": "E-posta adresleri", + "alertingEmailPlaceholder": "E-posta ekleyin ve Enter tuşuna basın", + "alertingWebhookMethod": "HTTP yöntemi", + "alertingWebhookSecret": "İmza sırrı (isteğe bağlı)", + "alertingWebhookSecretPlaceholder": "HMAC sırrı", + "alertingWebhookHeaders": "Başlıklar", + "alertingAddHeader": "Başlık ekle", + "alertingSelectSites": "Siteleri seçin…", + "alertingSitesSelected": "{count} site seçildi", + "alertingSelectHealthChecks": "Sağlık kontrolleri seçin…", + "alertingHealthChecksSelected": "{count} sağlık kontrolü seçildi", + "alertingNoHealthChecks": "Hedefleri etkinleştirilmiş sağlık kontrolleri yok", + "alertingHealthCheckStub": "Sağlık kontrolü kaynak seçimi henüz bağlanmadı - yine de tetikleyicileri ve eylemleri yapılandırabilirsiniz.", + "alertingSelectUsers": "Kullanıcıları seçin…", + "alertingUsersSelected": "{count} kullanıcı seçildi", + "alertingSelectRoles": "Rolleri seçin…", + "alertingRolesSelected": "{count} rol seçildi", + "alertingSummarySites": "Siteler ({count})", + "alertingSummaryAllSites": "Tüm siteler", + "alertingSummaryHealthChecks": "Sağlık kontrolleri ({count})", + "alertingSummaryAllHealthChecks": "Tüm sağlık kontrolleri", + "alertingSummaryResources": "Kaynaklar ({count})", + "alertingSummaryAllResources": "Tüm kaynaklar", + "alertingErrorNameRequired": "Bir ad girin", + "alertingErrorActionsMin": "En az bir eylem ekleyin", + "alertingErrorPickSites": "En az bir site seçin", + "alertingErrorPickHealthChecks": "En az bir sağlık kontrolü seçin", + "alertingErrorPickResources": "En az bir kaynak seçin", + "alertingErrorTriggerSite": "Bir site tetikleyicisi seçin", + "alertingErrorTriggerHealth": "Bir sağlık kontrolü tetikleyicisi seçin", + "alertingErrorTriggerResource": "Bir kaynak tetikleyicisi seçin", + "alertingErrorNotifyRecipients": "Kullanıcıları, rolleri veya en az bir e-posta seçin", + "alertingConfigureSource": "Kaynağı Yapılandır", + "alertingConfigureTrigger": "Tetikleyiciyi Yapılandır", + "alertingConfigureActions": "Eylemleri Yapılandır", + "alertingBackToRules": "Kurallara Geri Dön", + "alertingRuleCooldown": "Serinleme süresi (saniye)", + "alertingRuleCooldownDescription": "Aynı kural için tekrarlanan uyarılar arasında minimum süre. Her seferinde tetiklenmesi için 0 olarak ayarlayın.", + "alertingDraftBadge": "Taslak - bu kuralı kaydetmek için kaydedin", + "alertingSidebarHint": "Düzenlemek için kanvas üzerindeki bir adıma tıklayın.", + "alertingGraphCanvasTitle": "Kural Akışı", + "alertingGraphCanvasDescription": "Kaynak, tetikleyici ve eylemlerin görsel genel bakışı. Düzenlemek için bir düğümü seçin.", + "alertingNodeNotConfigured": "Henüz yapılandırılmadı", + "alertingNodeActionsCount": "{count, plural, one {# eylem} other {# eylemler}}", + "alertingNodeRoleSource": "Kaynak", + "alertingNodeRoleTrigger": "Tetikle", + "alertingNodeRoleAction": "Aksiyon", + "alertingTabRules": "Uyarı Kuralları", + "alertingTabHealthChecks": "Sağlık Kontrolleri", + "alertingRulesBannerTitle": "Bildirim Alın", + "alertingRulesBannerDescription": "Her kural neyin izleneceğini (bir site, sağlık kontrolü veya kaynak), ne zaman tetikleneceğini (örneğin çevrimdışı veya sağlıksız) ve ekibinize e-posta, web kancaları veya entegrasyonlar aracılığıyla nasıl bildirileceğini bağlar. Bu listeyi kullanarak kuralları oluşturun, etkinleştirin ve yönetin.", + "alertingHealthChecksBannerTitle": "Sağlık ve Kaynakları İzleyin", + "alertingHealthChecksBannerDescription": "Sağlık kontrolleri bir kez tanımladığınız HTTP veya TCP monitörleridir. Ardından hedef sağlıklı veya sağlıksız olduğunda bildirilmeniz için onları uyarı kurallarında kaynak olarak kullanabilirsiniz. Kaynaklar üzerindeki sağlık kontrolleri de burada görünür.", + "standaloneHcTableTitle": "Sağlık Kontrolleri", + "standaloneHcSearchPlaceholder": "Sağlık kontrollerini ara…", + "standaloneHcAddButton": "Sağlık Kontrolü Oluştur", + "standaloneHcCreateTitle": "Sağlık Kontrolü Oluştur", + "standaloneHcEditTitle": "Sağlık Kontrolünü Düzenle", + "standaloneHcDescription": "Uyarı kurallarında kullanılmak üzere bir HTTP veya TCP sağlık kontrolü yapılandırın.", + "standaloneHcNameLabel": "Ad", + "standaloneHcNamePlaceholder": "HTTP Monitörüm", + "standaloneHcDeleteTitle": "Sağlık kontrolünü sil", + "standaloneHcDeleteQuestion": "Bu sağlık kontrolünü silmek istediğinizi onaylayın lütfen.", + "standaloneHcDeleted": "Sağlık kontrolü silindi", + "standaloneHcSaved": "Sağlık kontrolü kaydedildi", + "standaloneHcColumnHealth": "Sağlık", + "standaloneHcColumnMode": "Mod", + "standaloneHcColumnTarget": "Hedef", + "standaloneHcHealthStateHealthy": "Sağlıklı", + "standaloneHcHealthStateUnhealthy": "Sağlıksız", + "standaloneHcHealthStateUnknown": "Bilinmiyor", + "standaloneHcFilterAnySite": "Tüm siteler", + "standaloneHcFilterAnyResource": "Tüm kaynaklar", + "standaloneHcFilterMode": "Mod", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "Ping", + "standaloneHcFilterHealth": "Sağlık", + "standaloneHcFilterEnabled": "Etkin", + "standaloneHcFilterEnabledOn": "Etkin", + "standaloneHcFilterEnabledOff": "Devre Dışı", + "standaloneHcFilterSiteIdFallback": "Site {id}", + "standaloneHcFilterResourceIdFallback": "Kaynak {id}", "blueprints": "Planlar", "blueprintsDescription": "Deklaratif yapılandırmaları uygulayın ve önceki çalışmaları görüntüleyin", "blueprintAdd": "Plan Ekle", @@ -1763,6 +1935,15 @@ "healthCheckIntervalMin": "Kontrol aralığı en az 5 saniye olmalıdır", "healthCheckTimeoutMin": "Zaman aşımı en az 1 saniye olmalıdır", "healthCheckRetryMin": "Tekrar deneme girişimleri en az 1 olmalıdır", + "healthCheckMode": "Modu Kontrol Et", + "healthCheckStrategy": "Strateji", + "healthCheckModeDescription": "TCP modu yalnızca bağlantıyı doğrular. HTTP modu HTTP yanıtını doğrular.", + "healthyThreshold": "Sağlıklı Eşik", + "healthyThresholdDescription": "Sağlıklı olarak işaretlenmeden önce gereken ardışık başarılar.", + "unhealthyThreshold": "Sağlıksız Eşik", + "unhealthyThresholdDescription": "Sağlıksız olarak işaretlenmeden önce gereken ardışık başarısızlıklar.", + "healthCheckHealthyThresholdMin": "Sağlıklı eşik en az 1 olmalıdır", + "healthCheckUnhealthyThresholdMin": "Sağlıksız eşik en az 1 olmalıdır", "httpMethod": "HTTP Yöntemi", "selectHttpMethod": "HTTP yöntemini seçin", "domainPickerSubdomainLabel": "Alt Alan Adı", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "Bağlantı Noktası", "editInternalResourceDialogModeHost": "Ev Sahibi", "editInternalResourceDialogModeCidr": "CIDR", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "Şema", + "editInternalResourceDialogEnableSsl": "SSL'i Etkinleştir", + "editInternalResourceDialogEnableSslDescription": "Hedefe güvenli HTTPS bağlantıları için SSL/TLS şifrelemeyi etkinleştirin.", "editInternalResourceDialogDestination": "Hedef", "editInternalResourceDialogDestinationHostDescription": "Site ağındaki kaynağın IP adresi veya ana bilgisayar adı.", "editInternalResourceDialogDestinationIPDescription": "Kaynağın site ağındaki IP veya ana bilgisayar adresi.", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "Ad", "createInternalResourceDialogSite": "Site", "selectSite": "Site seç...", + "multiSitesSelectorSitesCount": "{count, plural, one {# site} other {# siteler}}", "noSitesFound": "Site bulunamadı.", "createInternalResourceDialogProtocol": "Protokol", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "Bağlantı Noktası", "createInternalResourceDialogModeHost": "Ev Sahibi", "createInternalResourceDialogModeCidr": "CIDR", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "Şema", + "createInternalResourceDialogScheme": "Şema", + "createInternalResourceDialogEnableSsl": "SSL'i Etkinleştir", + "createInternalResourceDialogEnableSslDescription": "Hedefe güvenli HTTPS bağlantıları için SSL/TLS şifrelemeyi etkinleştirin.", "createInternalResourceDialogDestination": "Hedef", "createInternalResourceDialogDestinationHostDescription": "Site ağındaki kaynağın IP adresi veya ana bilgisayar adı.", "createInternalResourceDialogDestinationCidrDescription": "Site ağındaki kaynağın CIDR aralığı.", "createInternalResourceDialogAlias": "Takma Ad", "createInternalResourceDialogAliasDescription": "Bu kaynak için isteğe bağlı dahili DNS takma adı.", + "internalResourceDownstreamSchemeRequired": "HTTP kaynakları için şema gereklidir", + "internalResourceHttpPortRequired": "HTTP kaynakları için hedef bağlantı noktası gereklidir", "siteConfiguration": "Yapılandırma", "siteAcceptClientConnections": "İstemci Bağlantılarını Kabul Et", "siteAcceptClientConnectionsDescription": "Kullanıcı cihazları ve istemcilerin bu sitedeki kaynaklara erişmesine izin verin. Bu daha sonra değiştirilebilir.", @@ -1994,7 +2189,7 @@ "description": "Daha güvenilir ve düşük bakım gerektiren, ekstra özelliklere sahip kendi kendine barındırabileceğiniz Pangolin sunucusu", "introTitle": "Yönetilen Kendi Kendine Barındırılan Pangolin", "introDescription": "Bu, basitlik ve ekstra güvenilirlik arayan, ancak verilerini gizli tutmak ve kendi sunucularında barındırmak isteyen kişiler için tasarlanmış bir dağıtım seçeneğidir.", - "introDetail": "Bu seçenekle, kendi Pangolin düğümünüzü çalıştırmaya devam edersiniz — tünelleriniz, SSL bitişiniz ve trafiğiniz tamamen sunucunuzda kalır. Fark, yönetim ve izlemeyi bulut panomuz üzerinden gerçekleştiririz, bu da bir dizi avantaj sağlar:", + "introDetail": "Bu seçenekle, kendi Pangolin düğümünüzü çalıştırmaya devam edersiniz - tünelleriniz, SSL bitişiniz ve trafiğiniz tamamen sunucunuzda kalır. Fark, yönetim ve izlemeyi bulut panomuz üzerinden gerçekleştiririz, bu da bir dizi avantaj sağlar:", "benefitSimplerOperations": { "title": "Daha basit işlemler", "description": "Kendi e-posta sunucunuzu çalıştırmanıza veya karmaşık uyarılar kurmanıza gerek yok. Sağlık kontrolleri ve kesinti uyarılarını kutudan çıktığı gibi alırsınız." @@ -2297,7 +2492,7 @@ "alerts": { "commercialUseDisclosure": { "title": "Kullanım Açıklaması", - "description": "Kullanım amacınızı doğru bir şekilde yansıtan lisans seviyesini seçin. Kişisel Lisans, yazılımın bireysel, ticari olmayan veya yıllık geliri 100,000 ABD Dolarının altında olan küçük ölçekli ticari faaliyetlerde ücretsiz kullanılmasına izin verir. Bu sınırların ötesinde kullanım — bir işletme, organizasyon veya diğer gelir getirici ortamlarda kullanım dahil olmak üzere — geçerli bir Kurumsal Lisans ve ilgili lisans ücretinin ödenmesini gerektirir. Tüm kullanıcılar, ister Kişisel ister Kurumsal, Fossorial Ticari Lisans Şartlarına uymalıdır." + "description": "Kullanım amacınızı doğru bir şekilde yansıtan lisans seviyesini seçin. Kişisel Lisans, yazılımın bireysel, ticari olmayan veya yıllık geliri 100,000 ABD Dolarının altında olan küçük ölçekli ticari faaliyetlerde ücretsiz kullanılmasına izin verir. Bu sınırların ötesinde kullanım - bir işletme, organizasyon veya diğer gelir getirici ortamlarda kullanım dahil olmak üzere - geçerli bir Kurumsal Lisans ve ilgili lisans ücretinin ödenmesini gerektirir. Tüm kullanıcılar, ister Kişisel ister Kurumsal, Fossorial Ticari Lisans Şartlarına uymalıdır." }, "trialPeriodInformation": { "title": "Deneme Süresi Bilgileri", @@ -2429,6 +2624,7 @@ "validPassword": "Geçerli Şifre", "validEmail": "Geçerli E-posta", "validSSO": "Geçerli SSO", + "connectedClient": "Bağlı İstemci", "resourceBlocked": "Kaynak Engellendi", "droppedByRule": "Kurallara Göre Çıkartıldı", "noSessions": "Oturum Yok", @@ -2668,6 +2864,10 @@ "editInternalResourceDialogDestinationLabel": "Hedef", "editInternalResourceDialogDestinationDescription": "Dahili kaynak için hedef adresi belirtin. Seçilen moda bağlı olarak bu bir ana bilgisayar adı, IP adresi veya CIDR aralığı olabilir. Daha kolay tanımlama için isteğe bağlı olarak dahili bir DNS takma adı ayarlayın.", "editInternalResourceDialogPortRestrictionsDescription": "Belirtilen TCP/UDP portlarına erişimi kısıtlayın veya tüm portlara izin/engelleme verin.", + "createInternalResourceDialogHttpConfiguration": "HTTP yapılandırması", + "createInternalResourceDialogHttpConfigurationDescription": "HTTP veya HTTPS üzerinden bu kaynağa ulaşmak için istemcilerin kullanacağı alan adını seçin.", + "editInternalResourceDialogHttpConfiguration": "HTTP yapılandırması", + "editInternalResourceDialogHttpConfigurationDescription": "HTTP veya HTTPS üzerinden bu kaynağa ulaşmak için istemcilerin kullanacağı alan adını seçin.", "editInternalResourceDialogTcp": "TCP", "editInternalResourceDialogUdp": "UDP", "editInternalResourceDialogIcmp": "ICMP", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "Yakında geri döneceğiz! Sitemiz şu anda planlı bakım altındadır.", "maintenancePageMessageDescription": "Bakımın detaylarını açıklayan mesaj", "maintenancePageTimeTitle": "Tahmini Tamamlanma Süresi (İsteğe Bağlı)", + "privateMaintenanceScreenTitle": "Özel Yer Tutucu Ekran", + "privateMaintenanceScreenMessage": "Bu alan adı özel bir kaynak üzerinde kullanılmaktadır. Bu kaynağa erişmek için Pangolin istemcisini kullanarak bağlanın.", "maintenanceTime": "ör. 2 saat, 1 Kasım saat 17:00", "maintenanceEstimatedTimeDescription": "Bakımın ne zaman tamamlanmasını bekliyorsunuz", "editDomain": "Alan Adını Düzenle", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "HTTP Hedefi Ekle", "httpDestEditDescription": "Bu HTTP olay akışı hedefine yapılandırmayı güncelleyin.", "httpDestAddDescription": "Organizasyonunuzun olaylarını almak için yeni bir HTTP uç noktası yapılandırın.", + "S3DestEditTitle": "Hedefi Düzenle", + "S3DestAddTitle": "S3 Hedefi Ekle", + "S3DestEditDescription": "Bu S3 olay akışı hedefi için yapılandırmayı güncelleyin.", + "S3DestAddDescription": "Kuruluşunuzun olaylarını almak için yeni bir S3 uç noktası yapılandırın.", + "datadogDestEditTitle": "Hedefi Düzenle", + "datadogDestAddTitle": "Datadog Hedefi Ekle", + "datadogDestEditDescription": "Bu Datadog olay akışı hedefi için yapılandırmayı güncelleyin.", + "datadogDestAddDescription": "Kuruluşunuzun olaylarını almak için yeni bir Datadog uç noktası yapılandırın.", "httpDestTabSettings": "Ayarlar", "httpDestTabHeaders": "Başlıklar", "httpDestTabBody": "Gövde", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "Hedef başarıyla oluşturuldu", "httpDestUpdateFailed": "Hedef güncellenemedi", "httpDestCreateFailed": "Hedef oluşturulamadı", + "followRedirects": "Yönlendirmeleri Takip Et", + "followRedirectsDescription": "İstekler için HTTP yönlendirmelerini otomatik olarak takip edin.", + "alertingErrorWebhookUrl": "Webhook için geçerli bir URL girin lütfen.", + "healthCheckStrategyHttp": "Bağlantıyı doğrular ve HTTP yanıt durumunu kontrol eder.", + "healthCheckStrategyTcp": "Yanıtı denetlemeden sadece TCP bağlantısını doğrular.", + "healthCheckStrategySnmp": "Ağ aygıtlarının ve altyapısının sağlığını kontrol etmek için bir SNMP alma isteği yapar.", + "healthCheckStrategyIcmp": "Bir kaynağın erişilebilir ve yanıt verebilir olup olmadığını kontrol etmek için ICMP yankı isteklerini (ping) kullanır.", + "healthCheckTabStrategy": "Strateji", + "healthCheckTabConnection": "Bağlantı", + "healthCheckTabAdvanced": "Gelişmiş", + "healthCheckStrategyNotAvailable": "Bu strateji kullanılamıyor. Bu özelliği etkinleştirmek için lütfen satış ekibiyle iletişime geçin.", + "uptime30d": "Çalışma Süresi (30g)", "idpAddActionCreateNew": "Yeni kimlik sağlayıcı oluştur", "idpAddActionImportFromOrg": "Başka bir kuruluştan içe aktar", "idpImportDialogTitle": "Kimlik Sağlayıcı İçe Aktar", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "Bu işlem bu kuruluş için geri alınamaz.", "idpUnassociatedDescription": "Kimlik sağlayıcı bu kuruluştan başarıyla ayrıldı", "idpUnassociateMenu": "İlişkiyi Kes", - "idpDeleteAllOrgsMenu": "Sil" + "idpDeleteAllOrgsMenu": "Sil", + "publicIpEndpoint": "Uç Nokta", + "lastTriggeredAt": "Son Tetikleyici", + "reject": "Reddet" } diff --git a/messages/zh-CN.json b/messages/zh-CN.json index 5b446a0f3..1a79d3c35 100644 --- a/messages/zh-CN.json +++ b/messages/zh-CN.json @@ -1,4 +1,8 @@ { + "contactSalesEnable": "联系销售以启用此功能。", + "contactSalesBookDemo": "预订演示", + "contactSalesOr": "或", + "contactSalesContactUs": "联系我们", "setupCreate": "创建组织、站点和资源", "headerAuthCompatibilityInfo": "启用此功能以在身份验证令牌缺失时强制返回401未授权响应。对于不在没有服务器挑战的情况下不发送凭证的浏览器或特定HTTP库,这是必需的。", "headerAuthCompatibility": "扩展兼容性", @@ -19,6 +23,14 @@ "componentsInvalidKey": "检测到无效或过期的许可证密钥。按照许可证条款操作以继续使用所有功能。", "dismiss": "忽略", "subscriptionViolationMessage": "您的当前计划超出了您的限制。通过移除站点、用户或其他资源以保持在您的计划范围内来纠正问题。", + "trialBannerMessage": "您的试用将在 {countdown} 到期。升级以保持访问。", + "trialBannerExpired": "您的试用已到期。立即升级以恢复访问。", + "trialActive": "免费试用中", + "trialExpired": "试用到期", + "trialHasEnded": "您的试用已结束。", + "trialDaysRemaining": "{count, plural, one {# day remaining} other {# days remaining}}", + "trialDaysLeftShort": "试用期剩余 {days} 天", + "trialGoToBilling": "转到账单页面", "subscriptionViolationViewBilling": "查看计费", "componentsLicenseViolation": "许可证超限:该服务器使用了 {usedSites} 个站点,已超过授权的 {maxSites} 个。请遵守许可证条款以继续使用全部功能。", "componentsSupporterMessage": "感谢您的支持!您现在是 Pangolin 的 {tier} 用户。", @@ -267,8 +279,11 @@ "orgMissing": "缺少组织 ID", "orgMissingMessage": "没有组织ID,无法重新生成邀请。", "accessUsersManage": "管理用户", + "accessUserManage": "管理用户", "accessUsersDescription": "邀请和管理访问此组织的用户", "accessUsersSearch": "搜索用户...", + "accessUsersRoleFilterCount": "{count, plural, one {# role} other {# roles}}", + "accessUsersRoleFilterClear": "清除角色过滤器", "accessUserCreate": "创建用户", "accessUserRemove": "删除用户", "username": "用户名", @@ -1257,6 +1272,7 @@ "actionViewLogs": "查看日志", "noneSelected": "未选择", "orgNotFound2": "未找到组织。", + "search": "搜索…", "searchPlaceholder": "搜索...", "emptySearchOptions": "未找到选项", "create": "创建", @@ -1341,10 +1357,166 @@ "sidebarGeneral": "管理", "sidebarLogAndAnalytics": "日志与分析", "sidebarBluePrints": "蓝图", + "sidebarAlerting": "告警", + "sidebarHealthChecks": "健康检查", "sidebarOrganization": "组织", "sidebarManagement": "管理", "sidebarBillingAndLicenses": "帐单和许可证", "sidebarLogsAnalytics": "分析", + "alertingTitle": "告警", + "alertingDescription": "定义通知的来源、触发器和操作", + "alertingRules": "告警规则", + "alertingSearchRules": "搜索规则…", + "alertingAddRule": "创建规则", + "alertingColumnSource": "来源", + "alertingColumnTrigger": "触发", + "alertingColumnActions": "操作", + "alertingColumnEnabled": "已启用", + "alertingDeleteQuestion": "请确认您要删除此告警规则。", + "alertingDeleteRule": "删除告警规则", + "alertingRuleDeleted": "告警规则已删除", + "alertingRuleSaved": "告警规则已保存", + "alertingRuleSavedCreatedDescription": "您的新告警规则已创建。您可以在此页面继续编辑它。", + "alertingRuleSavedUpdatedDescription": "对此告警规则的更改已保存。", + "alertingEditRule": "编辑告警规则", + "alertingCreateRule": "创建告警规则", + "alertingRuleCredenzaDescription": "选择要监视的内容、何时触发以及如何通知", + "alertingRuleNamePlaceholder": "生产站点故障", + "alertingRuleEnabled": "规则已启用", + "alertingSectionSource": "来源", + "alertingSourceType": "来源类型", + "alertingSourceSite": "站点", + "alertingSourceHealthCheck": "健康检查", + "alertingPickSites": "站点", + "alertingPickHealthChecks": "健康检查", + "alertingPickResources": "资源", + "alertingAllSites": "所有站点", + "alertingAllSitesDescription": "任何站点的告警触发", + "alertingSpecificSites": "特定站点", + "alertingSpecificSitesDescription": "选择要监视的特定站点", + "alertingAllHealthChecks": "所有健康检查", + "alertingAllHealthChecksDescription": "任何健康检查的告警触发", + "alertingSpecificHealthChecks": "特定健康检查", + "alertingSpecificHealthChecksDescription": "选择要监视的特定健康检查", + "alertingAllResources": "所有资源", + "alertingAllResourcesDescription": "任何资源的告警触发", + "alertingSpecificResources": "特定资源", + "alertingSpecificResourcesDescription": "选择要监视的特定资源", + "alertingSelectResources": "选择资源…", + "alertingResourcesSelected": "{count} 个资源已选择", + "alertingResourcesEmpty": "在前 10 个结果中没有带目标的资源。", + "alertingSectionTrigger": "触发", + "alertingTrigger": "何时告警", + "alertingTriggerSiteOnline": "站点在线", + "alertingTriggerSiteOffline": "站点离线", + "alertingTriggerSiteToggle": "站点状态变更", + "alertingTriggerHcHealthy": "健康检查正常", + "alertingTriggerHcUnhealthy": "健康检查不正常", + "alertingTriggerHcToggle": "健康检查状态变更", + "alertingTriggerResourceHealthy": "资源正常", + "alertingTriggerResourceUnhealthy": "资源不正常", + "alertingSearchHealthChecks": "搜索健康检查…", + "alertingHealthChecksEmpty": "无可用健康检查。", + "alertingTriggerResourceToggle": "资源状态变更", + "alertingSourceResource": "资源", + "alertingSectionActions": "操作", + "alertingAddAction": "新增操作", + "alertingActionNotify": "电子邮件", + "alertingActionNotifyDescription": "向用户或角色发送电子邮件通知", + "alertingActionWebhook": "Webhook", + "alertingActionWebhookDescription": "发送 HTTP 请求到自定义终端", + "alertingExternalIntegration": "外部集成", + "alertingExternalPagerDutyDescription": "将告警发送给 PagerDuty 以进行事件管理", + "alertingExternalOpsgenieDescription": "将告警路由到 Opsgenie 进行电话值班管理", + "alertingExternalServiceNowDescription": "从告警事件创建 ServiceNow 事件", + "alertingExternalIncidentIoDescription": "从告警事件触发 Incident.io 工作流程", + "alertingActionType": "操作类型", + "alertingNotifyUsers": "用户", + "alertingNotifyRoles": "角色", + "alertingNotifyEmails": "电子邮件地址", + "alertingEmailPlaceholder": "添加电子邮件并按回车键", + "alertingWebhookMethod": "HTTP 方法", + "alertingWebhookSecret": "签名密钥(可选)", + "alertingWebhookSecretPlaceholder": "HMAC 密钥", + "alertingWebhookHeaders": "标头", + "alertingAddHeader": "添加标头", + "alertingSelectSites": "选择站点…", + "alertingSitesSelected": "{count} 个站点已选择", + "alertingSelectHealthChecks": "选择健康检查…", + "alertingHealthChecksSelected": "{count} 个健康检查已选择", + "alertingNoHealthChecks": "没有启用健康检查的目标", + "alertingHealthCheckStub": "健康检查来源选择尚未配置 - 你仍然可以配置触发器和操作。", + "alertingSelectUsers": "选择用户…", + "alertingUsersSelected": "{count} 个用户已选择", + "alertingSelectRoles": "选择角色…", + "alertingRolesSelected": "{count} 个角色已选择", + "alertingSummarySites": "站点 ({count})", + "alertingSummaryAllSites": "所有站点", + "alertingSummaryHealthChecks": "健康检查 ({count})", + "alertingSummaryAllHealthChecks": "所有健康检查", + "alertingSummaryResources": "资源 ({count})", + "alertingSummaryAllResources": "所有资源", + "alertingErrorNameRequired": "输入名称", + "alertingErrorActionsMin": "添加至少一个操作", + "alertingErrorPickSites": "至少选择一个站点", + "alertingErrorPickHealthChecks": "至少选择一个健康检查", + "alertingErrorPickResources": "至少选择一个资源", + "alertingErrorTriggerSite": "选择站点触发器", + "alertingErrorTriggerHealth": "选择健康检查触发器", + "alertingErrorTriggerResource": "选择资源触发器", + "alertingErrorNotifyRecipients": "选择用户、角色或至少一个电子邮件", + "alertingConfigureSource": "配置来源", + "alertingConfigureTrigger": "配置触发器", + "alertingConfigureActions": "配置操作", + "alertingBackToRules": "返回规则", + "alertingRuleCooldown": "冷却时间(秒)", + "alertingRuleCooldownDescription": "相同规则间隔重复告警的最小时间。设置为 0 固定触发。", + "alertingDraftBadge": "草稿 - 保存以存储此规则", + "alertingSidebarHint": "点击画布上的步骤在此处编辑。", + "alertingGraphCanvasTitle": "规则流程", + "alertingGraphCanvasDescription": "源、触发器和操作的视觉概况。选择一个节点,在面板上进行编辑。", + "alertingNodeNotConfigured": "尚未配置", + "alertingNodeActionsCount": "{count, plural, one {# action} other {# actions}}", + "alertingNodeRoleSource": "来源", + "alertingNodeRoleTrigger": "触发", + "alertingNodeRoleAction": "行为", + "alertingTabRules": "告警规则", + "alertingTabHealthChecks": "健康检查", + "alertingRulesBannerTitle": "获取通知", + "alertingRulesBannerDescription": "每条规则都连接要监视的对象(站点、健康检查或资源),触发时间(例如离线或不健康),以及如何通过电子邮件、Webhooks 或集成将通知发送给团队。使用此列表创建、启用和管理这些规则。", + "alertingHealthChecksBannerTitle": "监视健康和资源", + "alertingHealthChecksBannerDescription": "健康检查是您一次定义的 HTTP 或 TCP 监控。然后可以将它们用作告警规则中的来源,以便目标变得正常或不正常时得到通知。资源上的健康检查也会出现在此处。", + "standaloneHcTableTitle": "健康检查", + "standaloneHcSearchPlaceholder": "搜索健康检查…", + "standaloneHcAddButton": "创建健康检查", + "standaloneHcCreateTitle": "创建健康检查", + "standaloneHcEditTitle": "编辑健康检查", + "standaloneHcDescription": "配置 HTTP 或 TCP 健康检查以用于告警规则。", + "standaloneHcNameLabel": "名称", + "standaloneHcNamePlaceholder": "我的 HTTP 监视器", + "standaloneHcDeleteTitle": "删除健康检查", + "standaloneHcDeleteQuestion": "请确认您要删除此健康检查。", + "standaloneHcDeleted": "健康检查已删除", + "standaloneHcSaved": "健康检查已保存", + "standaloneHcColumnHealth": "健康", + "standaloneHcColumnMode": "模式", + "standaloneHcColumnTarget": "目标", + "standaloneHcHealthStateHealthy": "健康", + "standaloneHcHealthStateUnhealthy": "不健康", + "standaloneHcHealthStateUnknown": "未知", + "standaloneHcFilterAnySite": "所有站点", + "standaloneHcFilterAnyResource": "所有资源", + "standaloneHcFilterMode": "模式", + "standaloneHcFilterModeHttp": "HTTP", + "standaloneHcFilterModeTcp": "TCP", + "standaloneHcFilterModeSnmp": "SNMP", + "standaloneHcFilterModePing": "Ping", + "standaloneHcFilterHealth": "健康", + "standaloneHcFilterEnabled": "已启用", + "standaloneHcFilterEnabledOn": "已启用", + "standaloneHcFilterEnabledOff": "已禁用", + "standaloneHcFilterSiteIdFallback": "站点 {id}", + "standaloneHcFilterResourceIdFallback": "资源 {id}", "blueprints": "蓝图", "blueprintsDescription": "应用声明配置并查看先前运行的", "blueprintAdd": "添加蓝图", @@ -1763,6 +1935,15 @@ "healthCheckIntervalMin": "检查间隔必须至少为 5 秒", "healthCheckTimeoutMin": "超时必须至少为 1 秒", "healthCheckRetryMin": "重试次数必须至少为 1 次", + "healthCheckMode": "检查模式", + "healthCheckStrategy": "策略", + "healthCheckModeDescription": "TCP 模式仅验证连接性。HTTP 模式验证 HTTP 响应。", + "healthyThreshold": "正常阈值", + "healthyThresholdDescription": "标记为正常之前所需的连续成功次数。", + "unhealthyThreshold": "不正常阈值", + "unhealthyThresholdDescription": "标记为不正常之前所需的连续失败次数。", + "healthCheckHealthyThresholdMin": "健康阈值至少为 1", + "healthCheckUnhealthyThresholdMin": "不健康阈值至少为 1", "httpMethod": "HTTP 方法", "selectHttpMethod": "选择 HTTP 方法", "domainPickerSubdomainLabel": "子域名", @@ -1822,6 +2003,11 @@ "editInternalResourceDialogModePort": "端口", "editInternalResourceDialogModeHost": "主机", "editInternalResourceDialogModeCidr": "CIDR", + "editInternalResourceDialogModeHttp": "HTTP", + "editInternalResourceDialogModeHttps": "HTTPS", + "editInternalResourceDialogScheme": "方案", + "editInternalResourceDialogEnableSsl": "启用 SSL", + "editInternalResourceDialogEnableSslDescription": "为目标的安全 HTTPS 连接启用 SSL/TLS 加密。", "editInternalResourceDialogDestination": "目标", "editInternalResourceDialogDestinationHostDescription": "站点网络上资源的 IP 地址或主机名。", "editInternalResourceDialogDestinationIPDescription": "站点网络上资源的IP或主机名地址。", @@ -1837,6 +2023,7 @@ "createInternalResourceDialogName": "名称", "createInternalResourceDialogSite": "站点", "selectSite": "选择站点...", + "multiSitesSelectorSitesCount": "{count, plural, one {# site} other {# sites}}", "noSitesFound": "未找到站点。", "createInternalResourceDialogProtocol": "协议", "createInternalResourceDialogTcp": "TCP", @@ -1865,11 +2052,19 @@ "createInternalResourceDialogModePort": "端口", "createInternalResourceDialogModeHost": "主机", "createInternalResourceDialogModeCidr": "CIDR", + "createInternalResourceDialogModeHttp": "HTTP", + "createInternalResourceDialogModeHttps": "HTTPS", + "scheme": "方案", + "createInternalResourceDialogScheme": "方案", + "createInternalResourceDialogEnableSsl": "启用 SSL", + "createInternalResourceDialogEnableSslDescription": "为目标的安全 HTTPS 连接启用 SSL/TLS 加密。", "createInternalResourceDialogDestination": "目标", "createInternalResourceDialogDestinationHostDescription": "站点网络上资源的 IP 地址或主机名。", "createInternalResourceDialogDestinationCidrDescription": "站点网络上资源的 CIDR 范围。", "createInternalResourceDialogAlias": "Alias", "createInternalResourceDialogAliasDescription": "此资源可选的内部DNS别名。", + "internalResourceDownstreamSchemeRequired": "HTTP 资源需要方案", + "internalResourceHttpPortRequired": "HTTP 资源需要目的端口", "siteConfiguration": "配置", "siteAcceptClientConnections": "接受客户端连接", "siteAcceptClientConnectionsDescription": "允许用户设备和客户端访问此站点上的资源。这可以稍后更改。", @@ -1994,7 +2189,7 @@ "description": "更可靠和低维护自我托管的 Pangolin 服务器,带有额外的铃声和告密器", "introTitle": "托管自托管的潘戈林公司", "introDescription": "这是一种部署选择,为那些希望简洁和额外可靠的人设计,同时仍然保持他们的数据的私密性和自我托管性。", - "introDetail": "通过此选项,您仍然运行您自己的 Pangolin 节点 — — 您的隧道、SSL 终止,并且流量在您的服务器上保持所有状态。 不同之处在于,管理和监测是通过我们的云层仪表板进行的,该仪表板开启了一些好处:", + "introDetail": "通过此选项,您仍然运行您自己的 Pangolin 节点 - - 您的隧道、SSL 终止,并且流量在您的服务器上保持所有状态。 不同之处在于,管理和监测是通过我们的云层仪表板进行的,该仪表板开启了一些好处:", "benefitSimplerOperations": { "title": "简单的操作", "description": "无需运行您自己的邮件服务器或设置复杂的警报。您将从方框中获得健康检查和下限提醒。" @@ -2119,7 +2314,7 @@ "selectDomainForOrgAuthPage": "选择组织认证页面的域", "domainPickerProvidedDomain": "提供的域", "domainPickerFreeProvidedDomain": "免费提供的域", - "domainPickerFreeDomainsPaidFeature": "提供的域名是付费功能。订阅即可将域名包含在您的计划中—无需自带域名。", + "domainPickerFreeDomainsPaidFeature": "提供的域名是付费功能。订阅即可将域名包含在您的计划中-无需自带域名。", "domainPickerVerified": "已验证", "domainPickerUnverified": "未验证", "domainPickerManual": "手动", @@ -2297,7 +2492,7 @@ "alerts": { "commercialUseDisclosure": { "title": "使用情况披露", - "description": "选择能准确反映您预定用途的许可等级。 个人许可证允许对个人、非商业性或小型商业活动免费使用软件,年收入毛额不到100 000美元。 超出这些限度的任何用途,包括在企业、组织内的用途。 或其他创收环境——需要有效的企业许可证和支付适用的许可证费用。 所有用户,不论是个人还是企业,都必须遵守寄养商业许可证条款。" + "description": "选择能准确反映您预定用途的许可等级。 个人许可证允许对个人、非商业性或小型商业活动免费使用软件,年收入毛额不到100 000美元。 超出这些限度的任何用途,包括在企业、组织内的用途。 或其他创收环境--需要有效的企业许可证和支付适用的许可证费用。 所有用户,不论是个人还是企业,都必须遵守寄养商业许可证条款。" }, "trialPeriodInformation": { "title": "试用期信息", @@ -2429,6 +2624,7 @@ "validPassword": "有效密码", "validEmail": "Valid email", "validSSO": "Valid SSO", + "connectedClient": "已连接客户端", "resourceBlocked": "资源被阻止", "droppedByRule": "被规则删除", "noSessions": "无会话", @@ -2668,6 +2864,10 @@ "editInternalResourceDialogDestinationLabel": "目标", "editInternalResourceDialogDestinationDescription": "指定内部资源的目标地址。根据选择的模式,这可以是主机名、IP地址或CIDR范围。可选的,设置一个内部DNS别名以便于识别。", "editInternalResourceDialogPortRestrictionsDescription": "限制访问特定的TCP/UDP端口或允许/阻止所有端口。", + "createInternalResourceDialogHttpConfiguration": "HTTP 配置", + "createInternalResourceDialogHttpConfigurationDescription": "选择客户将使用的域名通过 HTTP 或 HTTPS 访问此资源。", + "editInternalResourceDialogHttpConfiguration": "HTTP 配置", + "editInternalResourceDialogHttpConfigurationDescription": "选择客户将使用的域名通过 HTTP 或 HTTPS 访问此资源。", "editInternalResourceDialogTcp": "TCP", "editInternalResourceDialogUdp": "UDP", "editInternalResourceDialogIcmp": "ICMP", @@ -2706,6 +2906,8 @@ "maintenancePageMessagePlaceholder": "我们很快回来! 我们的网站目前正在进行计划中的维护。", "maintenancePageMessageDescription": "详细说明维护的消息", "maintenancePageTimeTitle": "预计完成时间(可选)", + "privateMaintenanceScreenTitle": "私有占位符界面", + "privateMaintenanceScreenMessage": "此域名正在私有资源上使用。请连接 Pangolin 客户端以访问此资源。", "maintenanceTime": "例如,2小时,11月1日下午5:00", "maintenanceEstimatedTimeDescription": "您期望维护完成的时间", "editDomain": "编辑域名", @@ -2843,6 +3045,14 @@ "httpDestAddTitle": "添加 HTTP 目标", "httpDestEditDescription": "更新此 HTTP 事件流媒体目的地的配置。", "httpDestAddDescription": "配置新的 HTTP 端点来接收您的组织事件。", + "S3DestEditTitle": "编辑目的地", + "S3DestAddTitle": "添加 S3 目的地", + "S3DestEditDescription": "更新此 S3 事件流目的地的配置。", + "S3DestAddDescription": "配置新的 S3 终端以接收您的组织事件。", + "datadogDestEditTitle": "编辑目的地", + "datadogDestAddTitle": "添加 Datadog 目的地", + "datadogDestEditDescription": "更新此 Datadog 事件流目的地的配置。", + "datadogDestAddDescription": "配置新的 Datadog 终端以接收您的组织事件。", "httpDestTabSettings": "设置", "httpDestTabHeaders": "信头", "httpDestTabBody": "正文内容", @@ -2882,7 +3092,7 @@ "httpDestFormatJsonArrayTitle": "JSON 数组", "httpDestFormatJsonArrayDescription": "每批一个请求,实体是一个 JSON 数组。与大多数通用的 Web 钩子和数据兼容。", "httpDestFormatNdjsonTitle": "NDJSON", - "httpDestFormatNdjsonDescription": "每批有一个请求,物体是换行符限制的 JSON ——每行一个对象,不是外部数组。 Sluk HEC、Elastic / OpenSearch和Grafana Loki所需。", + "httpDestFormatNdjsonDescription": "每批有一个请求,物体是换行符限制的 JSON --每行一个对象,不是外部数组。 Sluk HEC、Elastic / OpenSearch和Grafana Loki所需。", "httpDestFormatSingleTitle": "每个请求一个事件", "httpDestFormatSingleDescription": "为每个事件单独发送一个 HTTP POST。仅用于无法处理批量的端点。", "httpDestLogTypesTitle": "日志类型", @@ -2901,6 +3111,18 @@ "httpDestCreatedSuccess": "目标创建成功", "httpDestUpdateFailed": "更新目标失败", "httpDestCreateFailed": "创建目标失败", + "followRedirects": "遵循重定向", + "followRedirectsDescription": "自动跟踪请求的 HTTP 重定向。", + "alertingErrorWebhookUrl": "请输入有效的 Webhook URL。", + "healthCheckStrategyHttp": "验证连接并检查 HTTP 响应状态。", + "healthCheckStrategyTcp": "只验证 TCP 连接性,不检查响应。", + "healthCheckStrategySnmp": "进行 SNMP get 请求以检查网络设备和基础架构的健康状况。", + "healthCheckStrategyIcmp": "使用 ICMP 回显请求(ping)检查资源是否可达并响应。", + "healthCheckTabStrategy": "策略", + "healthCheckTabConnection": "连接", + "healthCheckTabAdvanced": "高级", + "healthCheckStrategyNotAvailable": "此策略不可用。请联系销售以启用此功能。", + "uptime30d": "正常运行时间(30天)", "idpAddActionCreateNew": "创建新的身份提供者", "idpAddActionImportFromOrg": "从另一个组织导入", "idpImportDialogTitle": "导入身份提供者", @@ -2917,5 +3139,8 @@ "idpUnassociateWarning": "此操作无法对该组织撤销。", "idpUnassociatedDescription": "身份提供者已成功从该组织中取消关联", "idpUnassociateMenu": "取消关联", - "idpDeleteAllOrgsMenu": "删除" + "idpDeleteAllOrgsMenu": "删除", + "publicIpEndpoint": "终端", + "lastTriggeredAt": "最后触发", + "reject": "拒绝" } diff --git a/messages/zh-TW.json b/messages/zh-TW.json index cf7c25ced..1ef8061e2 100644 --- a/messages/zh-TW.json +++ b/messages/zh-TW.json @@ -1763,7 +1763,7 @@ "description": "更可靠、維護成本更低的自架 Pangolin 伺服器,並附帶額外的附加功能", "introTitle": "託管式自架 Pangolin", "introDescription": "這是一種部署選擇,為那些希望簡潔和額外可靠的人設計,同時仍然保持他們的數據的私密性和自我託管性。", - "introDetail": "通過此選項,您仍然運行您自己的 Pangolin 節點 — — 您的隧道、SSL 終止,並且流量在您的伺服器上保持所有狀態。 不同之處在於,管理和監測是通過我們的雲層儀錶板進行的,該儀錶板開啟了一些好處:", + "introDetail": "通過此選項,您仍然運行您自己的 Pangolin 節點 - - 您的隧道、SSL 終止,並且流量在您的伺服器上保持所有狀態。 不同之處在於,管理和監測是通過我們的雲層儀錶板進行的,該儀錶板開啟了一些好處:", "benefitSimplerOperations": { "title": "簡單的操作", "description": "無需運行您自己的郵件伺服器或設置複雜的警報。您將從方框中獲得健康檢查和下限提醒。" @@ -2035,7 +2035,7 @@ "alerts": { "commercialUseDisclosure": { "title": "使用情況披露", - "description": "選擇能準確反映您預定用途的許可等級。 個人許可證允許對個人、非商業性或小型商業活動免費使用軟體,年收入毛額不到 100,000 美元。 超出這些限度的任何用途,包括在企業、組織內的用途。 或其他創收環境——需要有效的企業許可證和支付適用的許可證費用。 所有用戶,不論是個人還是企業,都必須遵守寄養商業許可證條款。" + "description": "選擇能準確反映您預定用途的許可等級。 個人許可證允許對個人、非商業性或小型商業活動免費使用軟體,年收入毛額不到 100,000 美元。 超出這些限度的任何用途,包括在企業、組織內的用途。 或其他創收環境--需要有效的企業許可證和支付適用的許可證費用。 所有用戶,不論是個人還是企業,都必須遵守寄養商業許可證條款。" }, "trialPeriodInformation": { "title": "試用期資訊", diff --git a/package-lock.json b/package-lock.json index 1676e6f25..8c241554a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1058,6 +1058,7 @@ "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", @@ -2353,6 +2354,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "Apache-2.0", "optional": true, "os": [ @@ -2375,6 +2377,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "Apache-2.0", "optional": true, "os": [ @@ -2397,6 +2400,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2413,6 +2417,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2429,6 +2434,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2445,6 +2451,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2461,6 +2468,7 @@ "cpu": [ "ppc64" ], + "dev": true, "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2477,6 +2485,7 @@ "cpu": [ "s390x" ], + "dev": true, "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2493,6 +2502,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2509,6 +2519,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2525,6 +2536,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2541,6 +2553,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "Apache-2.0", "optional": true, "os": [ @@ -2563,6 +2576,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "Apache-2.0", "optional": true, "os": [ @@ -2585,6 +2599,7 @@ "cpu": [ "ppc64" ], + "dev": true, "license": "Apache-2.0", "optional": true, "os": [ @@ -2607,6 +2622,7 @@ "cpu": [ "s390x" ], + "dev": true, "license": "Apache-2.0", "optional": true, "os": [ @@ -2629,6 +2645,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "Apache-2.0", "optional": true, "os": [ @@ -2651,6 +2668,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "Apache-2.0", "optional": true, "os": [ @@ -2673,6 +2691,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "Apache-2.0", "optional": true, "os": [ @@ -2695,6 +2714,7 @@ "cpu": [ "wasm32" ], + "dev": true, "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", "optional": true, "dependencies": { @@ -2714,6 +2734,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "Apache-2.0 AND LGPL-3.0-or-later", "optional": true, "os": [ @@ -2733,6 +2754,7 @@ "cpu": [ "ia32" ], + "dev": true, "license": "Apache-2.0 AND LGPL-3.0-or-later", "optional": true, "os": [ @@ -2752,6 +2774,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "Apache-2.0 AND LGPL-3.0-or-later", "optional": true, "os": [ @@ -3011,6 +3034,7 @@ "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": "^14.21.3 || >=16" }, @@ -6957,6 +6981,7 @@ "resolved": "https://registry.npmjs.org/@react-email/text/-/text-0.1.6.tgz", "integrity": "sha512-TYqkioRS45wTR5il3dYk/SbUjjEdhSwh9BtRNB99qNH1pXAwA45H7rAuxehiu8iJQJH0IyIr+6n62gBz9ezmsw==", "license": "MIT", + "peer": true, "engines": { "node": ">=20.0.0" }, @@ -8417,6 +8442,7 @@ "version": "5.90.21", "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.90.21.tgz", "integrity": "sha512-0Lu6y5t+tvlTJMTO7oh5NSpJfpg/5D41LlThfepTixPYkJ0sE2Jj0m0f6yYqujBwIXlId87e234+MxG3D3g7kg==", + "peer": true, "dependencies": { "@tanstack/query-core": "5.90.20" }, @@ -8532,6 +8558,7 @@ "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==", "devOptional": true, "license": "MIT", + "peer": true, "dependencies": { "@types/node": "*" } @@ -8879,6 +8906,7 @@ "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@types/body-parser": "*", "@types/express-serve-static-core": "^5.0.0", @@ -8974,6 +9002,7 @@ "integrity": "sha512-oX8xrhvpiyRCQkG1MFchB09f+cXftgIXb3a7UUa4Y3wpmZPw5tyZGTLWhlESOLq1Rq6oDlc8npVU2/9xiCuXMA==", "devOptional": true, "license": "MIT", + "peer": true, "dependencies": { "undici-types": "~7.18.0" } @@ -9001,6 +9030,7 @@ "integrity": "sha512-gT+oueVQkqnj6ajGJXblFR4iavIXWsGAFCk3dP4Kki5+a9R4NMt0JARdk6s8cUKcfUoqP5dAtDSLU8xYUTFV+Q==", "devOptional": true, "license": "MIT", + "peer": true, "dependencies": { "@types/node": "*", "pg-protocol": "*", @@ -9026,6 +9056,7 @@ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz", "integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==", "devOptional": true, + "peer": true, "dependencies": { "csstype": "^3.2.2" } @@ -9036,6 +9067,7 @@ "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", "devOptional": true, "license": "MIT", + "peer": true, "peerDependencies": { "@types/react": "^19.2.0" } @@ -9122,8 +9154,7 @@ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/@types/ws": { "version": "8.18.1", @@ -9197,6 +9228,7 @@ "integrity": "sha512-klQbnPAAiGYFyI02+znpBRLyjL4/BrBd0nyWkdC0s/6xFLkXYQ8OoRrSkqacS1ddVxf/LDyODIKbQ5TgKAf/Fg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.56.1", "@typescript-eslint/types": "8.56.1", @@ -9670,6 +9702,7 @@ "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", "dev": true, "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -10119,6 +10152,7 @@ "integrity": "sha512-Ixm8tFfoKKIPYdCCKYTsqv+Fd4IJ0DQqMyEimo+pxUOMUR9cVPlwTrFt9Avu+3cb6Zp3mAzl+t1MrG2fxxKsxw==", "devOptional": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/types": "^7.26.0" } @@ -10190,6 +10224,7 @@ "integrity": "sha512-Ba0KR+Fzxh2jDRhdg6TSH0SJGzb8C0aBY4hR8w8madIdIzzC6Y1+kx5qR6eS1Z+Gy20h6ZU28aeyg0z1VIrShQ==", "hasInstallScript": true, "license": "MIT", + "peer": true, "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" @@ -10318,6 +10353,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -11224,6 +11260,7 @@ "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz", "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==", "license": "ISC", + "peer": true, "engines": { "node": ">=12" } @@ -11664,7 +11701,6 @@ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.2.tgz", "integrity": "sha512-6obghkliLdmKa56xdbLOpUZ43pAR6xFy1uOrxBaIDjT+yaRuuybLjGS9eVBoSR/UPU5fq3OXClEHLJNGvbxKpQ==", "license": "(MPL-2.0 OR Apache-2.0)", - "peer": true, "engines": { "node": ">=20" }, @@ -12299,6 +12335,7 @@ "dev": true, "hasInstallScript": true, "license": "MIT", + "peer": true, "bin": { "esbuild": "bin/esbuild" }, @@ -12384,6 +12421,7 @@ "integrity": "sha512-COV33RzXZkqhG9P2rZCFl9ZmJ7WL+gQSCRzE7RhkbclbQPtLAWReL7ysA0Sh4c8Im2U9ynybdR56PV0XcKvqaQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.2", @@ -12520,6 +12558,7 @@ "integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@rtsao/scc": "^1.1.0", "array-includes": "^3.1.9", @@ -12913,6 +12952,7 @@ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", "license": "MIT", + "peer": true, "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", @@ -15330,7 +15370,6 @@ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz", "integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==", "license": "MIT", - "peer": true, "dependencies": { "dompurify": "3.2.7", "marked": "14.0.0" @@ -15341,7 +15380,6 @@ "resolved": "https://registry.npmjs.org/marked/-/marked-14.0.0.tgz", "integrity": "sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==", "license": "MIT", - "peer": true, "bin": { "marked": "bin/marked.js" }, @@ -15430,6 +15468,7 @@ "resolved": "https://registry.npmjs.org/next/-/next-15.5.15.tgz", "integrity": "sha512-VSqCrJwtLVGwAVE0Sb/yikrQfkwkZW9p+lL/J4+xe+G3ZA+QnWPqgcfH1tDUEuk9y+pthzzVFp4L/U8JerMfMQ==", "license": "MIT", + "peer": true, "dependencies": { "@next/env": "15.5.15", "@swc/helpers": "0.5.15", @@ -16389,6 +16428,7 @@ "resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz", "integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==", "license": "MIT", + "peer": true, "dependencies": { "pg-connection-string": "^2.12.0", "pg-pool": "^3.13.0", @@ -16896,6 +16936,7 @@ "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz", "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==", "license": "MIT", + "peer": true, "engines": { "node": ">=0.10.0" } @@ -16927,6 +16968,7 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz", "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==", "license": "MIT", + "peer": true, "dependencies": { "scheduler": "^0.27.0" }, @@ -17219,6 +17261,7 @@ "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.71.2.tgz", "integrity": "sha512-1CHvcDYzuRUNOflt4MOq3ZM46AronNJtQ1S7tnX6YN4y72qhgiUItpacZUAQ0TyWYci3yz1X+rXaSxiuEm86PA==", "license": "MIT", + "peer": true, "engines": { "node": ">=18.0.0" }, @@ -18680,7 +18723,8 @@ "version": "4.2.2", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.2.2.tgz", "integrity": "sha512-KWBIxs1Xb6NoLdMVqhbhgwZf2PGBpPEiwOqgI4pFIYbNTfBXiKYyWoTsXgBQ9WFg/OlhnvHaY+AEpW7wSmFo2Q==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/tapable": { "version": "2.3.2", @@ -19155,6 +19199,7 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "devOptional": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -19582,6 +19627,7 @@ "resolved": "https://registry.npmjs.org/winston/-/winston-3.19.0.tgz", "integrity": "sha512-LZNJgPzfKR+/J3cHkxcpHKpKKvGfDZVPS4hfJCc4cCG0CgYzvlD6yE/S3CIL/Yt91ak327YCpiF/0MyeZHEHKA==", "license": "MIT", + "peer": true, "dependencies": { "@colors/colors": "^1.6.0", "@dabh/diagnostics": "^2.0.8", @@ -19788,6 +19834,7 @@ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", "license": "MIT", + "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/public/third-party/incidentio.png b/public/third-party/incidentio.png new file mode 100644 index 000000000..e567d31fb Binary files /dev/null and b/public/third-party/incidentio.png differ diff --git a/public/third-party/opsgenie.png b/public/third-party/opsgenie.png new file mode 100644 index 000000000..3a1f5a849 Binary files /dev/null and b/public/third-party/opsgenie.png differ diff --git a/public/third-party/pgd.png b/public/third-party/pgd.png new file mode 100644 index 000000000..b084406a0 Binary files /dev/null and b/public/third-party/pgd.png differ diff --git a/public/third-party/servicenow.png b/public/third-party/servicenow.png new file mode 100644 index 000000000..b3fcca4dc Binary files /dev/null and b/public/third-party/servicenow.png differ diff --git a/server/apiServer.ts b/server/apiServer.ts index dafec1b85..9a91d473e 100644 --- a/server/apiServer.ts +++ b/server/apiServer.ts @@ -121,7 +121,7 @@ export function createApiServer() { const httpServer = apiServer.listen(externalPort, (err?: any) => { if (err) throw err; logger.info( - `API server is running on http://localhost:${externalPort}` + `Dashboard API server is running on http://localhost:${externalPort}` ); }); diff --git a/server/auth/actions.ts b/server/auth/actions.ts index 213dab9d3..5ae98f965 100644 --- a/server/auth/actions.ts +++ b/server/auth/actions.ts @@ -123,6 +123,7 @@ export enum ActionsEnum { deleteOrgDomain = "deleteOrgDomain", restartOrgDomain = "restartOrgDomain", sendUsageNotification = "sendUsageNotification", + sendTrialNotification = "sendTrialNotification", createRemoteExitNode = "createRemoteExitNode", updateRemoteExitNode = "updateRemoteExitNode", getRemoteExitNode = "getRemoteExitNode", @@ -144,7 +145,19 @@ export enum ActionsEnum { createEventStreamingDestination = "createEventStreamingDestination", updateEventStreamingDestination = "updateEventStreamingDestination", deleteEventStreamingDestination = "deleteEventStreamingDestination", - listEventStreamingDestinations = "listEventStreamingDestinations" + listEventStreamingDestinations = "listEventStreamingDestinations", + createAlertRule = "createAlertRule", + updateAlertRule = "updateAlertRule", + deleteAlertRule = "deleteAlertRule", + listAlertRules = "listAlertRules", + getAlertRule = "getAlertRule", + createHealthCheck = "createHealthCheck", + updateHealthCheck = "updateHealthCheck", + deleteHealthCheck = "deleteHealthCheck", + listHealthChecks = "listHealthChecks", + triggerSiteAlert = "triggerSiteAlert", + triggerResourceAlert = "triggerResourceAlert", + triggerHealthCheckAlert = "triggerHealthCheckAlert" } export async function checkUserActionPermission( diff --git a/server/db/pg/schema/privateSchema.ts b/server/db/pg/schema/privateSchema.ts index 4122fb5b5..d930b69d0 100644 --- a/server/db/pg/schema/privateSchema.ts +++ b/server/db/pg/schema/privateSchema.ts @@ -16,11 +16,14 @@ import { domains, orgs, targets, + roles, users, exitNodes, sessions, clients, + resources, siteResources, + targetHealthCheck, sites } from "./schema"; @@ -88,6 +91,8 @@ export const subscriptions = pgTable("subscriptions", { updatedAt: bigint("updatedAt", { mode: "number" }), version: integer("version"), billingCycleAnchor: bigint("billingCycleAnchor", { mode: "number" }), + expiresAt: bigint("expiresAt", { mode: "number" }), + trial: boolean("trial").default(false), type: varchar("type", { length: 50 }) // tier1, tier2, tier3, or license }); @@ -425,7 +430,9 @@ export const eventStreamingDestinations = pgTable( orgId: varchar("orgId", { length: 255 }) .notNull() .references(() => orgs.orgId, { onDelete: "cascade" }), - sendConnectionLogs: boolean("sendConnectionLogs").notNull().default(false), + sendConnectionLogs: boolean("sendConnectionLogs") + .notNull() + .default(false), sendRequestLogs: boolean("sendRequestLogs").notNull().default(false), sendActionLogs: boolean("sendActionLogs").notNull().default(false), sendAccessLogs: boolean("sendAccessLogs").notNull().default(false), @@ -447,7 +454,9 @@ export const eventStreamingCursors = pgTable( onDelete: "cascade" }), logType: varchar("logType", { length: 50 }).notNull(), // "request" | "action" | "access" | "connection" - lastSentId: bigint("lastSentId", { mode: "number" }).notNull().default(0), + lastSentId: bigint("lastSentId", { mode: "number" }) + .notNull() + .default(0), lastSentAt: bigint("lastSentAt", { mode: "number" }) // epoch milliseconds, null if never sent }, (table) => [ @@ -458,6 +467,104 @@ export const eventStreamingCursors = pgTable( ] ); +export const alertRules = pgTable("alertRules", { + alertRuleId: serial("alertRuleId").primaryKey(), + orgId: varchar("orgId", { length: 255 }) + .notNull() + .references(() => orgs.orgId, { onDelete: "cascade" }), + name: varchar("name", { length: 255 }).notNull(), + // Single field encodes both source and trigger - no redundancy + eventType: varchar("eventType", { length: 100 }) + .$type< + | "site_online" + | "site_offline" + | "site_toggle" + | "health_check_healthy" + | "health_check_unhealthy" + | "health_check_toggle" + | "resource_healthy" + | "resource_unhealthy" + | "resource_toggle" + >() + .notNull(), + // Nullable depending on eventType + enabled: boolean("enabled").notNull().default(true), + cooldownSeconds: integer("cooldownSeconds").notNull().default(300), + allSites: boolean("allSites").notNull().default(false), + allHealthChecks: boolean("allHealthChecks").notNull().default(false), + allResources: boolean("allResources").notNull().default(false), + lastTriggeredAt: bigint("lastTriggeredAt", { mode: "number" }), // nullable + createdAt: bigint("createdAt", { mode: "number" }).notNull(), + updatedAt: bigint("updatedAt", { mode: "number" }).notNull() +}); + +export const alertSites = pgTable("alertSites", { + alertRuleId: integer("alertRuleId") + .notNull() + .references(() => alertRules.alertRuleId, { onDelete: "cascade" }), + siteId: integer("siteId") + .notNull() + .references(() => sites.siteId, { onDelete: "cascade" }) +}); + +export const alertHealthChecks = pgTable("alertHealthChecks", { + alertRuleId: integer("alertRuleId") + .notNull() + .references(() => alertRules.alertRuleId, { onDelete: "cascade" }), + healthCheckId: integer("healthCheckId") + .notNull() + .references(() => targetHealthCheck.targetHealthCheckId, { + onDelete: "cascade" + }) +}); + +export const alertResources = pgTable("alertResources", { + alertRuleId: integer("alertRuleId") + .notNull() + .references(() => alertRules.alertRuleId, { onDelete: "cascade" }), + resourceId: integer("resourceId") + .notNull() + .references(() => resources.resourceId, { onDelete: "cascade" }) +}); + +// Separating channels by type avoids the mixed-shape problem entirely +export const alertEmailActions = pgTable("alertEmailActions", { + emailActionId: serial("emailActionId").primaryKey(), + alertRuleId: integer("alertRuleId") + .notNull() + .references(() => alertRules.alertRuleId, { onDelete: "cascade" }), + enabled: boolean("enabled").notNull().default(true), + lastSentAt: bigint("lastSentAt", { mode: "number" }) // nullable +}); + +export const alertEmailRecipients = pgTable("alertEmailRecipients", { + recipientId: serial("recipientId").primaryKey(), + emailActionId: integer("emailActionId") + .notNull() + .references(() => alertEmailActions.emailActionId, { + onDelete: "cascade" + }), + // At least one of these should be set - enforced at app level + userId: varchar("userId").references(() => users.userId, { + onDelete: "cascade" + }), + roleId: integer("roleId").references(() => roles.roleId, { + onDelete: "cascade" + }), + email: varchar("email", { length: 255 }) // external emails not tied to a user +}); + +export const alertWebhookActions = pgTable("alertWebhookActions", { + webhookActionId: serial("webhookActionId").primaryKey(), + alertRuleId: integer("alertRuleId") + .notNull() + .references(() => alertRules.alertRuleId, { onDelete: "cascade" }), + webhookUrl: text("webhookUrl").notNull(), + config: text("config"), // encrypted JSON with auth config (authType, credentials) + enabled: boolean("enabled").notNull().default(true), + lastSentAt: bigint("lastSentAt", { mode: "number" }) // nullable +}); + export type Approval = InferSelectModel; export type Limit = InferSelectModel; export type Account = InferSelectModel; @@ -495,3 +602,4 @@ export type EventStreamingDestination = InferSelectModel< export type EventStreamingCursor = InferSelectModel< typeof eventStreamingCursors >; +export type AlertResources = InferSelectModel; diff --git a/server/db/pg/schema/schema.ts b/server/db/pg/schema/schema.ts index acc3bb17f..b61cfcf19 100644 --- a/server/db/pg/schema/schema.ts +++ b/server/db/pg/schema/schema.ts @@ -57,7 +57,9 @@ export const orgs = pgTable("orgs", { settingsLogRetentionDaysAction: integer("settingsLogRetentionDaysAction") // where 0 = dont keep logs and -1 = keep forever and 9001 = end of the following year .notNull() .default(0), - settingsLogRetentionDaysConnection: integer("settingsLogRetentionDaysConnection") // where 0 = dont keep logs and -1 = keep forever and 9001 = end of the following year + settingsLogRetentionDaysConnection: integer( + "settingsLogRetentionDaysConnection" + ) // where 0 = dont keep logs and -1 = keep forever and 9001 = end of the following year .notNull() .default(0), sshCaPrivateKey: text("sshCaPrivateKey"), // Encrypted SSH CA private key (PEM format) @@ -101,7 +103,9 @@ export const sites = pgTable("sites", { lastHolePunch: bigint("lastHolePunch", { mode: "number" }), listenPort: integer("listenPort"), dockerSocketEnabled: boolean("dockerSocketEnabled").notNull().default(true), - status: varchar("status").$type<"pending" | "approved">().default("approved") + status: varchar("status") + .$type<"pending" | "approved">() + .default("approved") }); export const resources = pgTable("resources", { @@ -182,9 +186,18 @@ export const targets = pgTable("targets", { export const targetHealthCheck = pgTable("targetHealthCheck", { targetHealthCheckId: serial("targetHealthCheckId").primaryKey(), - targetId: integer("targetId") - .notNull() - .references(() => targets.targetId, { onDelete: "cascade" }), + targetId: integer("targetId").references(() => targets.targetId, { + onDelete: "cascade" + }), + orgId: varchar("orgId") + .references(() => orgs.orgId, { + onDelete: "cascade" + }) + .notNull(), + siteId: integer("siteId").references(() => sites.siteId, { + onDelete: "cascade" + }).notNull(), + name: varchar("name"), hcEnabled: boolean("hcEnabled").notNull().default(false), hcPath: varchar("hcPath"), hcScheme: varchar("hcScheme"), @@ -201,7 +214,9 @@ export const targetHealthCheck = pgTable("targetHealthCheck", { hcHealth: text("hcHealth") .$type<"unknown" | "healthy" | "unhealthy">() .default("unknown"), // "unknown", "healthy", "unhealthy" - hcTlsServerName: text("hcTlsServerName") + hcTlsServerName: text("hcTlsServerName"), + hcHealthyThreshold: integer("hcHealthyThreshold").default(1), + hcUnhealthyThreshold: integer("hcUnhealthyThreshold").default(1) }); export const exitNodes = pgTable("exitNodes", { @@ -222,16 +237,23 @@ export const exitNodes = pgTable("exitNodes", { export const siteResources = pgTable("siteResources", { // this is for the clients siteResourceId: serial("siteResourceId").primaryKey(), - siteId: integer("siteId") - .notNull() - .references(() => sites.siteId, { onDelete: "cascade" }), orgId: varchar("orgId") .notNull() .references(() => orgs.orgId, { onDelete: "cascade" }), + networkId: integer("networkId").references(() => networks.networkId, { + onDelete: "set null" + }), + defaultNetworkId: integer("defaultNetworkId").references( + () => networks.networkId, + { + onDelete: "restrict" + } + ), niceId: varchar("niceId").notNull(), name: varchar("name").notNull(), - mode: varchar("mode").$type<"host" | "cidr">().notNull(), // "host" | "cidr" | "port" - protocol: varchar("protocol"), // only for port mode + ssl: boolean("ssl").notNull().default(false), + mode: varchar("mode").$type<"host" | "cidr" | "http">().notNull(), // "host" | "cidr" | "http" + scheme: varchar("scheme").$type<"http" | "https">(), // only for when we are doing https or http mode proxyPort: integer("proxyPort"), // only for port mode destinationPort: integer("destinationPort"), // only for port mode destination: varchar("destination").notNull(), // ip, cidr, hostname; validate against the mode @@ -244,7 +266,38 @@ export const siteResources = pgTable("siteResources", { authDaemonPort: integer("authDaemonPort").default(22123), authDaemonMode: varchar("authDaemonMode", { length: 32 }) .$type<"site" | "remote">() - .default("site") + .default("site"), + domainId: varchar("domainId").references(() => domains.domainId, { + onDelete: "set null" + }), + subdomain: varchar("subdomain"), + fullDomain: varchar("fullDomain") +}); + +export const networks = pgTable("networks", { + networkId: serial("networkId").primaryKey(), + niceId: text("niceId"), + name: text("name"), + scope: varchar("scope") + .$type<"global" | "resource">() + .notNull() + .default("global"), + orgId: varchar("orgId") + .references(() => orgs.orgId, { + onDelete: "cascade" + }) + .notNull() +}); + +export const siteNetworks = pgTable("siteNetworks", { + siteId: integer("siteId") + .notNull() + .references(() => sites.siteId, { + onDelete: "cascade" + }), + networkId: integer("networkId") + .notNull() + .references(() => networks.networkId, { onDelete: "cascade" }) }); export const clientSiteResources = pgTable("clientSiteResources", { @@ -994,6 +1047,7 @@ export const requestAuditLog = pgTable( actor: text("actor"), actorId: text("actorId"), resourceId: integer("resourceId"), + siteResourceId: integer("siteResourceId"), ip: text("ip"), location: text("location"), userAgent: text("userAgent"), @@ -1041,6 +1095,20 @@ export const roundTripMessageTracker = pgTable("roundTripMessageTracker", { complete: boolean("complete").notNull().default(false) }); +export const statusHistory = pgTable("statusHistory", { + id: serial("id").primaryKey(), + entityType: varchar("entityType").notNull(), + entityId: integer("entityId").notNull(), + orgId: varchar("orgId") + .notNull() + .references(() => orgs.orgId, { onDelete: "cascade" }), + status: varchar("status").notNull(), + timestamp: integer("timestamp").notNull(), +}, (table) => [ + index("idx_statusHistory_entity").on(table.entityType, table.entityId, table.timestamp), + index("idx_statusHistory_org_timestamp").on(table.orgId, table.timestamp), +]); + export type Org = InferSelectModel; export type User = InferSelectModel; export type Site = InferSelectModel; @@ -1107,3 +1175,5 @@ export type RequestAuditLog = InferSelectModel; export type RoundTripMessageTracker = InferSelectModel< typeof roundTripMessageTracker >; +export type Network = InferSelectModel; +export type StatusHistory = InferSelectModel; diff --git a/server/db/sqlite/schema/privateSchema.ts b/server/db/sqlite/schema/privateSchema.ts index c1aa084a2..9a33e2049 100644 --- a/server/db/sqlite/schema/privateSchema.ts +++ b/server/db/sqlite/schema/privateSchema.ts @@ -13,9 +13,12 @@ import { domains, exitNodes, orgs, + resources, + roles, sessions, siteResources, sites, + targetHealthCheck, users } from "./schema"; @@ -82,6 +85,8 @@ export const subscriptions = sqliteTable("subscriptions", { createdAt: integer("createdAt").notNull(), updatedAt: integer("updatedAt"), version: integer("version"), + expiresAt: integer("expiresAt"), + trial: integer("trial", { mode: "boolean" }).default(false), billingCycleAnchor: integer("billingCycleAnchor"), type: text("type") // tier1, tier2, tier3, or license }); @@ -455,6 +460,94 @@ export const eventStreamingCursors = sqliteTable( ] ); +export const alertRules = sqliteTable("alertRules", { + alertRuleId: integer("alertRuleId").primaryKey({ autoIncrement: true }), + orgId: text("orgId") + .notNull() + .references(() => orgs.orgId, { onDelete: "cascade" }), + name: text("name").notNull(), + eventType: text("eventType") + .$type< + | "site_online" + | "site_offline" + | "site_toggle" + | "health_check_healthy" + | "health_check_unhealthy" + | "health_check_toggle" + | "resource_healthy" + | "resource_unhealthy" + | "resource_toggle" + >() + .notNull(), + enabled: integer("enabled", { mode: "boolean" }).notNull().default(true), + cooldownSeconds: integer("cooldownSeconds").notNull().default(300), + allSites: integer("allSites", { mode: "boolean" }).notNull().default(false), + allHealthChecks: integer("allHealthChecks", { mode: "boolean" }).notNull().default(false), + allResources: integer("allResources", { mode: "boolean" }).notNull().default(false), + lastTriggeredAt: integer("lastTriggeredAt"), + createdAt: integer("createdAt").notNull(), + updatedAt: integer("updatedAt").notNull() +}); + +export const alertSites = sqliteTable("alertSites", { + alertRuleId: integer("alertRuleId") + .notNull() + .references(() => alertRules.alertRuleId, { onDelete: "cascade" }), + siteId: integer("siteId") + .notNull() + .references(() => sites.siteId, { onDelete: "cascade" }) +}); + +export const alertHealthChecks = sqliteTable("alertHealthChecks", { + alertRuleId: integer("alertRuleId") + .notNull() + .references(() => alertRules.alertRuleId, { onDelete: "cascade" }), + healthCheckId: integer("healthCheckId") + .notNull() + .references(() => targetHealthCheck.targetHealthCheckId, { + onDelete: "cascade" + }) +}); + +export const alertResources = sqliteTable("alertResources", { + alertRuleId: integer("alertRuleId") + .notNull() + .references(() => alertRules.alertRuleId, { onDelete: "cascade" }), + resourceId: integer("resourceId") + .notNull() + .references(() => resources.resourceId, { onDelete: "cascade" }) +}); + +export const alertEmailActions = sqliteTable("alertEmailActions", { + emailActionId: integer("emailActionId").primaryKey({ autoIncrement: true }), + alertRuleId: integer("alertRuleId") + .notNull() + .references(() => alertRules.alertRuleId, { onDelete: "cascade" }), + enabled: integer("enabled", { mode: "boolean" }).notNull().default(true), + lastSentAt: integer("lastSentAt") +}); + +export const alertEmailRecipients = sqliteTable("alertEmailRecipients", { + recipientId: integer("recipientId").primaryKey({ autoIncrement: true }), + emailActionId: integer("emailActionId") + .notNull() + .references(() => alertEmailActions.emailActionId, { onDelete: "cascade" }), + userId: text("userId").references(() => users.userId, { onDelete: "cascade" }), + roleId: integer("roleId").references(() => roles.roleId, { onDelete: "cascade" }), + email: text("email") +}); + +export const alertWebhookActions = sqliteTable("alertWebhookActions", { + webhookActionId: integer("webhookActionId").primaryKey({ autoIncrement: true }), + alertRuleId: integer("alertRuleId") + .notNull() + .references(() => alertRules.alertRuleId, { onDelete: "cascade" }), + webhookUrl: text("webhookUrl").notNull(), + config: text("config"), // encrypted JSON with auth config (authType, credentials) + enabled: integer("enabled", { mode: "boolean" }).notNull().default(true), + lastSentAt: integer("lastSentAt") +}); + export type Approval = InferSelectModel; export type Limit = InferSelectModel; export type Account = InferSelectModel; @@ -486,3 +579,4 @@ export type EventStreamingDestination = InferSelectModel< export type EventStreamingCursor = InferSelectModel< typeof eventStreamingCursors >; +export type AlertResources = InferSelectModel; diff --git a/server/db/sqlite/schema/schema.ts b/server/db/sqlite/schema/schema.ts index 1fb04ef14..c5600b756 100644 --- a/server/db/sqlite/schema/schema.ts +++ b/server/db/sqlite/schema/schema.ts @@ -54,7 +54,9 @@ export const orgs = sqliteTable("orgs", { settingsLogRetentionDaysAction: integer("settingsLogRetentionDaysAction") // where 0 = dont keep logs and -1 = keep forever and 9001 = end of the following year .notNull() .default(0), - settingsLogRetentionDaysConnection: integer("settingsLogRetentionDaysConnection") // where 0 = dont keep logs and -1 = keep forever and 9001 = end of the following year + settingsLogRetentionDaysConnection: integer( + "settingsLogRetentionDaysConnection" + ) // where 0 = dont keep logs and -1 = keep forever and 9001 = end of the following year .notNull() .default(0), sshCaPrivateKey: text("sshCaPrivateKey"), // Encrypted SSH CA private key (PEM format) @@ -92,6 +94,9 @@ export const sites = sqliteTable("sites", { exitNodeId: integer("exitNode").references(() => exitNodes.exitNodeId, { onDelete: "set null" }), + networkId: integer("networkId").references(() => networks.networkId, { + onDelete: "set null" + }), name: text("name").notNull(), pubKey: text("pubKey"), subnet: text("subnet"), @@ -204,9 +209,18 @@ export const targetHealthCheck = sqliteTable("targetHealthCheck", { targetHealthCheckId: integer("targetHealthCheckId").primaryKey({ autoIncrement: true }), - targetId: integer("targetId") - .notNull() - .references(() => targets.targetId, { onDelete: "cascade" }), + targetId: integer("targetId").references(() => targets.targetId, { + onDelete: "cascade" + }), + orgId: text("orgId") + .references(() => orgs.orgId, { + onDelete: "cascade" + }) + .notNull(), + siteId: integer("siteId").references(() => sites.siteId, { + onDelete: "cascade" + }).notNull(), + name: text("name"), hcEnabled: integer("hcEnabled", { mode: "boolean" }) .notNull() .default(false), @@ -227,7 +241,9 @@ export const targetHealthCheck = sqliteTable("targetHealthCheck", { hcHealth: text("hcHealth") .$type<"unknown" | "healthy" | "unhealthy">() .default("unknown"), // "unknown", "healthy", "unhealthy" - hcTlsServerName: text("hcTlsServerName") + hcTlsServerName: text("hcTlsServerName"), + hcHealthyThreshold: integer("hcHealthyThreshold").default(1), + hcUnhealthyThreshold: integer("hcUnhealthyThreshold").default(1) }); export const exitNodes = sqliteTable("exitNodes", { @@ -250,16 +266,21 @@ export const siteResources = sqliteTable("siteResources", { siteResourceId: integer("siteResourceId").primaryKey({ autoIncrement: true }), - siteId: integer("siteId") - .notNull() - .references(() => sites.siteId, { onDelete: "cascade" }), orgId: text("orgId") .notNull() .references(() => orgs.orgId, { onDelete: "cascade" }), + networkId: integer("networkId").references(() => networks.networkId, { + onDelete: "set null" + }), + defaultNetworkId: integer("defaultNetworkId").references( + () => networks.networkId, + { onDelete: "restrict" } + ), niceId: text("niceId").notNull(), name: text("name").notNull(), - mode: text("mode").$type<"host" | "cidr">().notNull(), // "host" | "cidr" | "port" - protocol: text("protocol"), // only for port mode + ssl: integer("ssl", { mode: "boolean" }).notNull().default(false), + mode: text("mode").$type<"host" | "cidr" | "http">().notNull(), // "host" | "cidr" | "http" + scheme: text("scheme").$type<"http" | "https">(), // only for when we are doing https or http mode proxyPort: integer("proxyPort"), // only for port mode destinationPort: integer("destinationPort"), // only for port mode destination: text("destination").notNull(), // ip, cidr, hostname @@ -274,7 +295,36 @@ export const siteResources = sqliteTable("siteResources", { authDaemonPort: integer("authDaemonPort").default(22123), authDaemonMode: text("authDaemonMode") .$type<"site" | "remote">() - .default("site") + .default("site"), + domainId: text("domainId").references(() => domains.domainId, { + onDelete: "set null" + }), + subdomain: text("subdomain"), + fullDomain: text("fullDomain") +}); + +export const networks = sqliteTable("networks", { + networkId: integer("networkId").primaryKey({ autoIncrement: true }), + niceId: text("niceId"), + name: text("name"), + scope: text("scope") + .$type<"global" | "resource">() + .notNull() + .default("global"), + orgId: text("orgId") + .notNull() + .references(() => orgs.orgId, { onDelete: "cascade" }) +}); + +export const siteNetworks = sqliteTable("siteNetworks", { + siteId: integer("siteId") + .notNull() + .references(() => sites.siteId, { + onDelete: "cascade" + }), + networkId: integer("networkId") + .notNull() + .references(() => networks.networkId, { onDelete: "cascade" }) }); export const clientSiteResources = sqliteTable("clientSiteResources", { @@ -1096,6 +1146,7 @@ export const requestAuditLog = sqliteTable( actor: text("actor"), actorId: text("actorId"), resourceId: integer("resourceId"), + siteResourceId: integer("siteResourceId"), ip: text("ip"), location: text("location"), userAgent: text("userAgent"), @@ -1143,6 +1194,20 @@ export const roundTripMessageTracker = sqliteTable("roundTripMessageTracker", { complete: integer("complete", { mode: "boolean" }).notNull().default(false) }); +export const statusHistory = sqliteTable("statusHistory", { + id: integer("id").primaryKey({ autoIncrement: true }), + entityType: text("entityType").notNull(), // "site" | "healthCheck" + entityId: integer("entityId").notNull(), // siteId or targetHealthCheckId + orgId: text("orgId") + .notNull() + .references(() => orgs.orgId, { onDelete: "cascade" }), + status: text("status").notNull(), // "online"/"offline" for sites; "healthy"/"unhealthy"/"unknown" for healthChecks + timestamp: integer("timestamp").notNull(), // unix epoch seconds +}, (table) => [ + index("idx_statusHistory_entity").on(table.entityType, table.entityId, table.timestamp), + index("idx_statusHistory_org_timestamp").on(table.orgId, table.timestamp), +]); + export type Org = InferSelectModel; export type User = InferSelectModel; export type Site = InferSelectModel; @@ -1195,6 +1260,7 @@ export type ApiKey = InferSelectModel; export type ApiKeyAction = InferSelectModel; export type ApiKeyOrg = InferSelectModel; export type SiteResource = InferSelectModel; +export type Network = InferSelectModel; export type OrgDomains = InferSelectModel; export type SetupToken = InferSelectModel; export type HostMeta = InferSelectModel; @@ -1209,3 +1275,4 @@ export type DeviceWebAuthCode = InferSelectModel; export type RoundTripMessageTracker = InferSelectModel< typeof roundTripMessageTracker >; +export type StatusHistory = InferSelectModel; diff --git a/server/emails/templates/AlertNotification.tsx b/server/emails/templates/AlertNotification.tsx new file mode 100644 index 000000000..b540142d2 --- /dev/null +++ b/server/emails/templates/AlertNotification.tsx @@ -0,0 +1,212 @@ +import React from "react"; +import { Body, Head, Html, Preview, Tailwind } from "@react-email/components"; +import { themeColors } from "./lib/theme"; +import { + EmailContainer, + EmailFooter, + EmailGreeting, + EmailHeading, + EmailInfoSection, + EmailLetterHead, + EmailSection, + EmailSignature, + EmailText +} from "./components/Email"; +import ButtonLink from "./components/ButtonLink"; + +export type AlertEventType = + | "site_online" + | "site_offline" + | "site_toggle" + | "health_check_healthy" + | "health_check_unhealthy" + | "health_check_toggle" + | "resource_healthy" + | "resource_unhealthy" + | "resource_toggle"; + +export type AlertNotificationProps = { + eventType: AlertEventType; + orgId: string; + data: Record; + dashboardLink: string; +}; + +function getEventMeta(eventType: AlertEventType): { + heading: string; + previewText: string; + summary: string; + statusLabel: string; + statusColor: string; +} { + switch (eventType) { + case "site_online": + return { + heading: "Site Back Online", + previewText: "A site in your organization is back online.", + summary: + "Good news – a site in your organization has come back online and is now reachable.", + statusLabel: "Online", + statusColor: "#16a34a" + }; + case "site_offline": + return { + heading: "Site Offline", + previewText: "A site in your organization has gone offline.", + summary: + "A site in your organization has gone offline and is no longer reachable.", + statusLabel: "Offline", + statusColor: "#dc2626" + }; + case "site_toggle": + return { + heading: "Site Status Changed", + previewText: "A site in your organization has changed status.", + summary: "A site in your organization has changed status.", + statusLabel: "Status Changed", + statusColor: "#f59e0b" + }; + case "health_check_healthy": + return { + heading: "Health Check Recovered", + previewText: + "A health check in your organization is now healthy.", + summary: + "A health check in your organization has recovered and is now reporting a healthy status.", + statusLabel: "Healthy", + statusColor: "#16a34a" + }; + case "health_check_unhealthy": + return { + heading: "Health Check Failing", + previewText: + "A health check in your organization is not healthy.", + summary: + "A health check in your organization is currently failing.", + statusLabel: "Not Healthy", + statusColor: "#dc2626" + }; + case "health_check_toggle": + return { + heading: "Health Check Status Changed", + previewText: + "A health check in your organization has changed status.", + summary: + "A health check in your organization has changed status.", + statusLabel: "Status Changed", + statusColor: "#f59e0b" + }; + case "resource_healthy": + return { + heading: "Resource Healthy", + previewText: "A resource in your organization is now healthy.", + summary: + "A resource in your organization has recovered and is now reporting a healthy status.", + statusLabel: "Healthy", + statusColor: "#16a34a" + }; + case "resource_unhealthy": + return { + heading: "Resource Unhealthy", + previewText: "A resource in your organization is not healthy.", + summary: + "A resource in your organization is currently unhealthy.", + statusLabel: "Unhealthy", + statusColor: "#dc2626" + }; + case "resource_toggle": + return { + heading: "Resource Status Changed", + previewText: + "A resource in your organization has changed status.", + summary: "A resource in your organization has changed status.", + statusLabel: "Status Changed", + statusColor: "#f59e0b" + }; + default: + return { + heading: "Alert Notification", + previewText: + "An alert event has occurred in your organization.", + summary: "An alert event has occurred in your organization.", + statusLabel: "Alert", + statusColor: "#f59e0b" + }; + } +} + +function formatDataItems( + data: Record +): { label: string; value: React.ReactNode }[] { + return Object.entries(data) + .filter(([key]) => key !== "orgId") + .map(([key, value]) => ({ + label: key + .replace(/([A-Z])/g, " $1") + .replace(/^./, (s) => s.toUpperCase()) + .trim(), + value: String(value ?? "-") + })); +} + +export const AlertNotification = (props: AlertNotificationProps) => { + const { eventType, orgId, data, dashboardLink } = props; + const meta = getEventMeta(eventType); + const dataItems = formatDataItems(data); + + const allItems: { label: string; value: React.ReactNode }[] = [ + { label: "Organization", value: orgId }, + { + label: "Status", + value: ( + + {meta.statusLabel} + + ) + }, + { label: "Time", value: new Date().toUTCString() }, + ...dataItems + ]; + + return ( + + + {meta.previewText} + + + + + + {meta.heading} + + Hi there, + + {meta.summary} + + + + + Open your dashboard to view more details and manage + your alert rules. + + + + + Open Dashboard + + + + + + + + + + + ); +}; + +export default AlertNotification; diff --git a/server/emails/templates/EnterpriseEditionKeyGenerated.tsx b/server/emails/templates/EnterpriseEditionKeyGenerated.tsx index 44472c8a6..82154ab7d 100644 --- a/server/emails/templates/EnterpriseEditionKeyGenerated.tsx +++ b/server/emails/templates/EnterpriseEditionKeyGenerated.tsx @@ -32,7 +32,7 @@ export const EnterpriseEditionKeyGenerated = ({ }: EnterpriseEditionKeyGeneratedProps) => { const previewText = personalUseOnly ? "Your Enterprise Edition key for personal use is ready" - : "Thank you for your purchase — your Enterprise Edition key is ready"; + : "Thank you for your purchase - your Enterprise Edition key is ready"; return ( diff --git a/server/emails/templates/NotifyTrialExpiring.tsx b/server/emails/templates/NotifyTrialExpiring.tsx new file mode 100644 index 000000000..7cd6d30ac --- /dev/null +++ b/server/emails/templates/NotifyTrialExpiring.tsx @@ -0,0 +1,127 @@ +import React from "react"; +import { Body, Head, Html, Preview, Tailwind } from "@react-email/components"; +import { themeColors } from "./lib/theme"; +import { + EmailContainer, + EmailFooter, + EmailGreeting, + EmailHeading, + EmailLetterHead, + EmailSignature, + EmailText +} from "./components/Email"; + +interface Props { + email: string; + orgName: string; + trialEndsAt: string; + daysRemaining: number | null; + billingLink: string; +} + +export const NotifyTrialExpiring = ({ + email, + orgName, + trialEndsAt, + daysRemaining, + billingLink +}: Props) => { + const hasEnded = daysRemaining === null || daysRemaining === 0; + const isLastDay = daysRemaining === 1; + + const previewText = hasEnded + ? `Your trial for ${orgName} has ended.` + : isLastDay + ? `Your trial for ${orgName} ends tomorrow.` + : `Your trial for ${orgName} ends in ${daysRemaining} days.`; + + const heading = hasEnded + ? "Your Trial Ended" + : "Your Trial is Ending Soon"; + + return ( + + + {previewText} + + + + + + {heading} + + Hi there, + + {hasEnded ? ( + <> + + Your free trial for{" "} + {orgName} ended on{" "} + {trialEndsAt}. Your account + has been moved to the free plan, which + includes limited functionality. + + + + Some features and resources may now be + restricted or disconnected. To restore full + access and continue using all the features + you had during your trial, please upgrade to + a paid plan. + + + + You can{" "} + + upgrade your plan here + {" "} + to get back up and running right away. + + + ) : ( + <> + + Just a reminder that your free trial for{" "} + {orgName} will end on{" "} + {trialEndsAt} + {isLastDay + ? " — that's tomorrow!" + : `, in ${daysRemaining} days`} + . + + + + After your trial ends, your account will be + moved to the free plan and some + functionality may be restricted or your + sites may disconnect. + + + + To avoid any interruption to your service, + we encourage you to upgrade before your + trial expires. You can{" "} + + upgrade your plan here + + . + + + )} + + + If you have any questions or need assistance, please + don't hesitate to reach out to our support team. + + + + + + + + + + ); +}; + +export default NotifyTrialExpiring; diff --git a/server/emails/templates/components/Email.tsx b/server/emails/templates/components/Email.tsx index 71d8b4671..f74046042 100644 --- a/server/emails/templates/components/Email.tsx +++ b/server/emails/templates/components/Email.tsx @@ -5,7 +5,7 @@ import { build } from "@server/build"; // EmailContainer: Wraps the entire email layout export function EmailContainer({ children }: { children: React.ReactNode }) { return ( - + {children} ); @@ -18,7 +18,7 @@ export function EmailLetterHead() { Pangolin Logo diff --git a/server/index.ts b/server/index.ts index 0fc44c279..e3a6ba049 100644 --- a/server/index.ts +++ b/server/index.ts @@ -22,6 +22,7 @@ import { TraefikConfigManager } from "@server/lib/traefik/TraefikConfigManager"; import { initCleanup } from "#dynamic/cleanup"; import license from "#dynamic/license/license"; import { initLogCleanupInterval } from "@server/lib/cleanupLogs"; +import { initAcmeCertSync } from "#dynamic/lib/acmeCertSync"; import { fetchServerIp } from "@server/lib/serverIpService"; async function startServers() { @@ -39,6 +40,7 @@ async function startServers() { initTelemetryClient(); initLogCleanupInterval(); + initAcmeCertSync(); // Start all servers const apiServer = createApiServer(); diff --git a/server/internalServer.ts b/server/internalServer.ts index 7ba046e4b..83872e7f9 100644 --- a/server/internalServer.ts +++ b/server/internalServer.ts @@ -36,7 +36,7 @@ export function createInternalServer() { internalServer.listen(internalPort, (err?: any) => { if (err) throw err; logger.info( - `Internal server is running on http://localhost:${internalPort}` + `Internal API server is running on http://localhost:${internalPort}` ); }); diff --git a/server/lib/acmeCertSync.ts b/server/lib/acmeCertSync.ts new file mode 100644 index 000000000..d8fbd6368 --- /dev/null +++ b/server/lib/acmeCertSync.ts @@ -0,0 +1,3 @@ +export function initAcmeCertSync(): void { + // stub +} \ No newline at end of file diff --git a/server/lib/alerts/events/healthCheckEvents.ts b/server/lib/alerts/events/healthCheckEvents.ts new file mode 100644 index 000000000..dacb5287a --- /dev/null +++ b/server/lib/alerts/events/healthCheckEvents.ts @@ -0,0 +1,19 @@ +// stub + +export async function fireHealthCheckHealthyAlert( + orgId: string, + healthCheckId: number, + healthCheckName?: string, + extra?: Record +): Promise { + return; +} + +export async function fireHealthCheckNotHealthyAlert( + orgId: string, + healthCheckId: number, + healthCheckName?: string, + extra?: Record +): Promise { + return; +} diff --git a/server/lib/alerts/events/siteEvents.ts b/server/lib/alerts/events/siteEvents.ts new file mode 100644 index 000000000..8426fa9c2 --- /dev/null +++ b/server/lib/alerts/events/siteEvents.ts @@ -0,0 +1,19 @@ +// stub + +export async function fireSiteOnlineAlert( + orgId: string, + siteId: number, + siteName?: string, + extra?: Record +): Promise { + return; +} + +export async function fireSiteOfflineAlert( + orgId: string, + siteId: number, + siteName?: string, + extra?: Record +): Promise { + return; +} diff --git a/server/lib/alerts/index.ts b/server/lib/alerts/index.ts new file mode 100644 index 000000000..017603253 --- /dev/null +++ b/server/lib/alerts/index.ts @@ -0,0 +1,2 @@ +export * from "./events/siteEvents"; +export * from "./events/healthCheckEvents"; diff --git a/server/lib/billing/tierMatrix.ts b/server/lib/billing/tierMatrix.ts index 0756ea665..5ae57c8a7 100644 --- a/server/lib/billing/tierMatrix.ts +++ b/server/lib/billing/tierMatrix.ts @@ -20,7 +20,10 @@ export enum TierFeature { FullRbac = "fullRbac", SiteProvisioningKeys = "siteProvisioningKeys", // handle downgrade by revoking keys if needed SIEM = "siem", // handle downgrade by disabling SIEM integrations - DomainNamespaces = "domainNamespaces" // handle downgrade by removing custom domain namespaces + HTTPPrivateResources = "httpPrivateResources", // handle downgrade by disabling HTTP private resources + DomainNamespaces = "domainNamespaces", // handle downgrade by removing custom domain namespaces + StandaloneHealthChecks = "standaloneHealthChecks", + AlertingRules = "alertingRules" } export const tierMatrix: Record = { @@ -58,5 +61,8 @@ export const tierMatrix: Record = { [TierFeature.FullRbac]: ["tier1", "tier2", "tier3", "enterprise"], [TierFeature.SiteProvisioningKeys]: ["tier3", "enterprise"], [TierFeature.SIEM]: ["enterprise"], - [TierFeature.DomainNamespaces]: ["tier1", "tier2", "tier3", "enterprise"] + [TierFeature.HTTPPrivateResources]: ["tier3", "enterprise"], + [TierFeature.DomainNamespaces]: ["tier1", "tier2", "tier3", "enterprise"], + [TierFeature.StandaloneHealthChecks]: ["tier2", "tier3", "enterprise"], + [TierFeature.AlertingRules]: ["tier2", "tier3", "enterprise"] }; diff --git a/server/lib/blueprints/applyBlueprint.ts b/server/lib/blueprints/applyBlueprint.ts index a304bb392..fd189e6ca 100644 --- a/server/lib/blueprints/applyBlueprint.ts +++ b/server/lib/blueprints/applyBlueprint.ts @@ -121,8 +121,8 @@ export async function applyBlueprint({ for (const result of clientResourcesResults) { if ( result.oldSiteResource && - result.oldSiteResource.siteId != - result.newSiteResource.siteId + JSON.stringify(result.newSites?.sort()) !== + JSON.stringify(result.oldSites?.sort()) ) { // query existing associations const existingRoleIds = await trx @@ -222,38 +222,46 @@ export async function applyBlueprint({ trx ); } else { - const [newSite] = await trx - .select() - .from(sites) - .innerJoin(newts, eq(sites.siteId, newts.siteId)) - .where( - and( - eq(sites.siteId, result.newSiteResource.siteId), - eq(sites.orgId, orgId), - eq(sites.type, "newt"), - isNotNull(sites.pubKey) + let good = true; + for (const newSite of result.newSites) { + const [site] = await trx + .select() + .from(sites) + .innerJoin(newts, eq(sites.siteId, newts.siteId)) + .where( + and( + eq(sites.siteId, newSite.siteId), + eq(sites.orgId, orgId), + eq(sites.type, "newt"), + isNotNull(sites.pubKey) + ) ) - ) - .limit(1); + .limit(1); + + if (!site) { + logger.debug( + `No newt sites found for client resource ${result.newSiteResource.siteResourceId}, skipping target update` + ); + good = false; + break; + } - if (!newSite) { logger.debug( - `No newt site found for client resource ${result.newSiteResource.siteResourceId}, skipping target update` + `Updating client resource ${result.newSiteResource.siteResourceId} on site ${newSite.siteId}` ); - continue; } - logger.debug( - `Updating client resource ${result.newSiteResource.siteResourceId} on site ${newSite.sites.siteId}` - ); + if (!good) { + continue; + } await handleMessagingForUpdatedSiteResource( result.oldSiteResource, result.newSiteResource, - { - siteId: newSite.sites.siteId, - orgId: newSite.sites.orgId - }, + result.newSites.map((site) => ({ + siteId: site.siteId, + orgId: result.newSiteResource.orgId + })), trx ); } diff --git a/server/lib/blueprints/clientResources.ts b/server/lib/blueprints/clientResources.ts index 80c691c63..df1fd0cfb 100644 --- a/server/lib/blueprints/clientResources.ts +++ b/server/lib/blueprints/clientResources.ts @@ -1,24 +1,104 @@ import { clients, clientSiteResources, + domains, + orgDomains, roles, roleSiteResources, + Site, SiteResource, + siteNetworks, siteResources, Transaction, userOrgs, users, - userSiteResources + userSiteResources, + networks } from "@server/db"; import { sites } from "@server/db"; -import { eq, and, ne, inArray, or } from "drizzle-orm"; +import { eq, and, ne, inArray, or, isNotNull } from "drizzle-orm"; import { Config } from "./types"; import logger from "@server/logger"; import { getNextAvailableAliasAddress } from "../ip"; +import { createCertificate } from "#dynamic/routers/certificates/createCertificate"; + +async function getDomainForSiteResource( + siteResourceId: number | undefined, + fullDomain: string, + orgId: string, + trx: Transaction +): Promise<{ subdomain: string | null; domainId: string }> { + const [fullDomainExists] = await trx + .select({ siteResourceId: siteResources.siteResourceId }) + .from(siteResources) + .where( + and( + eq(siteResources.fullDomain, fullDomain), + eq(siteResources.orgId, orgId), + siteResourceId + ? ne(siteResources.siteResourceId, siteResourceId) + : isNotNull(siteResources.siteResourceId) + ) + ) + .limit(1); + + if (fullDomainExists) { + throw new Error( + `Site resource already exists with domain: ${fullDomain} in org ${orgId}` + ); + } + + const possibleDomains = await trx + .select() + .from(domains) + .innerJoin(orgDomains, eq(domains.domainId, orgDomains.domainId)) + .where(and(eq(orgDomains.orgId, orgId), eq(domains.verified, true))) + .execute(); + + if (possibleDomains.length === 0) { + throw new Error( + `Domain not found for full-domain: ${fullDomain} in org ${orgId}` + ); + } + + const validDomains = possibleDomains.filter((domain) => { + if (domain.domains.type == "ns" || domain.domains.type == "wildcard") { + return ( + fullDomain === domain.domains.baseDomain || + fullDomain.endsWith(`.${domain.domains.baseDomain}`) + ); + } else if (domain.domains.type == "cname") { + return fullDomain === domain.domains.baseDomain; + } + }); + + if (validDomains.length === 0) { + throw new Error( + `Domain not found for full-domain: ${fullDomain} in org ${orgId}` + ); + } + + const domainSelection = validDomains[0].domains; + const baseDomain = domainSelection.baseDomain; + + let subdomain: string | null = null; + if (fullDomain !== baseDomain) { + subdomain = fullDomain.replace(`.${baseDomain}`, ""); + } + + await createCertificate(domainSelection.domainId, fullDomain, trx); + + return { + subdomain, + domainId: domainSelection.domainId + }; +} export type ClientResourcesResults = { newSiteResource: SiteResource; oldSiteResource?: SiteResource; + newSites: { siteId: number }[]; + oldSites: { siteId: number }[]; }[]; export async function updateClientResources( @@ -43,53 +123,104 @@ export async function updateClientResources( ) .limit(1); - const resourceSiteId = resourceData.site; - let site; + const existingSiteIds = existingResource?.networkId + ? await trx + .select({ siteId: sites.siteId }) + .from(siteNetworks) + .where(eq(siteNetworks.networkId, existingResource.networkId)) + : []; - if (resourceSiteId) { - // Look up site by niceId - [site] = await trx - .select({ siteId: sites.siteId }) - .from(sites) - .where( - and( - eq(sites.niceId, resourceSiteId), - eq(sites.orgId, orgId) + let allSites: { siteId: number }[] = []; + if (resourceData.site) { + let siteSingle; + const resourceSiteId = resourceData.site; + + if (resourceSiteId) { + // Look up site by niceId + [siteSingle] = await trx + .select({ siteId: sites.siteId }) + .from(sites) + .where( + and( + eq(sites.niceId, resourceSiteId), + eq(sites.orgId, orgId) + ) ) - ) - .limit(1); - } else if (siteId) { - // Use the provided siteId directly, but verify it belongs to the org - [site] = await trx - .select({ siteId: sites.siteId }) - .from(sites) - .where(and(eq(sites.siteId, siteId), eq(sites.orgId, orgId))) - .limit(1); - } else { - throw new Error(`Target site is required`); + .limit(1); + } else if (siteId) { + // Use the provided siteId directly, but verify it belongs to the org + [siteSingle] = await trx + .select({ siteId: sites.siteId }) + .from(sites) + .where( + and(eq(sites.siteId, siteId), eq(sites.orgId, orgId)) + ) + .limit(1); + } else { + throw new Error(`Target site is required`); + } + + if (!siteSingle) { + throw new Error( + `Site not found: ${resourceSiteId} in org ${orgId}` + ); + } + allSites.push(siteSingle); } - if (!site) { - throw new Error( - `Site not found: ${resourceSiteId} in org ${orgId}` - ); + if (resourceData.sites) { + for (const siteNiceId of resourceData.sites) { + const [site] = await trx + .select({ siteId: sites.siteId }) + .from(sites) + .where( + and( + eq(sites.niceId, siteNiceId), + eq(sites.orgId, orgId) + ) + ) + .limit(1); + if (!site) { + throw new Error( + `Site not found: ${siteId} in org ${orgId}` + ); + } + allSites.push(site); + } } if (existingResource) { + let domainInfo: + | { subdomain: string | null; domainId: string } + | undefined; + if (resourceData["full-domain"] && resourceData.mode === "http") { + domainInfo = await getDomainForSiteResource( + existingResource.siteResourceId, + resourceData["full-domain"], + orgId, + trx + ); + } + // Update existing resource const [updatedResource] = await trx .update(siteResources) .set({ name: resourceData.name || resourceNiceId, - siteId: site.siteId, mode: resourceData.mode, + ssl: resourceData.ssl, + scheme: resourceData.scheme, destination: resourceData.destination, + destinationPort: resourceData["destination-port"], enabled: true, // hardcoded for now // enabled: resourceData.enabled ?? true, alias: resourceData.alias || null, disableIcmp: resourceData["disable-icmp"], tcpPortRangeString: resourceData["tcp-ports"], - udpPortRangeString: resourceData["udp-ports"] + udpPortRangeString: resourceData["udp-ports"], + fullDomain: resourceData["full-domain"] || null, + subdomain: domainInfo ? domainInfo.subdomain : null, + domainId: domainInfo ? domainInfo.domainId : null }) .where( eq( @@ -100,7 +231,21 @@ export async function updateClientResources( .returning(); const siteResourceId = existingResource.siteResourceId; - const orgId = existingResource.orgId; + + if (updatedResource.networkId) { + await trx + .delete(siteNetworks) + .where( + eq(siteNetworks.networkId, updatedResource.networkId) + ); + + for (const site of allSites) { + await trx.insert(siteNetworks).values({ + siteId: site.siteId, + networkId: updatedResource.networkId + }); + } + } await trx .delete(clientSiteResources) @@ -204,37 +349,72 @@ export async function updateClientResources( results.push({ newSiteResource: updatedResource, - oldSiteResource: existingResource + oldSiteResource: existingResource, + newSites: allSites, + oldSites: existingSiteIds }); } else { let aliasAddress: string | null = null; - if (resourceData.mode == "host") { - // we can only have an alias on a host + if (resourceData.mode === "host" || resourceData.mode === "http") { aliasAddress = await getNextAvailableAliasAddress(orgId); } + let domainInfo: + | { subdomain: string | null; domainId: string } + | undefined; + if (resourceData["full-domain"] && resourceData.mode === "http") { + domainInfo = await getDomainForSiteResource( + undefined, + resourceData["full-domain"], + orgId, + trx + ); + } + + const [network] = await trx + .insert(networks) + .values({ + scope: "resource", + orgId: orgId + }) + .returning(); + // Create new resource const [newResource] = await trx .insert(siteResources) .values({ orgId: orgId, - siteId: site.siteId, niceId: resourceNiceId, + networkId: network.networkId, + defaultNetworkId: network.networkId, name: resourceData.name || resourceNiceId, mode: resourceData.mode, + ssl: resourceData.ssl, + scheme: resourceData.scheme, destination: resourceData.destination, + destinationPort: resourceData["destination-port"], enabled: true, // hardcoded for now // enabled: resourceData.enabled ?? true, alias: resourceData.alias || null, aliasAddress: aliasAddress, disableIcmp: resourceData["disable-icmp"], tcpPortRangeString: resourceData["tcp-ports"], - udpPortRangeString: resourceData["udp-ports"] + udpPortRangeString: resourceData["udp-ports"], + fullDomain: resourceData["full-domain"] || null, + subdomain: domainInfo ? domainInfo.subdomain : null, + domainId: domainInfo ? domainInfo.domainId : null }) .returning(); const siteResourceId = newResource.siteResourceId; + for (const site of allSites) { + await trx.insert(siteNetworks).values({ + siteId: site.siteId, + networkId: network.networkId + }); + } + const [adminRole] = await trx .select() .from(roles) @@ -324,7 +504,11 @@ export async function updateClientResources( `Created new client resource ${newResource.name} (${newResource.siteResourceId}) for org ${orgId}` ); - results.push({ newSiteResource: newResource }); + results.push({ + newSiteResource: newResource, + newSites: allSites, + oldSites: existingSiteIds + }); } } diff --git a/server/lib/blueprints/proxyResources.ts b/server/lib/blueprints/proxyResources.ts index e16da2ea5..175c8c79f 100644 --- a/server/lib/blueprints/proxyResources.ts +++ b/server/lib/blueprints/proxyResources.ts @@ -140,7 +140,10 @@ export async function updateProxyResources( const [newHealthcheck] = await trx .insert(targetHealthCheck) .values({ + name: `${targetData.hostname}:${targetData.port}`, + siteId: site.siteId, targetId: newTarget.targetId, + orgId: orgId, hcEnabled: healthcheckData?.enabled || false, hcPath: healthcheckData?.path, hcScheme: healthcheckData?.scheme, @@ -158,7 +161,9 @@ export async function updateProxyResources( healthcheckData?.["follow-redirects"], hcMethod: healthcheckData?.method, hcStatus: healthcheckData?.status, - hcHealth: "unknown" + hcHealth: "unknown", + hcHealthyThreshold: healthcheckData?.["healthy-threshold"], + hcUnhealthyThreshold: healthcheckData?.["unhealthy-threshold"] }) .returning(); @@ -522,7 +527,9 @@ export async function updateProxyResources( healthcheckData?.followRedirects || healthcheckData?.["follow-redirects"], hcMethod: healthcheckData?.method, - hcStatus: healthcheckData?.status + hcStatus: healthcheckData?.status, + hcHealthyThreshold: healthcheckData?.["healthy-threshold"], + hcUnhealthyThreshold: healthcheckData?.["unhealthy-threshold"] }) .where( eq( @@ -1081,6 +1088,8 @@ function checkIfHealthcheckChanged( JSON.stringify(incoming.hcHeaders) ) return true; + if (existing.hcHealthyThreshold !== incoming.hcHealthyThreshold) return true; + if (existing.hcUnhealthyThreshold !== incoming.hcUnhealthyThreshold) return true; return false; } @@ -1100,7 +1109,7 @@ function checkIfTargetChanged( return false; } -async function getDomain( +export async function getDomain( resourceId: number | undefined, fullDomain: string, orgId: string, diff --git a/server/lib/blueprints/types.ts b/server/lib/blueprints/types.ts index 6ebc509b8..913cf31ed 100644 --- a/server/lib/blueprints/types.ts +++ b/server/lib/blueprints/types.ts @@ -12,7 +12,7 @@ export const TargetHealthCheckSchema = z.object({ hostname: z.string(), port: z.int().min(1).max(65535), enabled: z.boolean().optional().default(true), - path: z.string().optional().default("/"), + path: z.string().optional(), scheme: z.string().optional(), mode: z.string().default("http"), interval: z.int().default(30), @@ -26,8 +26,10 @@ export const TargetHealthCheckSchema = z.object({ .default(null), "follow-redirects": z.boolean().default(true), followRedirects: z.boolean().optional(), // deprecated alias - method: z.string().default("GET"), - status: z.int().optional() + method: z.string().optional(), + status: z.int().optional(), + "healthy-threshold": z.int().min(1).optional().default(1), + "unhealthy-threshold": z.int().min(1).optional().default(1) }); // Schema for individual target within a resource @@ -164,6 +166,7 @@ export const ResourceSchema = z name: z.string().optional(), protocol: z.enum(["http", "tcp", "udp"]).optional(), ssl: z.boolean().optional(), + scheme: z.enum(["http", "https"]).optional(), "full-domain": z.string().optional(), "proxy-port": z.int().min(1).max(65535).optional(), enabled: z.boolean().optional(), @@ -325,16 +328,20 @@ export function isTargetsOnlyResource(resource: any): boolean { export const ClientResourceSchema = z .object({ name: z.string().min(1).max(255), - mode: z.enum(["host", "cidr"]), - site: z.string(), + mode: z.enum(["host", "cidr", "http"]), + site: z.string(), // DEPRECATED IN FAVOR OF sites + sites: z.array(z.string()).optional().default([]), // protocol: z.enum(["tcp", "udp"]).optional(), // proxyPort: z.int().positive().optional(), - // destinationPort: z.int().positive().optional(), + "destination-port": z.int().positive().optional(), destination: z.string().min(1), // enabled: z.boolean().default(true), "tcp-ports": portRangeStringSchema.optional().default("*"), "udp-ports": portRangeStringSchema.optional().default("*"), "disable-icmp": z.boolean().optional().default(false), + "full-domain": z.string().optional(), + ssl: z.boolean().optional(), + scheme: z.enum(["http", "https"]).optional().nullable(), alias: z .string() .regex( @@ -477,6 +484,39 @@ export const ConfigSchema = z }); } + // Enforce the full-domain uniqueness across client-resources in the same stack + const clientFullDomainMap = new Map(); + + Object.entries(config["client-resources"]).forEach( + ([resourceKey, resource]) => { + const fullDomain = resource["full-domain"]; + if (fullDomain) { + if (!clientFullDomainMap.has(fullDomain)) { + clientFullDomainMap.set(fullDomain, []); + } + clientFullDomainMap.get(fullDomain)!.push(resourceKey); + } + } + ); + + const clientFullDomainDuplicates = Array.from( + clientFullDomainMap.entries() + ) + .filter(([_, resourceKeys]) => resourceKeys.length > 1) + .map( + ([fullDomain, resourceKeys]) => + `'${fullDomain}' used by resources: ${resourceKeys.join(", ")}` + ) + .join("; "); + + if (clientFullDomainDuplicates.length !== 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ["client-resources"], + message: `Duplicate 'full-domain' values found: ${clientFullDomainDuplicates}` + }); + } + // Enforce proxy-port uniqueness within proxy-resources per protocol const protocolPortMap = new Map(); diff --git a/server/lib/certificates.ts b/server/lib/certificates.ts index f5860ff3a..0b1688015 100644 --- a/server/lib/certificates.ts +++ b/server/lib/certificates.ts @@ -1,5 +1,6 @@ export async function getValidCertificatesForDomains( - domains: Set + domains: Set, + useCache: boolean ): Promise< Array<{ id: number; diff --git a/server/lib/consts.ts b/server/lib/consts.ts index 8ad4f48e9..d2218e874 100644 --- a/server/lib/consts.ts +++ b/server/lib/consts.ts @@ -2,7 +2,7 @@ import path from "path"; import { fileURLToPath } from "url"; // This is a placeholder value replaced by the build process -export const APP_VERSION = "1.17.0"; +export const APP_VERSION = "1.18.0"; export const __FILENAME = fileURLToPath(import.meta.url); export const __DIRNAME = path.dirname(__FILENAME); diff --git a/server/lib/encryption.ts b/server/lib/encryption.ts deleted file mode 100644 index 79caecd1a..000000000 --- a/server/lib/encryption.ts +++ /dev/null @@ -1,39 +0,0 @@ -import crypto from "crypto"; - -export function encryptData(data: string, key: Buffer): string { - const algorithm = "aes-256-gcm"; - const iv = crypto.randomBytes(16); - const cipher = crypto.createCipheriv(algorithm, key, iv); - - let encrypted = cipher.update(data, "utf8", "hex"); - encrypted += cipher.final("hex"); - - const authTag = cipher.getAuthTag(); - - // Combine IV, auth tag, and encrypted data - return iv.toString("hex") + ":" + authTag.toString("hex") + ":" + encrypted; -} - -// Helper function to decrypt data (you'll need this to read certificates) -export function decryptData(encryptedData: string, key: Buffer): string { - const algorithm = "aes-256-gcm"; - const parts = encryptedData.split(":"); - - if (parts.length !== 3) { - throw new Error("Invalid encrypted data format"); - } - - const iv = Buffer.from(parts[0], "hex"); - const authTag = Buffer.from(parts[1], "hex"); - const encrypted = parts[2]; - - const decipher = crypto.createDecipheriv(algorithm, key, iv); - decipher.setAuthTag(authTag); - - let decrypted = decipher.update(encrypted, "hex", "utf8"); - decrypted += decipher.final("utf8"); - - return decrypted; -} - -// openssl rand -hex 32 > config/encryption.key diff --git a/server/lib/ip.ts b/server/lib/ip.ts index 633983629..3e57e8c94 100644 --- a/server/lib/ip.ts +++ b/server/lib/ip.ts @@ -5,6 +5,7 @@ import config from "@server/lib/config"; import z from "zod"; import logger from "@server/logger"; import semver from "semver"; +import { getValidCertificatesForDomains } from "#dynamic/lib/certificates"; interface IPRange { start: bigint; @@ -477,9 +478,9 @@ export type Alias = { alias: string | null; aliasAddress: string | null }; export function generateAliasConfig(allSiteResources: SiteResource[]): Alias[] { return allSiteResources - .filter((sr) => sr.alias && sr.aliasAddress && sr.mode == "host") + .filter((sr) => sr.aliasAddress && ((sr.alias && sr.mode == "host") || (sr.fullDomain && sr.mode == "http"))) .map((sr) => ({ - alias: sr.alias, + alias: sr.alias || sr.fullDomain, aliasAddress: sr.aliasAddress })); } @@ -582,16 +583,26 @@ export type SubnetProxyTargetV2 = { protocol: "tcp" | "udp"; }[]; resourceId?: number; + protocol?: "http" | "https"; // if set, this target only applies to the specified protocol + httpTargets?: HTTPTarget[]; + tlsCert?: string; + tlsKey?: string; }; -export function generateSubnetProxyTargetV2( +export type HTTPTarget = { + destAddr: string; // must be an IP or hostname + destPort: number; + scheme: "http" | "https"; +}; + +export async function generateSubnetProxyTargetV2( siteResource: SiteResource, clients: { clientId: number; pubKey: string | null; subnet: string | null; }[] -): SubnetProxyTargetV2[] | undefined { +): Promise { if (clients.length === 0) { logger.debug( `No clients have access to site resource ${siteResource.siteResourceId}, skipping target generation.` @@ -642,6 +653,67 @@ export function generateSubnetProxyTargetV2( disableIcmp, resourceId: siteResource.siteResourceId }); + } else if (siteResource.mode == "http") { + let destination = siteResource.destination; + // check if this is a valid ip + const ipSchema = z.union([z.ipv4(), z.ipv6()]); + if (ipSchema.safeParse(destination).success) { + destination = `${destination}/32`; + } + + if ( + !siteResource.aliasAddress || + !siteResource.destinationPort || + !siteResource.scheme || + !siteResource.fullDomain + ) { + logger.debug( + `Site resource ${siteResource.siteResourceId} is in HTTP mode but is missing alias or alias address or destinationPort or scheme, skipping alias target generation.` + ); + return; + } + // also push a match for the alias address + let tlsCert: string | undefined; + let tlsKey: string | undefined; + + if (siteResource.ssl && siteResource.fullDomain) { + try { + const certs = await getValidCertificatesForDomains( + new Set([siteResource.fullDomain]), + true + ); + if (certs.length > 0 && certs[0].certFile && certs[0].keyFile) { + tlsCert = certs[0].certFile; + tlsKey = certs[0].keyFile; + } else { + logger.warn( + `No valid certificate found for SSL site resource ${siteResource.siteResourceId} with domain ${siteResource.fullDomain}` + ); + } + } catch (err) { + logger.error( + `Failed to retrieve certificate for site resource ${siteResource.siteResourceId} domain ${siteResource.fullDomain}: ${err}` + ); + } + } + + targets.push({ + sourcePrefixes: [], + destPrefix: `${siteResource.aliasAddress}/32`, + rewriteTo: destination, + portRange, + disableIcmp, + resourceId: siteResource.siteResourceId, + protocol: siteResource.ssl ? "https" : "http", + httpTargets: [ + { + destAddr: siteResource.destination, + destPort: siteResource.destinationPort, + scheme: siteResource.scheme + } + ], + ...(tlsCert && tlsKey ? { tlsCert, tlsKey } : {}) + }); } if (targets.length == 0) { diff --git a/server/lib/rebuildClientAssociations.ts b/server/lib/rebuildClientAssociations.ts index d636a2f2b..40c5a5bf7 100644 --- a/server/lib/rebuildClientAssociations.ts +++ b/server/lib/rebuildClientAssociations.ts @@ -11,17 +11,16 @@ import { roleSiteResources, Site, SiteResource, + siteNetworks, siteResources, sites, Transaction, userOrgRoles, - userOrgs, userSiteResources } from "@server/db"; import { and, eq, inArray, ne } from "drizzle-orm"; import { - addPeer as newtAddPeer, deletePeer as newtDeletePeer } from "@server/routers/newt/peers"; import { @@ -35,7 +34,6 @@ import { generateRemoteSubnets, generateSubnetProxyTargetV2, parseEndpoint, - formatEndpoint } from "@server/lib/ip"; import { addPeerData, @@ -48,15 +46,27 @@ export async function getClientSiteResourceAccess( siteResource: SiteResource, trx: Transaction | typeof db = db ) { - // get the site - const [site] = await trx - .select() - .from(sites) - .where(eq(sites.siteId, siteResource.siteId)) - .limit(1); + // get all sites associated with this siteResource via its network + const sitesList = siteResource.networkId + ? await trx + .select() + .from(sites) + .innerJoin( + siteNetworks, + eq(siteNetworks.siteId, sites.siteId) + ) + .where(eq(siteNetworks.networkId, siteResource.networkId)) + .then((rows) => rows.map((row) => row.sites)) + : []; - if (!site) { - throw new Error(`Site with ID ${siteResource.siteId} not found`); + logger.debug( + `rebuildClientAssociations: [getClientSiteResourceAccess] siteResourceId=${siteResource.siteResourceId} networkId=${siteResource.networkId} siteCount=${sitesList.length} siteIds=[${sitesList.map((s) => s.siteId).join(", ")}]` + ); + + if (sitesList.length === 0) { + logger.warn( + `No sites found for siteResource ${siteResource.siteResourceId} with networkId ${siteResource.networkId}` + ); } const roleIds = await trx @@ -136,8 +146,12 @@ export async function getClientSiteResourceAccess( const mergedAllClients = Array.from(allClientsMap.values()); const mergedAllClientIds = mergedAllClients.map((c) => c.clientId); + logger.debug( + `rebuildClientAssociations: [getClientSiteResourceAccess] siteResourceId=${siteResource.siteResourceId} mergedClientCount=${mergedAllClientIds.length} clientIds=[${mergedAllClientIds.join(", ")}] (userBased=${newAllClients.length} direct=${directClients.length})` + ); + return { - site, + sitesList, mergedAllClients, mergedAllClientIds }; @@ -153,40 +167,59 @@ export async function rebuildClientAssociationsFromSiteResource( subnet: string | null; }[]; }> { - const siteId = siteResource.siteId; + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] START siteResourceId=${siteResource.siteResourceId} networkId=${siteResource.networkId} orgId=${siteResource.orgId}` + ); - const { site, mergedAllClients, mergedAllClientIds } = + const { sitesList, mergedAllClients, mergedAllClientIds } = await getClientSiteResourceAccess(siteResource, trx); + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] access resolved siteResourceId=${siteResource.siteResourceId} siteCount=${sitesList.length} siteIds=[${sitesList.map((s) => s.siteId).join(", ")}] mergedClientCount=${mergedAllClients.length} clientIds=[${mergedAllClientIds.join(", ")}]` + ); + /////////// process the client-siteResource associations /////////// - // get all of the clients associated with other resources on this site - const allUpdatedClientsFromOtherResourcesOnThisSite = await trx - .select({ - clientId: clientSiteResourcesAssociationsCache.clientId - }) - .from(clientSiteResourcesAssociationsCache) - .innerJoin( - siteResources, - eq( - clientSiteResourcesAssociationsCache.siteResourceId, - siteResources.siteResourceId - ) - ) - .where( - and( - eq(siteResources.siteId, siteId), - ne(siteResources.siteResourceId, siteResource.siteResourceId) - ) - ); + // get all of the clients associated with other resources in the same network, + // joined through siteNetworks so we know which siteId each client belongs to + const allUpdatedClientsFromOtherResourcesOnThisSite = siteResource.networkId + ? await trx + .select({ + clientId: clientSiteResourcesAssociationsCache.clientId, + siteId: siteNetworks.siteId + }) + .from(clientSiteResourcesAssociationsCache) + .innerJoin( + siteResources, + eq( + clientSiteResourcesAssociationsCache.siteResourceId, + siteResources.siteResourceId + ) + ) + .innerJoin( + siteNetworks, + eq(siteNetworks.networkId, siteResources.networkId) + ) + .where( + and( + eq(siteResources.networkId, siteResource.networkId), + ne( + siteResources.siteResourceId, + siteResource.siteResourceId + ) + ) + ) + : []; - const allClientIdsFromOtherResourcesOnThisSite = Array.from( - new Set( - allUpdatedClientsFromOtherResourcesOnThisSite.map( - (row) => row.clientId - ) - ) - ); + // Build a per-site map so the loop below can check by siteId rather than + // across the entire network. + const clientsFromOtherResourcesBySite = new Map>(); + for (const row of allUpdatedClientsFromOtherResourcesOnThisSite) { + if (!clientsFromOtherResourcesBySite.has(row.siteId)) { + clientsFromOtherResourcesBySite.set(row.siteId, new Set()); + } + clientsFromOtherResourcesBySite.get(row.siteId)!.add(row.clientId); + } const existingClientSiteResources = await trx .select({ @@ -204,6 +237,10 @@ export async function rebuildClientAssociationsFromSiteResource( (row) => row.clientId ); + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteResourceId=${siteResource.siteResourceId} existingResourceClientIds=[${existingClientSiteResourceIds.join(", ")}]` + ); + // Get full client details for existing resource clients (needed for sending delete messages) const existingResourceClients = existingClientSiteResourceIds.length > 0 @@ -223,6 +260,10 @@ export async function rebuildClientAssociationsFromSiteResource( (clientId) => !existingClientSiteResourceIds.includes(clientId) ); + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteResourceId=${siteResource.siteResourceId} resourceClients toAdd=[${clientSiteResourcesToAdd.join(", ")}]` + ); + const clientSiteResourcesToInsert = clientSiteResourcesToAdd.map( (clientId) => ({ clientId, @@ -231,17 +272,34 @@ export async function rebuildClientAssociationsFromSiteResource( ); if (clientSiteResourcesToInsert.length > 0) { + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteResourceId=${siteResource.siteResourceId} inserting ${clientSiteResourcesToInsert.length} clientSiteResource association(s)` + ); await trx .insert(clientSiteResourcesAssociationsCache) .values(clientSiteResourcesToInsert) .returning(); + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteResourceId=${siteResource.siteResourceId} inserted clientSiteResource associations` + ); + } else { + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteResourceId=${siteResource.siteResourceId} no clientSiteResource associations to insert` + ); } const clientSiteResourcesToRemove = existingClientSiteResourceIds.filter( (clientId) => !mergedAllClientIds.includes(clientId) ); + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteResourceId=${siteResource.siteResourceId} resourceClients toRemove=[${clientSiteResourcesToRemove.join(", ")}]` + ); + if (clientSiteResourcesToRemove.length > 0) { + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteResourceId=${siteResource.siteResourceId} deleting ${clientSiteResourcesToRemove.length} clientSiteResource association(s)` + ); await trx .delete(clientSiteResourcesAssociationsCache) .where( @@ -260,82 +318,127 @@ export async function rebuildClientAssociationsFromSiteResource( /////////// process the client-site associations /////////// - const existingClientSites = await trx - .select({ - clientId: clientSitesAssociationsCache.clientId - }) - .from(clientSitesAssociationsCache) - .where(eq(clientSitesAssociationsCache.siteId, siteResource.siteId)); - - const existingClientSiteIds = existingClientSites.map( - (row) => row.clientId + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteResourceId=${siteResource.siteResourceId} beginning client-site association loop over ${sitesList.length} site(s)` ); - // Get full client details for existing clients (needed for sending delete messages) - const existingClients = await trx - .select({ - clientId: clients.clientId, - pubKey: clients.pubKey, - subnet: clients.subnet - }) - .from(clients) - .where(inArray(clients.clientId, existingClientSiteIds)); + for (const site of sitesList) { + const siteId = site.siteId; - const clientSitesToAdd = mergedAllClientIds.filter( - (clientId) => - !existingClientSiteIds.includes(clientId) && - !allClientIdsFromOtherResourcesOnThisSite.includes(clientId) // dont remove if there is still another connection for another site resource - ); + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] processing siteId=${siteId} for siteResourceId=${siteResource.siteResourceId}` + ); - const clientSitesToInsert = clientSitesToAdd.map((clientId) => ({ - clientId, - siteId - })); + const existingClientSites = await trx + .select({ + clientId: clientSitesAssociationsCache.clientId + }) + .from(clientSitesAssociationsCache) + .where(eq(clientSitesAssociationsCache.siteId, siteId)); - if (clientSitesToInsert.length > 0) { - await trx - .insert(clientSitesAssociationsCache) - .values(clientSitesToInsert) - .returning(); - } + const existingClientSiteIds = existingClientSites.map( + (row) => row.clientId + ); - // Now remove any client-site associations that should no longer exist - const clientSitesToRemove = existingClientSiteIds.filter( - (clientId) => - !mergedAllClientIds.includes(clientId) && - !allClientIdsFromOtherResourcesOnThisSite.includes(clientId) // dont remove if there is still another connection for another site resource - ); + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteId=${siteId} existingClientSiteIds=[${existingClientSiteIds.join(", ")}]` + ); - if (clientSitesToRemove.length > 0) { - await trx - .delete(clientSitesAssociationsCache) - .where( - and( - eq(clientSitesAssociationsCache.siteId, siteId), - inArray( - clientSitesAssociationsCache.clientId, - clientSitesToRemove - ) - ) + // Get full client details for existing clients (needed for sending delete messages) + const existingClients = + existingClientSiteIds.length > 0 + ? await trx + .select({ + clientId: clients.clientId, + pubKey: clients.pubKey, + subnet: clients.subnet + }) + .from(clients) + .where(inArray(clients.clientId, existingClientSiteIds)) + : []; + + const otherResourceClientIds = clientsFromOtherResourcesBySite.get(siteId) ?? new Set(); + + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteId=${siteId} otherResourceClientIds=[${[...otherResourceClientIds].join(", ")}] mergedAllClientIds=[${mergedAllClientIds.join(", ")}]` + ); + + const clientSitesToAdd = mergedAllClientIds.filter( + (clientId) => + !existingClientSiteIds.includes(clientId) && + !otherResourceClientIds.has(clientId) // dont add if already connected via another site resource + ); + + const clientSitesToInsert = clientSitesToAdd.map((clientId) => ({ + clientId, + siteId + })); + + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteId=${siteId} clientSites toAdd=[${clientSitesToAdd.join(", ")}]` + ); + + if (clientSitesToInsert.length > 0) { + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteId=${siteId} inserting ${clientSitesToInsert.length} clientSite association(s)` ); + await trx + .insert(clientSitesAssociationsCache) + .values(clientSitesToInsert) + .returning(); + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteId=${siteId} inserted clientSite associations` + ); + } else { + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteId=${siteId} no clientSite associations to insert` + ); + } + + // Now remove any client-site associations that should no longer exist + const clientSitesToRemove = existingClientSiteIds.filter( + (clientId) => + !mergedAllClientIds.includes(clientId) && + !otherResourceClientIds.has(clientId) // dont remove if there is still another connection for another site resource + ); + + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteId=${siteId} clientSites toRemove=[${clientSitesToRemove.join(", ")}]` + ); + + if (clientSitesToRemove.length > 0) { + logger.debug( + `rebuildClientAssociations: [rebuildClientAssociationsFromSiteResource] siteId=${siteId} deleting ${clientSitesToRemove.length} clientSite association(s)` + ); + await trx + .delete(clientSitesAssociationsCache) + .where( + and( + eq(clientSitesAssociationsCache.siteId, siteId), + inArray( + clientSitesAssociationsCache.clientId, + clientSitesToRemove + ) + ) + ); + } + + // Now handle the messages to add/remove peers on both the newt and olm sides + await handleMessagesForSiteClients( + site, + siteId, + mergedAllClients, + existingClients, + clientSitesToAdd, + clientSitesToRemove, + trx + ); } - /////////// send the messages /////////// - - // Now handle the messages to add/remove peers on both the newt and olm sides - await handleMessagesForSiteClients( - site, - siteId, - mergedAllClients, - existingClients, - clientSitesToAdd, - clientSitesToRemove, - trx - ); - // Handle subnet proxy target updates for the resource associations await handleSubnetProxyTargetUpdates( siteResource, + sitesList, mergedAllClients, existingResourceClients, clientSiteResourcesToAdd, @@ -624,6 +727,7 @@ export async function updateClientSiteDestinations( async function handleSubnetProxyTargetUpdates( siteResource: SiteResource, + sitesList: Site[], allClients: { clientId: number; pubKey: string | null; @@ -638,125 +742,138 @@ async function handleSubnetProxyTargetUpdates( clientSiteResourcesToRemove: number[], trx: Transaction | typeof db = db ): Promise { - // Get the newt for this site - const [newt] = await trx - .select() - .from(newts) - .where(eq(newts.siteId, siteResource.siteId)) - .limit(1); + const proxyJobs: Promise[] = []; + const olmJobs: Promise[] = []; - if (!newt) { - logger.warn( - `Newt not found for site ${siteResource.siteId}, skipping subnet proxy target updates` - ); - return; - } + for (const siteData of sitesList) { + const siteId = siteData.siteId; - const proxyJobs = []; - const olmJobs = []; - // Generate targets for added associations - if (clientSiteResourcesToAdd.length > 0) { - const addedClients = allClients.filter((client) => - clientSiteResourcesToAdd.includes(client.clientId) - ); + // Get the newt for this site + const [newt] = await trx + .select() + .from(newts) + .where(eq(newts.siteId, siteId)) + .limit(1); - if (addedClients.length > 0) { - const targetsToAdd = generateSubnetProxyTargetV2( - siteResource, - addedClients + if (!newt) { + logger.warn( + `Newt not found for site ${siteId}, skipping subnet proxy target updates` ); - - if (targetsToAdd) { - proxyJobs.push( - addSubnetProxyTargets( - newt.newtId, - targetsToAdd, - newt.version - ) - ); - } - - for (const client of addedClients) { - olmJobs.push( - addPeerData( - client.clientId, - siteResource.siteId, - generateRemoteSubnets([siteResource]), - generateAliasConfig([siteResource]) - ) - ); - } + continue; } - } - // here we use the existingSiteResource from BEFORE we updated the destination so we dont need to worry about updating destinations here - - // Generate targets for removed associations - if (clientSiteResourcesToRemove.length > 0) { - const removedClients = existingClients.filter((client) => - clientSiteResourcesToRemove.includes(client.clientId) - ); - - if (removedClients.length > 0) { - const targetsToRemove = generateSubnetProxyTargetV2( - siteResource, - removedClients + // Generate targets for added associations + if (clientSiteResourcesToAdd.length > 0) { + const addedClients = allClients.filter((client) => + clientSiteResourcesToAdd.includes(client.clientId) ); - if (targetsToRemove) { - proxyJobs.push( - removeSubnetProxyTargets( - newt.newtId, - targetsToRemove, - newt.version - ) + if (addedClients.length > 0) { + const targetsToAdd = await generateSubnetProxyTargetV2( + siteResource, + addedClients ); - } - for (const client of removedClients) { - // Check if this client still has access to another resource on this site with the same destination - const destinationStillInUse = await trx - .select() - .from(siteResources) - .innerJoin( - clientSiteResourcesAssociationsCache, - eq( - clientSiteResourcesAssociationsCache.siteResourceId, - siteResources.siteResourceId - ) - ) - .where( - and( - eq( - clientSiteResourcesAssociationsCache.clientId, - client.clientId - ), - eq(siteResources.siteId, siteResource.siteId), - eq( - siteResources.destination, - siteResource.destination - ), - ne( - siteResources.siteResourceId, - siteResource.siteResourceId - ) + if (targetsToAdd) { + proxyJobs.push( + addSubnetProxyTargets( + newt.newtId, + targetsToAdd, + newt.version ) ); + } - // Only remove remote subnet if no other resource uses the same destination - const remoteSubnetsToRemove = - destinationStillInUse.length > 0 - ? [] - : generateRemoteSubnets([siteResource]); + for (const client of addedClients) { + olmJobs.push( + addPeerData( + client.clientId, + siteId, + generateRemoteSubnets([siteResource]), + generateAliasConfig([siteResource]) + ) + ); + } + } + } - olmJobs.push( - removePeerData( - client.clientId, - siteResource.siteId, - remoteSubnetsToRemove, - generateAliasConfig([siteResource]) - ) + // here we use the existingSiteResource from BEFORE we updated the destination so we dont need to worry about updating destinations here + + // Generate targets for removed associations + if (clientSiteResourcesToRemove.length > 0) { + const removedClients = existingClients.filter((client) => + clientSiteResourcesToRemove.includes(client.clientId) + ); + + if (removedClients.length > 0) { + const targetsToRemove = await generateSubnetProxyTargetV2( + siteResource, + removedClients ); + + if (targetsToRemove) { + proxyJobs.push( + removeSubnetProxyTargets( + newt.newtId, + targetsToRemove, + newt.version + ) + ); + } + + for (const client of removedClients) { + // Check if this client still has access to another resource + // on this specific site with the same destination. We scope + // by siteId (via siteNetworks) rather than networkId because + // removePeerData operates per-site - a resource on a different + // site sharing the same network should not block removal here. + const destinationStillInUse = await trx + .select() + .from(siteResources) + .innerJoin( + clientSiteResourcesAssociationsCache, + eq( + clientSiteResourcesAssociationsCache.siteResourceId, + siteResources.siteResourceId + ) + ) + .innerJoin( + siteNetworks, + eq(siteNetworks.networkId, siteResources.networkId) + ) + .where( + and( + eq( + clientSiteResourcesAssociationsCache.clientId, + client.clientId + ), + eq(siteNetworks.siteId, siteId), + eq( + siteResources.destination, + siteResource.destination + ), + ne( + siteResources.siteResourceId, + siteResource.siteResourceId + ) + ) + ); + + // Only remove remote subnet if no other resource uses the same destination + const remoteSubnetsToRemove = + destinationStillInUse.length > 0 + ? [] + : generateRemoteSubnets([siteResource]); + + olmJobs.push( + removePeerData( + client.clientId, + siteId, + remoteSubnetsToRemove, + generateAliasConfig([siteResource]) + ) + ); + } } } } @@ -863,10 +980,25 @@ export async function rebuildClientAssociationsFromClient( ) : []; - // Group by siteId for site-level associations - const newSiteIds = Array.from( - new Set(newSiteResources.map((sr) => sr.siteId)) + // Group by siteId for site-level associations - look up via siteNetworks since + // siteResources no longer carries a direct siteId column. + const networkIds = Array.from( + new Set( + newSiteResources + .map((sr) => sr.networkId) + .filter((id): id is number => id !== null) + ) ); + const newSiteIds = + networkIds.length > 0 + ? await trx + .select({ siteId: siteNetworks.siteId }) + .from(siteNetworks) + .where(inArray(siteNetworks.networkId, networkIds)) + .then((rows) => + Array.from(new Set(rows.map((r) => r.siteId))) + ) + : []; /////////// Process client-siteResource associations /////////// @@ -1139,13 +1271,45 @@ async function handleMessagesForClientResources( resourcesToAdd.includes(r.siteResourceId) ); + // Build (resource, siteId) pairs by looking up siteNetworks for each resource's networkId + const addedNetworkIds = Array.from( + new Set( + addedResources + .map((r) => r.networkId) + .filter((id): id is number => id !== null) + ) + ); + const addedSiteNetworkRows = + addedNetworkIds.length > 0 + ? await trx + .select({ + networkId: siteNetworks.networkId, + siteId: siteNetworks.siteId + }) + .from(siteNetworks) + .where(inArray(siteNetworks.networkId, addedNetworkIds)) + : []; + const addedNetworkToSites = new Map(); + for (const row of addedSiteNetworkRows) { + if (!addedNetworkToSites.has(row.networkId)) { + addedNetworkToSites.set(row.networkId, []); + } + addedNetworkToSites.get(row.networkId)!.push(row.siteId); + } + // Group by site for proxy updates const addedBySite = new Map(); for (const resource of addedResources) { - if (!addedBySite.has(resource.siteId)) { - addedBySite.set(resource.siteId, []); + const siteIds = + resource.networkId != null + ? (addedNetworkToSites.get(resource.networkId) ?? []) + : []; + for (const siteId of siteIds) { + if (!addedBySite.has(siteId)) { + addedBySite.set(siteId, []); + } + addedBySite.get(siteId)!.push(resource); } - addedBySite.get(resource.siteId)!.push(resource); } // Add subnet proxy targets for each site @@ -1164,7 +1328,7 @@ async function handleMessagesForClientResources( } for (const resource of resources) { - const targets = generateSubnetProxyTargetV2(resource, [ + const targets = await generateSubnetProxyTargetV2(resource, [ { clientId: client.clientId, pubKey: client.pubKey, @@ -1187,7 +1351,7 @@ async function handleMessagesForClientResources( olmJobs.push( addPeerData( client.clientId, - resource.siteId, + siteId, generateRemoteSubnets([resource]), generateAliasConfig([resource]) ) @@ -1199,7 +1363,7 @@ async function handleMessagesForClientResources( error.message.includes("not found") ) { logger.debug( - `Olm data not found for client ${client.clientId} and site ${resource.siteId}, skipping removal` + `Olm data not found for client ${client.clientId} and site ${siteId}, skipping addition` ); } else { throw error; @@ -1216,13 +1380,45 @@ async function handleMessagesForClientResources( .from(siteResources) .where(inArray(siteResources.siteResourceId, resourcesToRemove)); + // Build (resource, siteId) pairs via siteNetworks + const removedNetworkIds = Array.from( + new Set( + removedResources + .map((r) => r.networkId) + .filter((id): id is number => id !== null) + ) + ); + const removedSiteNetworkRows = + removedNetworkIds.length > 0 + ? await trx + .select({ + networkId: siteNetworks.networkId, + siteId: siteNetworks.siteId + }) + .from(siteNetworks) + .where(inArray(siteNetworks.networkId, removedNetworkIds)) + : []; + const removedNetworkToSites = new Map(); + for (const row of removedSiteNetworkRows) { + if (!removedNetworkToSites.has(row.networkId)) { + removedNetworkToSites.set(row.networkId, []); + } + removedNetworkToSites.get(row.networkId)!.push(row.siteId); + } + // Group by site for proxy updates const removedBySite = new Map(); for (const resource of removedResources) { - if (!removedBySite.has(resource.siteId)) { - removedBySite.set(resource.siteId, []); + const siteIds = + resource.networkId != null + ? (removedNetworkToSites.get(resource.networkId) ?? []) + : []; + for (const siteId of siteIds) { + if (!removedBySite.has(siteId)) { + removedBySite.set(siteId, []); + } + removedBySite.get(siteId)!.push(resource); } - removedBySite.get(resource.siteId)!.push(resource); } // Remove subnet proxy targets for each site @@ -1241,7 +1437,7 @@ async function handleMessagesForClientResources( } for (const resource of resources) { - const targets = generateSubnetProxyTargetV2(resource, [ + const targets = await generateSubnetProxyTargetV2(resource, [ { clientId: client.clientId, pubKey: client.pubKey, @@ -1260,7 +1456,11 @@ async function handleMessagesForClientResources( } try { - // Check if this client still has access to another resource on this site with the same destination + // Check if this client still has access to another resource + // on this specific site with the same destination. We scope + // by siteId (via siteNetworks) rather than networkId because + // removePeerData operates per-site - a resource on a different + // site sharing the same network should not block removal here. const destinationStillInUse = await trx .select() .from(siteResources) @@ -1271,13 +1471,17 @@ async function handleMessagesForClientResources( siteResources.siteResourceId ) ) + .innerJoin( + siteNetworks, + eq(siteNetworks.networkId, siteResources.networkId) + ) .where( and( eq( clientSiteResourcesAssociationsCache.clientId, client.clientId ), - eq(siteResources.siteId, resource.siteId), + eq(siteNetworks.siteId, siteId), eq( siteResources.destination, resource.destination @@ -1299,7 +1503,7 @@ async function handleMessagesForClientResources( olmJobs.push( removePeerData( client.clientId, - resource.siteId, + siteId, remoteSubnetsToRemove, generateAliasConfig([resource]) ) @@ -1311,7 +1515,7 @@ async function handleMessagesForClientResources( error.message.includes("not found") ) { logger.debug( - `Olm data not found for client ${client.clientId} and site ${resource.siteId}, skipping removal` + `Olm data not found for client ${client.clientId} and site ${siteId}, skipping removal` ); } else { throw error; diff --git a/server/lib/statusHistory.ts b/server/lib/statusHistory.ts new file mode 100644 index 000000000..001a0b93b --- /dev/null +++ b/server/lib/statusHistory.ts @@ -0,0 +1,133 @@ +import { z } from "zod"; + +export const statusHistoryQuerySchema = z + .object({ + days: z + .string() + .optional() + .transform((v) => (v ? parseInt(v, 10) : 90)), + }) + .pipe( + z.object({ + days: z.number().int().min(1).max(365), + }) + ); + +export interface StatusHistoryDayBucket { + date: string; // ISO date "YYYY-MM-DD" + uptimePercent: number; // 0-100 + totalDowntimeSeconds: number; + downtimeWindows: { start: number; end: number | null; status: string }[]; + status: "good" | "degraded" | "bad" | "no_data"; +} + +export interface StatusHistoryResponse { + entityType: string; + entityId: number; + days: StatusHistoryDayBucket[]; + overallUptimePercent: number; + totalDowntimeSeconds: number; +} + +export function computeBuckets( + events: { entityType: string; entityId: number; orgId: string; status: string; timestamp: number; id: number }[], + days: number +): { buckets: StatusHistoryDayBucket[]; totalDowntime: number } { + const nowSec = Math.floor(Date.now() / 1000); + const buckets: StatusHistoryDayBucket[] = []; + let totalDowntime = 0; + + for (let d = 0; d < days; d++) { + const dayStartSec = nowSec - (days - d) * 86400; + const dayEndSec = dayStartSec + 86400; + + const dayEvents = events.filter( + (e) => e.timestamp >= dayStartSec && e.timestamp < dayEndSec + ); + + // Determine the status at the start of this day (last event before dayStart) + const lastBeforeDay = [...events] + .filter((e) => e.timestamp < dayStartSec) + .at(-1); + + const currentStatus = lastBeforeDay?.status ?? null; + + const windows: { start: number; end: number | null; status: string }[] = []; + let dayDowntime = 0; + + let windowStart = dayStartSec; + let windowStatus = currentStatus; + + for (const evt of dayEvents) { + if (windowStatus !== null && windowStatus !== evt.status) { + const windowEnd = evt.timestamp; + const isDown = + windowStatus === "offline" || + windowStatus === "unhealthy" || + windowStatus === "unknown"; + if (isDown) { + dayDowntime += windowEnd - windowStart; + windows.push({ + start: windowStart, + end: windowEnd, + status: windowStatus, + }); + } + } + windowStart = evt.timestamp; + windowStatus = evt.status; + } + + // Close the final window at the end of the day (or now if day hasn't ended) + if (windowStatus !== null) { + const finalEnd = Math.min(dayEndSec, nowSec); + const isDown = + windowStatus === "offline" || + windowStatus === "unhealthy" || + windowStatus === "unknown"; + if (isDown && finalEnd > windowStart) { + dayDowntime += finalEnd - windowStart; + windows.push({ + start: windowStart, + end: finalEnd, + status: windowStatus, + }); + } + } + + totalDowntime += dayDowntime; + + const effectiveDayLength = Math.max( + 0, + Math.min(dayEndSec, nowSec) - dayStartSec + ); + const uptimePct = + effectiveDayLength > 0 + ? Math.max( + 0, + ((effectiveDayLength - dayDowntime) / + effectiveDayLength) * + 100 + ) + : 100; + + const dateStr = new Date(dayStartSec * 1000).toISOString().slice(0, 10); + + let status: StatusHistoryDayBucket["status"] = "no_data"; + if (currentStatus !== null || dayEvents.length > 0) { + if (uptimePct >= 99) status = "good"; + else if (uptimePct >= 50) status = "degraded"; + else status = "bad"; + } + + buckets.push({ + date: dateStr, + uptimePercent: Math.round(uptimePct * 100) / 100, + totalDowntimeSeconds: dayDowntime, + downtimeWindows: windows, + status, + }); + } + + return { buckets, totalDowntime }; +} diff --git a/server/lib/telemetry.ts b/server/lib/telemetry.ts index fda59f394..8d341bf1d 100644 --- a/server/lib/telemetry.ts +++ b/server/lib/telemetry.ts @@ -72,7 +72,7 @@ class TelemetryClient { logger.debug("Successfully sent analytics data"); }); }, - 48 * 60 * 60 * 1000 + 336 * 60 * 60 * 1000 ); this.collectAndSendAnalytics().catch((err) => { diff --git a/server/lib/traefik/TraefikConfigManager.ts b/server/lib/traefik/TraefikConfigManager.ts index 6ef3c45b5..c8fcfafdc 100644 --- a/server/lib/traefik/TraefikConfigManager.ts +++ b/server/lib/traefik/TraefikConfigManager.ts @@ -1011,7 +1011,7 @@ export class TraefikConfigManager { ); if (!isUnused) { - // Domain is still active — remove from pending deletion if it was queued + // Domain is still active - remove from pending deletion if it was queued if (this.pendingDeletion.has(dirName)) { logger.info( `Certificate ${dirName} is active again, cancelling pending deletion` @@ -1021,7 +1021,7 @@ export class TraefikConfigManager { continue; } - // Domain is unused — add to pending deletion or decrement its counter + // Domain is unused - add to pending deletion or decrement its counter if (!this.pendingDeletion.has(dirName)) { const graceCycles = 3; logger.info( @@ -1036,7 +1036,7 @@ export class TraefikConfigManager { ); this.pendingDeletion.set(dirName, remaining); } else { - // Grace period expired — actually delete now + // Grace period expired - actually delete now this.pendingDeletion.delete(dirName); const domainDir = path.join(certsPath, dirName); diff --git a/server/lib/traefik/pathEncoding.test.ts b/server/lib/traefik/pathEncoding.test.ts index 83d53a039..f0318807a 100644 --- a/server/lib/traefik/pathEncoding.test.ts +++ b/server/lib/traefik/pathEncoding.test.ts @@ -24,7 +24,7 @@ function encodePath(path: string | null | undefined): string { /** * Exact replica of the OLD key computation from upstream main. - * Uses sanitize() for paths — this is what had the collision bug. + * Uses sanitize() for paths - this is what had the collision bug. */ function oldKeyComputation( resourceId: number, @@ -44,7 +44,7 @@ function oldKeyComputation( /** * Replica of the NEW key computation from our fix. - * Uses encodePath() for paths — collision-free. + * Uses encodePath() for paths - collision-free. */ function newKeyComputation( resourceId: number, @@ -195,11 +195,11 @@ function runTests() { true, "/a/b and /a-b MUST have different keys" ); - console.log(" PASS: collision fix — /a/b vs /a-b have different keys"); + console.log(" PASS: collision fix - /a/b vs /a-b have different keys"); passed++; } - // Test 9: demonstrate the old bug — old code maps /a/b and /a-b to same key + // Test 9: demonstrate the old bug - old code maps /a/b and /a-b to same key { const oldKeyAB = oldKeyComputation(1, "/a/b", "prefix", null, null); const oldKeyDash = oldKeyComputation(1, "/a-b", "prefix", null, null); @@ -208,11 +208,11 @@ function runTests() { oldKeyDash, "old code MUST have this collision (confirms the bug exists)" ); - console.log(" PASS: confirmed old code bug — /a/b and /a-b collided"); + console.log(" PASS: confirmed old code bug - /a/b and /a-b collided"); passed++; } - // Test 10: /api/v1 and /api-v1 — old code collision, new code fixes it + // Test 10: /api/v1 and /api-v1 - old code collision, new code fixes it { const oldKey1 = oldKeyComputation(1, "/api/v1", "prefix", null, null); const oldKey2 = oldKeyComputation(1, "/api-v1", "prefix", null, null); @@ -229,11 +229,11 @@ function runTests() { true, "new code must separate /api/v1 and /api-v1" ); - console.log(" PASS: collision fix — /api/v1 vs /api-v1"); + console.log(" PASS: collision fix - /api/v1 vs /api-v1"); passed++; } - // Test 11: /app.v2 and /app/v2 and /app-v2 — three-way collision fixed + // Test 11: /app.v2 and /app/v2 and /app-v2 - three-way collision fixed { const a = newKeyComputation(1, "/app.v2", "prefix", null, null); const b = newKeyComputation(1, "/app/v2", "prefix", null, null); @@ -245,14 +245,14 @@ function runTests() { "three paths must produce three unique keys" ); console.log( - " PASS: collision fix — three-way /app.v2, /app/v2, /app-v2" + " PASS: collision fix - three-way /app.v2, /app/v2, /app-v2" ); passed++; } // ── Edge cases ─────────────────────────────────────────────────── - // Test 12: same path in different resources — always separate + // Test 12: same path in different resources - always separate { const key1 = newKeyComputation(1, "/api", "prefix", null, null); const key2 = newKeyComputation(2, "/api", "prefix", null, null); @@ -261,11 +261,11 @@ function runTests() { true, "different resources with same path must have different keys" ); - console.log(" PASS: edge case — same path, different resources"); + console.log(" PASS: edge case - same path, different resources"); passed++; } - // Test 13: same resource, different pathMatchType — separate keys + // Test 13: same resource, different pathMatchType - separate keys { const exact = newKeyComputation(1, "/api", "exact", null, null); const prefix = newKeyComputation(1, "/api", "prefix", null, null); @@ -274,11 +274,11 @@ function runTests() { true, "exact vs prefix must have different keys" ); - console.log(" PASS: edge case — same path, different match types"); + console.log(" PASS: edge case - same path, different match types"); passed++; } - // Test 14: same resource and path, different rewrite config — separate keys + // Test 14: same resource and path, different rewrite config - separate keys { const noRewrite = newKeyComputation(1, "/api", "prefix", null, null); const withRewrite = newKeyComputation( @@ -293,7 +293,7 @@ function runTests() { true, "with vs without rewrite must have different keys" ); - console.log(" PASS: edge case — same path, different rewrite config"); + console.log(" PASS: edge case - same path, different rewrite config"); passed++; } @@ -308,7 +308,7 @@ function runTests() { paths.length, "special URL chars must produce unique keys" ); - console.log(" PASS: edge case — special URL characters in paths"); + console.log(" PASS: edge case - special URL characters in paths"); passed++; } diff --git a/server/middlewares/verifyDomainAccess.ts b/server/middlewares/verifyDomainAccess.ts index c9ecf42e0..d37f6725d 100644 --- a/server/middlewares/verifyDomainAccess.ts +++ b/server/middlewares/verifyDomainAccess.ts @@ -15,7 +15,7 @@ export async function verifyDomainAccess( try { const userId = req.user!.userId; const domainId = - req.params.domainId || req.body.apiKeyId || req.query.apiKeyId; + req.params.domainId; const orgId = req.params.orgId; if (!userId) { diff --git a/server/nextServer.ts b/server/nextServer.ts index b862a699c..18b14a397 100644 --- a/server/nextServer.ts +++ b/server/nextServer.ts @@ -11,7 +11,7 @@ export async function createNextServer() { // const app = next({ dev }); const app = next({ dev: process.env.ENVIRONMENT !== "prod", - turbopack: true + turbopack: false }); const handle = app.getRequestHandler(); @@ -29,7 +29,7 @@ export async function createNextServer() { nextServer.listen(nextPort, (err?: any) => { if (err) throw err; logger.info( - `Next.js server is running on http://localhost:${nextPort}` + `Dashboard Web UI server is running on http://localhost:${nextPort}` ); }); diff --git a/server/private/lib/acmeCertSync.ts b/server/private/lib/acmeCertSync.ts new file mode 100644 index 000000000..62a18b805 --- /dev/null +++ b/server/private/lib/acmeCertSync.ts @@ -0,0 +1,478 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import fs from "fs"; +import crypto from "crypto"; +import { + certificates, + clients, + clientSiteResourcesAssociationsCache, + db, + domains, + newts, + siteNetworks, + SiteResource, + siteResources +} from "@server/db"; +import { and, eq } from "drizzle-orm"; +import { encrypt, decrypt } from "@server/lib/crypto"; +import logger from "@server/logger"; +import privateConfig from "#private/lib/config"; +import config from "@server/lib/config"; +import { + generateSubnetProxyTargetV2, + SubnetProxyTargetV2 +} from "@server/lib/ip"; +import { updateTargets } from "@server/routers/client/targets"; +import cache from "#private/lib/cache"; +import { build } from "@server/build"; + +interface AcmeCert { + domain: { main: string; sans?: string[] }; + certificate: string; + key: string; + Store: string; +} + +interface AcmeJson { + [resolver: string]: { + Certificates: AcmeCert[]; + }; +} + +async function pushCertUpdateToAffectedNewts( + domain: string, + domainId: string | null, + oldCertPem: string | null, + oldKeyPem: string | null +): Promise { + // Find all SSL-enabled HTTP site resources that use this cert's domain + let affectedResources: SiteResource[] = []; + + if (domainId) { + affectedResources = await db + .select() + .from(siteResources) + .where( + and( + eq(siteResources.domainId, domainId), + eq(siteResources.ssl, true) + ) + ); + } else { + // Fallback: match by exact fullDomain when no domainId is available + affectedResources = await db + .select() + .from(siteResources) + .where( + and( + eq(siteResources.fullDomain, domain), + eq(siteResources.ssl, true) + ) + ); + } + + if (affectedResources.length === 0) { + logger.debug( + `acmeCertSync: no affected site resources for cert domain "${domain}"` + ); + return; + } + + logger.debug( + `acmeCertSync: pushing cert update to ${affectedResources.length} affected site resource(s) for domain "${domain}"` + ); + + for (const resource of affectedResources) { + try { + // Get all sites for this resource via siteNetworks + const resourceSiteRows = resource.networkId + ? await db + .select({ siteId: siteNetworks.siteId }) + .from(siteNetworks) + .where(eq(siteNetworks.networkId, resource.networkId)) + : []; + + if (resourceSiteRows.length === 0) { + logger.debug( + `acmeCertSync: no sites for resource ${resource.siteResourceId}, skipping` + ); + continue; + } + + // Get all clients with access to this resource + const resourceClients = await db + .select({ + clientId: clients.clientId, + pubKey: clients.pubKey, + subnet: clients.subnet + }) + .from(clients) + .innerJoin( + clientSiteResourcesAssociationsCache, + eq( + clients.clientId, + clientSiteResourcesAssociationsCache.clientId + ) + ) + .where( + eq( + clientSiteResourcesAssociationsCache.siteResourceId, + resource.siteResourceId + ) + ); + + if (resourceClients.length === 0) { + logger.debug( + `acmeCertSync: no clients for resource ${resource.siteResourceId}, skipping` + ); + continue; + } + + // Invalidate the cert cache so generateSubnetProxyTargetV2 fetches fresh data + if (resource.fullDomain) { + await cache.del(`cert:${resource.fullDomain}`); + } + + // Generate target once - same cert applies to all sites for this resource + const newTargets = await generateSubnetProxyTargetV2( + resource, + resourceClients + ); + + if (!newTargets) { + logger.debug( + `acmeCertSync: could not generate target for resource ${resource.siteResourceId}, skipping` + ); + continue; + } + + // Construct the old targets - same routing shape but with the previous cert/key. + // The newt only uses destPrefix/sourcePrefixes for removal, but we keep the + // semantics correct so the update message accurately reflects what changed. + const oldTargets: SubnetProxyTargetV2[] = newTargets.map((t) => ({ + ...t, + tlsCert: oldCertPem ?? undefined, + tlsKey: oldKeyPem ?? undefined + })); + + // Push update to each site's newt + for (const { siteId } of resourceSiteRows) { + const [newt] = await db + .select() + .from(newts) + .where(eq(newts.siteId, siteId)) + .limit(1); + + if (!newt) { + logger.debug( + `acmeCertSync: no newt found for site ${siteId}, skipping resource ${resource.siteResourceId}` + ); + continue; + } + + await updateTargets( + newt.newtId, + { oldTargets: oldTargets, newTargets: newTargets }, + newt.version + ); + + logger.debug( + `acmeCertSync: pushed cert update to newt for site ${siteId}, resource ${resource.siteResourceId}` + ); + } + } catch (err) { + logger.error( + `acmeCertSync: error pushing cert update for resource ${resource?.siteResourceId}: ${err}` + ); + } + } +} + +async function findDomainId(certDomain: string): Promise { + // Strip wildcard prefix before lookup (*.example.com -> example.com) + const lookupDomain = certDomain.startsWith("*.") + ? certDomain.slice(2) + : certDomain; + + // 1. Exact baseDomain match (any domain type) + const exactMatch = await db + .select({ domainId: domains.domainId }) + .from(domains) + .where(eq(domains.baseDomain, lookupDomain)) + .limit(1); + + if (exactMatch.length > 0) { + return exactMatch[0].domainId; + } + + // 2. Walk up the domain hierarchy looking for a wildcard-type domain whose + // baseDomain is a suffix of the cert domain. e.g. cert "sub.example.com" + // matches a wildcard domain with baseDomain "example.com". + const parts = lookupDomain.split("."); + for (let i = 1; i < parts.length; i++) { + const candidate = parts.slice(i).join("."); + if (!candidate) continue; + + const wildcardMatch = await db + .select({ domainId: domains.domainId }) + .from(domains) + .where( + and( + eq(domains.baseDomain, candidate), + eq(domains.type, "wildcard") + ) + ) + .limit(1); + + if (wildcardMatch.length > 0) { + return wildcardMatch[0].domainId; + } + } + + return null; +} + +function extractFirstCert(pemBundle: string): string | null { + const match = pemBundle.match( + /-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/ + ); + return match ? match[0] : null; +} + +async function syncAcmeCerts( + acmeJsonPath: string, + resolver: string +): Promise { + let raw: string; + try { + raw = fs.readFileSync(acmeJsonPath, "utf8"); + } catch (err) { + logger.debug(`acmeCertSync: could not read ${acmeJsonPath}: ${err}`); + return; + } + + let acmeJson: AcmeJson; + try { + acmeJson = JSON.parse(raw); + } catch (err) { + logger.debug(`acmeCertSync: could not parse acme.json: ${err}`); + return; + } + + const resolverData = acmeJson[resolver]; + if (!resolverData || !Array.isArray(resolverData.Certificates)) { + logger.debug( + `acmeCertSync: no certificates found for resolver "${resolver}"` + ); + return; + } + + for (const cert of resolverData.Certificates) { + const domain = cert.domain?.main; + + if (!domain) { + logger.debug(`acmeCertSync: skipping cert with missing domain`); + continue; + } + + if (!cert.certificate || !cert.key) { + logger.debug( + `acmeCertSync: skipping cert for ${domain} - empty certificate or key field` + ); + continue; + } + + const certPem = Buffer.from(cert.certificate, "base64").toString( + "utf8" + ); + const keyPem = Buffer.from(cert.key, "base64").toString("utf8"); + + if (!certPem.trim() || !keyPem.trim()) { + logger.debug( + `acmeCertSync: skipping cert for ${domain} - blank PEM after base64 decode` + ); + continue; + } + + // Check if cert already exists in DB + const existing = await db + .select() + .from(certificates) + .where(eq(certificates.domain, domain)) + .limit(1); + + let oldCertPem: string | null = null; + let oldKeyPem: string | null = null; + + if (existing.length > 0 && existing[0].certFile) { + try { + const storedCertPem = decrypt( + existing[0].certFile, + config.getRawConfig().server.secret! + ); + if (storedCertPem === certPem) { + logger.debug( + `acmeCertSync: cert for ${domain} is unchanged, skipping` + ); + continue; + } + // Cert has changed; capture old values so we can send a correct + // update message to the newt after the DB write. + oldCertPem = storedCertPem; + if (existing[0].keyFile) { + try { + oldKeyPem = decrypt( + existing[0].keyFile, + config.getRawConfig().server.secret! + ); + } catch (keyErr) { + logger.debug( + `acmeCertSync: could not decrypt stored key for ${domain}: ${keyErr}` + ); + } + } + } catch (err) { + // Decryption failure means we should proceed with the update + logger.debug( + `acmeCertSync: could not decrypt stored cert for ${domain}, will update: ${err}` + ); + } + } + + // Parse cert expiry from the first cert in the PEM bundle + let expiresAt: number | null = null; + const firstCertPem = extractFirstCert(certPem); + if (firstCertPem) { + try { + const x509 = new crypto.X509Certificate(firstCertPem); + expiresAt = Math.floor(new Date(x509.validTo).getTime() / 1000); + } catch (err) { + logger.debug( + `acmeCertSync: could not parse cert expiry for ${domain}: ${err}` + ); + } + } + + const wildcard = domain.startsWith("*."); + const encryptedCert = encrypt( + certPem, + config.getRawConfig().server.secret! + ); + const encryptedKey = encrypt( + keyPem, + config.getRawConfig().server.secret! + ); + const now = Math.floor(Date.now() / 1000); + + const domainId = await findDomainId(domain); + if (domainId) { + logger.debug( + `acmeCertSync: resolved domainId "${domainId}" for cert domain "${domain}"` + ); + } else { + logger.debug( + `acmeCertSync: no matching domain record found for cert domain "${domain}"` + ); + } + + if (existing.length > 0) { + await db + .update(certificates) + .set({ + certFile: encryptedCert, + keyFile: encryptedKey, + status: "valid", + expiresAt, + updatedAt: now, + wildcard, + ...(domainId !== null && { domainId }) + }) + .where(eq(certificates.domain, domain)); + + logger.debug( + `acmeCertSync: updated certificate for ${domain} (expires ${expiresAt ? new Date(expiresAt * 1000).toISOString() : "unknown"})` + ); + + await pushCertUpdateToAffectedNewts( + domain, + domainId, + oldCertPem, + oldKeyPem + ); + } else { + await db.insert(certificates).values({ + domain, + domainId, + certFile: encryptedCert, + keyFile: encryptedKey, + status: "valid", + expiresAt, + createdAt: now, + updatedAt: now, + wildcard + }); + + logger.debug( + `acmeCertSync: inserted new certificate for ${domain} (expires ${expiresAt ? new Date(expiresAt * 1000).toISOString() : "unknown"})` + ); + + // For a brand-new cert, push to any SSL resources that were waiting for it + await pushCertUpdateToAffectedNewts(domain, domainId, null, null); + } + } +} + +export function initAcmeCertSync(): void { + if (build == "saas") { + logger.debug(`acmeCertSync: skipping ACME cert sync in SaaS build`); + return; + } + + const privateConfigData = privateConfig.getRawPrivateConfig(); + + if (!privateConfigData.flags?.enable_acme_cert_sync) { + logger.debug( + `acmeCertSync: ACME cert sync is disabled by config flag, skipping` + ); + return; + } + + if (privateConfigData.flags.use_pangolin_dns) { + logger.debug( + `acmeCertSync: ACME cert sync requires use_pangolin_dns flag to be disabled, skipping` + ); + return; + } + + const acmeJsonPath = + privateConfigData.acme?.acme_json_path ?? + "config/letsencrypt/acme.json"; + const resolver = privateConfigData.acme?.resolver ?? "letsencrypt"; + const intervalMs = privateConfigData.acme?.sync_interval_ms ?? 5000; + + logger.debug( + `acmeCertSync: starting ACME cert sync from "${acmeJsonPath}" using resolver "${resolver}" every ${intervalMs}ms` + ); + + // Run immediately on init, then on the configured interval + syncAcmeCerts(acmeJsonPath, resolver).catch((err) => { + logger.error(`acmeCertSync: error during initial sync: ${err}`); + }); + + setInterval(() => { + syncAcmeCerts(acmeJsonPath, resolver).catch((err) => { + logger.error(`acmeCertSync: error during sync: ${err}`); + }); + }, intervalMs); +} diff --git a/server/private/lib/alerts/events/healthCheckEvents.ts b/server/private/lib/alerts/events/healthCheckEvents.ts new file mode 100644 index 000000000..cd9f3f1c3 --- /dev/null +++ b/server/private/lib/alerts/events/healthCheckEvents.ts @@ -0,0 +1,109 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import logger from "@server/logger"; +import { processAlerts } from "../processAlerts"; + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +/** + * Fire a `health_check_healthy` alert for the given health check. + * + * Call this after a previously-failing health check has recovered so that any + * matching `alertRules` can dispatch their email and webhook actions. + * + * @param orgId - Organisation that owns the health check. + * @param healthCheckId - Numeric primary key of the health check. + * @param healthCheckName - Human-readable name shown in notifications (optional). + * @param extra - Any additional key/value pairs to include in the payload. + */ +export async function fireHealthCheckHealthyAlert( + orgId: string, + healthCheckId: number, + healthCheckName?: string | null, + extra?: Record +): Promise { + try { + await processAlerts({ + eventType: "health_check_healthy", + orgId, + healthCheckId, + data: { + ...(healthCheckName != null ? { healthCheckName } : {}), + ...extra + } + }); + await processAlerts({ + eventType: "health_check_toggle", + orgId, + healthCheckId, + data: { + healthCheckId, + ...(healthCheckName != null ? { healthCheckName } : {}), + ...extra + } + }); + } catch (err) { + logger.error( + `fireHealthCheckHealthyAlert: unexpected error for healthCheckId ${healthCheckId}`, + err + ); + } +} + +/** + * Fire a `health_check_unhealthy` alert for the given health check. + * + * Call this after a health check has been detected as failing so that any + * matching `alertRules` can dispatch their email and webhook actions. + * + * @param orgId - Organisation that owns the health check. + * @param healthCheckId - Numeric primary key of the health check. + * @param healthCheckName - Human-readable name shown in notifications (optional). + * @param extra - Any additional key/value pairs to include in the payload. + */ +export async function fireHealthCheckUnhealthyAlert( + orgId: string, + healthCheckId: number, + healthCheckName?: string | null, + extra?: Record +): Promise { + try { + await processAlerts({ + eventType: "health_check_unhealthy", + orgId, + healthCheckId, + data: { + ...(healthCheckName != null ? { healthCheckName } : {}), + ...extra + } + }); + await processAlerts({ + eventType: "health_check_toggle", + orgId, + healthCheckId, + data: { + healthCheckId, + ...(healthCheckName != null ? { healthCheckName } : {}), + ...extra + } + }); + } catch (err) { + logger.error( + `fireHealthCheckNotHealthyAlert: unexpected error for healthCheckId ${healthCheckId}`, + err + ); + } +} diff --git a/server/private/lib/alerts/events/resourceEvents.ts b/server/private/lib/alerts/events/resourceEvents.ts new file mode 100644 index 000000000..280b1d0c9 --- /dev/null +++ b/server/private/lib/alerts/events/resourceEvents.ts @@ -0,0 +1,144 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import logger from "@server/logger"; +import { processAlerts } from "../processAlerts"; + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +/** + * Fire a `resource_healthy` alert for the given resource. + * + * Call this after a previously-unhealthy resource has recovered so that any + * matching `alertRules` can dispatch their email and webhook actions. + * + * @param orgId - Organisation that owns the resource. + * @param resourceId - Numeric primary key of the resource. + * @param resourceName - Human-readable name shown in notifications (optional). + * @param extra - Any additional key/value pairs to include in the payload. + */ +export async function fireResourceHealthyAlert( + orgId: string, + resourceId: number, + resourceName?: string | null, + extra?: Record +): Promise { + try { + await processAlerts({ + eventType: "resource_healthy", + orgId, + resourceId, + data: { + ...(resourceName != null ? { resourceName } : {}), + ...extra + } + }); + await processAlerts({ + eventType: "resource_toggle", + orgId, + resourceId, + data: { + resourceId, + ...(resourceName != null ? { resourceName } : {}), + ...extra + } + }); + } catch (err) { + logger.error( + `fireResourceHealthyAlert: unexpected error for resourceId ${resourceId}`, + err + ); + } +} + +/** + * Fire a `resource_unhealthy` alert for the given resource. + * + * Call this after a resource has been detected as unhealthy so that any + * matching `alertRules` can dispatch their email and webhook actions. + * + * @param orgId - Organisation that owns the resource. + * @param resourceId - Numeric primary key of the resource. + * @param resourceName - Human-readable name shown in notifications (optional). + * @param extra - Any additional key/value pairs to include in the payload. + */ +export async function fireResourceUnhealthyAlert( + orgId: string, + resourceId: number, + resourceName?: string | null, + extra?: Record +): Promise { + try { + await processAlerts({ + eventType: "resource_unhealthy", + orgId, + resourceId, + data: { + ...(resourceName != null ? { resourceName } : {}), + ...extra + } + }); + await processAlerts({ + eventType: "resource_toggle", + orgId, + resourceId, + data: { + resourceId, + ...(resourceName != null ? { resourceName } : {}), + ...extra + } + }); + } catch (err) { + logger.error( + `fireResourceUnhealthyAlert: unexpected error for resourceId ${resourceId}`, + err + ); + } +} + +/** + * Fire a `resource_toggle` alert for the given resource. + * + * Call this when a resource's enabled/disabled status is toggled so that any + * matching `alertRules` can dispatch their email and webhook actions. + * + * @param orgId - Organisation that owns the resource. + * @param resourceId - Numeric primary key of the resource. + * @param resourceName - Human-readable name shown in notifications (optional). + * @param extra - Any additional key/value pairs to include in the payload. + */ +export async function fireResourceToggleAlert( + orgId: string, + resourceId: number, + resourceName?: string | null, + extra?: Record +): Promise { + try { + await processAlerts({ + eventType: "resource_toggle", + orgId, + resourceId, + data: { + ...(resourceName != null ? { resourceName } : {}), + ...extra + } + }); + } catch (err) { + logger.error( + `fireResourceToggleAlert: unexpected error for resourceId ${resourceId}`, + err + ); + } +} diff --git a/server/private/lib/alerts/events/siteEvents.ts b/server/private/lib/alerts/events/siteEvents.ts new file mode 100644 index 000000000..d8531a5b7 --- /dev/null +++ b/server/private/lib/alerts/events/siteEvents.ts @@ -0,0 +1,109 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import logger from "@server/logger"; +import { processAlerts } from "../processAlerts"; + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +/** + * Fire a `site_online` alert for the given site. + * + * Call this after the site has been confirmed reachable / connected so that + * any matching `alertRules` can dispatch their email and webhook actions. + * + * @param orgId - Organisation that owns the site. + * @param siteId - Numeric primary key of the site. + * @param siteName - Human-readable name shown in notifications (optional). + * @param extra - Any additional key/value pairs to include in the payload. + */ +export async function fireSiteOnlineAlert( + orgId: string, + siteId: number, + siteName?: string, + extra?: Record +): Promise { + try { + await processAlerts({ + eventType: "site_online", + orgId, + siteId, + data: { + ...(siteName != null ? { siteName } : {}), + ...extra + } + }); + await processAlerts({ + eventType: "site_toggle", + orgId, + siteId, + data: { + siteId, + ...(siteName != null ? { siteName } : {}), + ...extra + } + }); + } catch (err) { + logger.error( + `fireSiteOnlineAlert: unexpected error for siteId ${siteId}`, + err + ); + } +} + +/** + * Fire a `site_offline` alert for the given site. + * + * Call this after the site has been detected as unreachable / disconnected so + * that any matching `alertRules` can dispatch their email and webhook actions. + * + * @param orgId - Organisation that owns the site. + * @param siteId - Numeric primary key of the site. + * @param siteName - Human-readable name shown in notifications (optional). + * @param extra - Any additional key/value pairs to include in the payload. + */ +export async function fireSiteOfflineAlert( + orgId: string, + siteId: number, + siteName?: string, + extra?: Record +): Promise { + try { + await processAlerts({ + eventType: "site_offline", + orgId, + siteId, + data: { + ...(siteName != null ? { siteName } : {}), + ...extra + } + }); + await processAlerts({ + eventType: "site_toggle", + orgId, + siteId, + data: { + siteId, + ...(siteName != null ? { siteName } : {}), + ...extra + } + }); + } catch (err) { + logger.error( + `fireSiteOfflineAlert: unexpected error for siteId ${siteId}`, + err + ); + } +} diff --git a/server/private/lib/alerts/index.ts b/server/private/lib/alerts/index.ts new file mode 100644 index 000000000..3460e965d --- /dev/null +++ b/server/private/lib/alerts/index.ts @@ -0,0 +1,19 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +export * from "./types"; +export * from "./processAlerts"; +export * from "./sendAlertWebhook"; +export * from "./sendAlertEmail"; +export * from "./events/siteEvents"; +export * from "./events/healthCheckEvents"; \ No newline at end of file diff --git a/server/private/lib/alerts/processAlerts.ts b/server/private/lib/alerts/processAlerts.ts new file mode 100644 index 000000000..681eb3cd0 --- /dev/null +++ b/server/private/lib/alerts/processAlerts.ts @@ -0,0 +1,333 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { and, eq, or } from "drizzle-orm"; +import { db } from "@server/db"; +import { + alertRules, + alertSites, + alertHealthChecks, + alertResources, + alertEmailActions, + alertEmailRecipients, + alertWebhookActions, + userOrgRoles, + users +} from "@server/db"; +import config from "@server/lib/config"; +import { decrypt } from "@server/lib/crypto"; +import logger from "@server/logger"; +import { AlertContext, WebhookAlertConfig } from "./types"; +import { sendAlertWebhook } from "./sendAlertWebhook"; +import { sendAlertEmail } from "./sendAlertEmail"; + +/** + * Core alert processing pipeline. + * + * Given an `AlertContext`, this function: + * 1. Finds all enabled `alertRules` whose `eventType` matches and whose + * `siteId` / `healthCheckId` is listed in the `alertSites` / + * `alertHealthChecks` junction tables (or has no junction entries, + * meaning "match all"). + * 2. Applies per-rule cooldown gating. + * 3. Dispatches emails and webhook POSTs for every attached action. + * 4. Updates `lastTriggeredAt` and `lastSentAt` timestamps. + */ +export async function processAlerts(context: AlertContext): Promise { + const now = Date.now(); + + // ------------------------------------------------------------------ + // 1. Find matching alert rules + // ------------------------------------------------------------------ + // Rules with allSites / allHealthChecks / allResources set to true match + // ANY event of that type. Rules without these flags set match only the + // specific IDs listed in the junction tables. + const baseConditions = and( + eq(alertRules.orgId, context.orgId), + eq(alertRules.eventType, context.eventType), + eq(alertRules.enabled, true) + ); + + let rules: (typeof alertRules.$inferSelect)[]; + + if (context.siteId != null) { + const rows = await db + .select() + .from(alertRules) + .leftJoin( + alertSites, + eq(alertSites.alertRuleId, alertRules.alertRuleId) + ) + .where( + and( + baseConditions, + or( + eq(alertRules.allSites, true), + eq(alertSites.siteId, context.siteId) + ) + ) + ); + // Deduplicate in case a rule matched on multiple junction rows + const seen = new Set(); + rules = rows + .map((r) => r.alertRules) + .filter((r) => { + if (seen.has(r.alertRuleId)) return false; + seen.add(r.alertRuleId); + return true; + }); + } else if (context.healthCheckId != null) { + const rows = await db + .select() + .from(alertRules) + .leftJoin( + alertHealthChecks, + eq(alertHealthChecks.alertRuleId, alertRules.alertRuleId) + ) + .where( + and( + baseConditions, + or( + eq(alertRules.allHealthChecks, true), + eq(alertHealthChecks.healthCheckId, context.healthCheckId) + ) + ) + ); + const seen = new Set(); + rules = rows + .map((r) => r.alertRules) + .filter((r) => { + if (seen.has(r.alertRuleId)) return false; + seen.add(r.alertRuleId); + return true; + }); + } else if (context.resourceId != null) { + const rows = await db + .select() + .from(alertRules) + .leftJoin( + alertResources, + eq(alertResources.alertRuleId, alertRules.alertRuleId) + ) + .where( + and( + baseConditions, + or( + eq(alertRules.allResources, true), + eq(alertResources.resourceId, context.resourceId) + ) + ) + ); + const seen = new Set(); + rules = rows + .map((r) => r.alertRules) + .filter((r) => { + if (seen.has(r.alertRuleId)) return false; + seen.add(r.alertRuleId); + return true; + }); + } else { + rules = []; + } + + if (rules.length === 0) { + logger.debug( + `processAlerts: no matching rules for event "${context.eventType}" in org "${context.orgId}"` + ); + return; + } + + for (const rule of rules) { + try { + await processRule(rule, context, now); + } catch (err) { + logger.error( + `processAlerts: error processing rule ${rule.alertRuleId} for event "${context.eventType}"`, + err + ); + } + } +} + +// --------------------------------------------------------------------------- +// Per-rule processing +// --------------------------------------------------------------------------- + +async function processRule( + rule: typeof alertRules.$inferSelect, + context: AlertContext, + now: number +): Promise { + // ------------------------------------------------------------------ + // 2. Cooldown check + // ------------------------------------------------------------------ + if ( + rule.lastTriggeredAt != null && + now - rule.lastTriggeredAt < rule.cooldownSeconds * 1000 + ) { + const remainingSeconds = Math.ceil( + (rule.cooldownSeconds * 1000 - (now - rule.lastTriggeredAt)) / 1000 + ); + logger.debug( + `processAlerts: rule ${rule.alertRuleId} is in cooldown – ${remainingSeconds}s remaining` + ); + return; + } + + // ------------------------------------------------------------------ + // 3. Mark rule as triggered (optimistic update – before sending so we + // don't re-trigger if the send is slow) + // ------------------------------------------------------------------ + await db + .update(alertRules) + .set({ lastTriggeredAt: now }) + .where(eq(alertRules.alertRuleId, rule.alertRuleId)); + + // ------------------------------------------------------------------ + // 4. Process email actions + // ------------------------------------------------------------------ + const emailActions = await db + .select() + .from(alertEmailActions) + .where( + and( + eq(alertEmailActions.alertRuleId, rule.alertRuleId), + eq(alertEmailActions.enabled, true) + ) + ); + + for (const action of emailActions) { + try { + const recipients = await resolveEmailRecipients(action.emailActionId); + if (recipients.length > 0) { + await sendAlertEmail(recipients, context); + await db + .update(alertEmailActions) + .set({ lastSentAt: now }) + .where( + eq(alertEmailActions.emailActionId, action.emailActionId) + ); + } + } catch (err) { + logger.error( + `processAlerts: failed to send alert email for action ${action.emailActionId}`, + err + ); + } + } + + // ------------------------------------------------------------------ + // 5. Process webhook actions + // ------------------------------------------------------------------ + const webhookActions = await db + .select() + .from(alertWebhookActions) + .where( + and( + eq(alertWebhookActions.alertRuleId, rule.alertRuleId), + eq(alertWebhookActions.enabled, true) + ) + ); + + const serverSecret = config.getRawConfig().server.secret!; + + for (const action of webhookActions) { + try { + let webhookConfig: WebhookAlertConfig = { authType: "none" }; + + if (action.config) { + try { + const decrypted = decrypt(action.config, serverSecret); + webhookConfig = JSON.parse(decrypted) as WebhookAlertConfig; + } catch (err) { + logger.error( + `processAlerts: failed to decrypt webhook config for action ${action.webhookActionId}`, + err + ); + continue; + } + } + + await sendAlertWebhook(action.webhookUrl, webhookConfig, context); + await db + .update(alertWebhookActions) + .set({ lastSentAt: now }) + .where( + eq( + alertWebhookActions.webhookActionId, + action.webhookActionId + ) + ); + } catch (err) { + logger.error( + `processAlerts: failed to send alert webhook for action ${action.webhookActionId}`, + err + ); + } + } +} + +// --------------------------------------------------------------------------- +// Email recipient resolution +// --------------------------------------------------------------------------- + +/** + * Resolves all email addresses for a given `emailActionId`. + * + * Recipients may be: + * - Direct users (by `userId`) + * - All users in a role (by `roleId`, resolved via `userOrgRoles`) + * - Direct external email addresses + */ +async function resolveEmailRecipients(emailActionId: number): Promise { + const rows = await db + .select() + .from(alertEmailRecipients) + .where(eq(alertEmailRecipients.emailActionId, emailActionId)); + + const emailSet = new Set(); + + for (const row of rows) { + if (row.email) { + emailSet.add(row.email); + } + + if (row.userId) { + const [user] = await db + .select({ email: users.email }) + .from(users) + .where(eq(users.userId, row.userId)) + .limit(1); + if (user?.email) { + emailSet.add(user.email); + } + } + + if (row.roleId) { + // Find all users with this role via userOrgRoles + const roleUsers = await db + .select({ email: users.email }) + .from(userOrgRoles) + .innerJoin(users, eq(userOrgRoles.userId, users.userId)) + .where(eq(userOrgRoles.roleId, Number(row.roleId))); + + for (const u of roleUsers) { + if (u.email) { + emailSet.add(u.email); + } + } + } + } + + return Array.from(emailSet); +} diff --git a/server/private/lib/alerts/sendAlertEmail.ts b/server/private/lib/alerts/sendAlertEmail.ts new file mode 100644 index 000000000..5e818678d --- /dev/null +++ b/server/private/lib/alerts/sendAlertEmail.ts @@ -0,0 +1,101 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { sendEmail } from "@server/emails"; +import AlertNotification from "@server/emails/templates/AlertNotification"; +import config from "@server/lib/config"; +import logger from "@server/logger"; +import { AlertContext } from "./types"; + +/** + * Sends an alert notification email to every address in `recipients`. + * + * Each recipient receives an individual email (no BCC list) so that delivery + * failures for one address do not affect the others. Failures per recipient + * are logged and swallowed – the caller only sees an error if something goes + * wrong before the send loop. + */ +export async function sendAlertEmail( + recipients: string[], + context: AlertContext +): Promise { + if (recipients.length === 0) { + return; + } + + const from = config.getNoReplyEmail(); + const subject = buildSubject(context); + + const baseUrl = config.getRawConfig().app.dashboard_url!.replace(/\/$/, ""); + const dashboardLink = `${baseUrl}/${context.orgId}/settings`; + + for (const to of recipients) { + try { + await sendEmail( + AlertNotification({ + eventType: context.eventType, + orgId: context.orgId, + data: context.data, + dashboardLink + }), + { + from, + to, + subject + } + ); + logger.debug( + `Alert email sent to "${to}" for event "${context.eventType}"` + ); + } catch (err) { + logger.error( + `sendAlertEmail: failed to send alert email to "${to}" for event "${context.eventType}"`, + err + ); + } + } +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function buildSubject(context: AlertContext): string { + switch (context.eventType) { + case "site_online": + return "[Alert] Site Back Online"; + case "site_offline": + return "[Alert] Site Offline"; + case "site_toggle": + return "[Alert] Site Status Changed"; + case "health_check_healthy": + return "[Alert] Health Check Recovered"; + case "health_check_unhealthy": + return "[Alert] Health Check Failing"; + case "health_check_toggle": + return "[Alert] Health Check Status Changed"; + case "resource_healthy": + return "[Alert] Resource Healthy"; + case "resource_unhealthy": + return "[Alert] Resource Unhealthy"; + case "resource_toggle": + return "[Alert] Resource Status Changed"; + default: { + // Exhaustiveness fallback – should never be reached with a + // well-typed caller, but keeps runtime behaviour predictable. + const _exhaustive: never = context.eventType; + void _exhaustive; + return "[Alert] Event Notification"; + } + } +} diff --git a/server/private/lib/alerts/sendAlertWebhook.ts b/server/private/lib/alerts/sendAlertWebhook.ts new file mode 100644 index 000000000..52c687cbc --- /dev/null +++ b/server/private/lib/alerts/sendAlertWebhook.ts @@ -0,0 +1,140 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import logger from "@server/logger"; +import { AlertContext, WebhookAlertConfig } from "./types"; + +const REQUEST_TIMEOUT_MS = 15_000; + +/** + * Sends a single webhook POST for an alert event. + * + * The payload shape is: + * ```json + * { + * "event": "site_online", + * "timestamp": "2024-01-01T00:00:00.000Z", + * "data": { ... } + * } + * ``` + * + * Authentication headers are applied according to `config.authType`, + * mirroring the same strategies supported by HttpLogDestination: + * none | bearer | basic | custom. + */ +export async function sendAlertWebhook( + url: string, + webhookConfig: WebhookAlertConfig, + context: AlertContext +): Promise { + const payload = { + event: context.eventType, + timestamp: new Date().toISOString(), + data: { + orgId: context.orgId, + ...context.data + } + }; + + const body = JSON.stringify(payload); + const headers = buildHeaders(webhookConfig); + + const controller = new AbortController(); + const timeoutHandle = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); + + let response: Response; + try { + response = await fetch(url, { + method: webhookConfig.method ?? "POST", + headers, + body, + signal: controller.signal + }); + } catch (err: unknown) { + const isAbort = err instanceof Error && err.name === "AbortError"; + if (isAbort) { + throw new Error( + `Alert webhook: request to "${url}" timed out after ${REQUEST_TIMEOUT_MS} ms` + ); + } + const msg = err instanceof Error ? err.message : String(err); + throw new Error(`Alert webhook: request to "${url}" failed – ${msg}`); + } finally { + clearTimeout(timeoutHandle); + } + + if (!response.ok) { + let snippet = ""; + try { + const text = await response.text(); + snippet = text.slice(0, 300); + } catch { + // best-effort + } + throw new Error( + `Alert webhook: server at "${url}" returned HTTP ${response.status} ${response.statusText}` + + (snippet ? ` – ${snippet}` : "") + ); + } + + logger.debug(`Alert webhook sent successfully to "${url}" for event "${context.eventType}"`); +} + +// --------------------------------------------------------------------------- +// Header construction (mirrors HttpLogDestination.buildHeaders) +// --------------------------------------------------------------------------- + +function buildHeaders(webhookConfig: WebhookAlertConfig): Record { + const headers: Record = { + "Content-Type": "application/json" + }; + + switch (webhookConfig.authType) { + case "bearer": { + const token = webhookConfig.bearerToken?.trim(); + if (token) { + headers["Authorization"] = `Bearer ${token}`; + } + break; + } + case "basic": { + const creds = webhookConfig.basicCredentials?.trim(); + if (creds) { + const encoded = Buffer.from(creds).toString("base64"); + headers["Authorization"] = `Basic ${encoded}`; + } + break; + } + case "custom": { + const name = webhookConfig.customHeaderName?.trim(); + const value = webhookConfig.customHeaderValue ?? ""; + if (name) { + headers[name] = value; + } + break; + } + case "none": + default: + break; + } + + if (webhookConfig.headers) { + for (const { key, value } of webhookConfig.headers) { + if (key.trim()) { + headers[key.trim()] = value; + } + } + } + + return headers; +} \ No newline at end of file diff --git a/server/private/lib/alerts/types.ts b/server/private/lib/alerts/types.ts new file mode 100644 index 000000000..0679b7ece --- /dev/null +++ b/server/private/lib/alerts/types.ts @@ -0,0 +1,70 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +// --------------------------------------------------------------------------- +// Alert event types +// --------------------------------------------------------------------------- + +export type AlertEventType = + | "site_online" + | "site_offline" + | "site_toggle" + | "health_check_healthy" + | "health_check_unhealthy" + | "health_check_toggle" + | "resource_healthy" + | "resource_unhealthy" + | "resource_toggle"; + +// --------------------------------------------------------------------------- +// Webhook authentication config (stored as encrypted JSON in the DB) +// --------------------------------------------------------------------------- + +export type WebhookAuthType = "none" | "bearer" | "basic" | "custom"; + +/** + * Stored as an encrypted JSON blob in `alertWebhookActions.config`. + */ +export interface WebhookAlertConfig { + /** Authentication strategy for the webhook endpoint */ + authType: WebhookAuthType; + /** Bearer token – used when authType === "bearer" */ + bearerToken?: string; + /** Basic credentials – "username:password" – used when authType === "basic" */ + basicCredentials?: string; + /** Custom header name – used when authType === "custom" */ + customHeaderName?: string; + /** Custom header value – used when authType === "custom" */ + customHeaderValue?: string; + /** Extra headers to send with every webhook request */ + headers?: Array<{ key: string; value: string }>; + /** HTTP method (default POST) */ + method?: string; +} + +// --------------------------------------------------------------------------- +// Internal alert event passed through the processing pipeline +// --------------------------------------------------------------------------- + +export interface AlertContext { + eventType: AlertEventType; + orgId: string; + /** Set for site_online / site_offline events */ + siteId?: number; + /** Set for health_check_* events */ + healthCheckId?: number; + /** Set for resource_* events */ + resourceId?: number; + /** Human-readable context data included in emails and webhook payloads */ + data: Record; +} diff --git a/server/private/lib/certificates.ts b/server/private/lib/certificates.ts index ae076c48e..af6f6fdaa 100644 --- a/server/private/lib/certificates.ts +++ b/server/private/lib/certificates.ts @@ -11,23 +11,15 @@ * This file is not licensed under the AGPLv3. */ -import config from "./config"; +import privateConfig from "./config"; +import config from "@server/lib/config"; import { certificates, db } from "@server/db"; import { and, eq, isNotNull, or, inArray, sql } from "drizzle-orm"; -import { decryptData } from "@server/lib/encryption"; +import { decrypt } from "@server/lib/crypto"; import logger from "@server/logger"; import cache from "#private/lib/cache"; -let encryptionKeyHex = ""; -let encryptionKey: Buffer; -function loadEncryptData() { - if (encryptionKey) { - return; // already loaded - } - encryptionKeyHex = config.getRawPrivateConfig().server.encryption_key; - encryptionKey = Buffer.from(encryptionKeyHex, "hex"); -} // Define the return type for clarity and type safety export type CertificateResult = { @@ -45,7 +37,7 @@ export async function getValidCertificatesForDomains( domains: Set, useCache: boolean = true ): Promise> { - loadEncryptData(); // Ensure encryption key is loaded + const finalResults: CertificateResult[] = []; const domainsToQuery = new Set(); @@ -68,7 +60,7 @@ export async function getValidCertificatesForDomains( // 2. If all domains were resolved from the cache, return early if (domainsToQuery.size === 0) { - const decryptedResults = decryptFinalResults(finalResults); + const decryptedResults = decryptFinalResults(finalResults, config.getRawConfig().server.secret!); return decryptedResults; } @@ -173,22 +165,23 @@ export async function getValidCertificatesForDomains( } } - const decryptedResults = decryptFinalResults(finalResults); + const decryptedResults = decryptFinalResults(finalResults, config.getRawConfig().server.secret!); return decryptedResults; } function decryptFinalResults( - finalResults: CertificateResult[] + finalResults: CertificateResult[], + secret: string ): CertificateResult[] { const validCertsDecrypted = finalResults.map((cert) => { // Decrypt and save certificate file - const decryptedCert = decryptData( + const decryptedCert = decrypt( cert.certFile!, // is not null from query - encryptionKey + secret ); // Decrypt and save key file - const decryptedKey = decryptData(cert.keyFile!, encryptionKey); + const decryptedKey = decrypt(cert.keyFile!, secret); // Return only the certificate data without org information return { diff --git a/server/private/lib/logConnectionAudit.ts b/server/private/lib/logConnectionAudit.ts index 8cc3a1e52..039b75ec9 100644 --- a/server/private/lib/logConnectionAudit.ts +++ b/server/private/lib/logConnectionAudit.ts @@ -153,7 +153,7 @@ export async function flushConnectionLogToDb(): Promise { ); } - // Stop processing further batches from this snapshot — they will + // Stop processing further batches from this snapshot - they will // be picked up via the re-queued records on the next flush. const remaining = snapshot.slice(i + INSERT_BATCH_SIZE); if (remaining.length > 0) { @@ -180,7 +180,7 @@ const flushTimer = setInterval(async () => { }, FLUSH_INTERVAL_MS); // Calling unref() means this timer will not keep the Node.js event loop alive -// on its own — the process can still exit normally when there is no other work +// on its own - the process can still exit normally when there is no other work // left. The graceful-shutdown path will call flushConnectionLogToDb() explicitly // before process.exit(), so no data is lost. flushTimer.unref(); @@ -223,7 +223,7 @@ export function logConnectionAudit(record: ConnectionLogRecord): void { buffer.push(record); if (buffer.length >= MAX_BUFFERED_RECORDS) { - // Fire and forget — errors are handled inside flushConnectionLogToDb + // Fire and forget - errors are handled inside flushConnectionLogToDb flushConnectionLogToDb().catch((error) => { logger.error( "Unexpected error during size-triggered connection log flush:", @@ -231,4 +231,4 @@ export function logConnectionAudit(record: ConnectionLogRecord): void { ); }); } -} \ No newline at end of file +} diff --git a/server/private/lib/logStreaming/providers/HttpLogDestination.ts b/server/private/lib/logStreaming/providers/HttpLogDestination.ts index dde7bd695..337a58f1f 100644 --- a/server/private/lib/logStreaming/providers/HttpLogDestination.ts +++ b/server/private/lib/logStreaming/providers/HttpLogDestination.ts @@ -37,7 +37,7 @@ const DEFAULT_FORMAT: PayloadFormat = "json_array"; * * **Payload formats** (controlled by `config.format`): * - * - `json_array` (default) — one POST per batch, body is a JSON array: + * - `json_array` (default) - one POST per batch, body is a JSON array: * ```json * [ * { "event": "request", "timestamp": "2024-01-01T00:00:00.000Z", "data": { … } }, @@ -46,7 +46,7 @@ const DEFAULT_FORMAT: PayloadFormat = "json_array"; * ``` * `Content-Type: application/json` * - * - `ndjson` — one POST per batch, body is newline-delimited JSON (one object + * - `ndjson` - one POST per batch, body is newline-delimited JSON (one object * per line, no outer array). Required by Splunk HEC, Elastic/OpenSearch, * and Grafana Loki: * ``` @@ -55,7 +55,7 @@ const DEFAULT_FORMAT: PayloadFormat = "json_array"; * ``` * `Content-Type: application/x-ndjson` * - * - `json_single` — one POST **per event**, body is a plain JSON object. + * - `json_single` - one POST **per event**, body is a plain JSON object. * Use only for endpoints that cannot handle batches at all. * * With a body template each event is rendered through the template before @@ -319,4 +319,4 @@ function epochSecondsToIso(epochSeconds: number): string { function escapeJsonString(value: string): string { // JSON.stringify produces `""` – strip the outer quotes. return JSON.stringify(value).slice(1, -1); -} \ No newline at end of file +} diff --git a/server/private/lib/logStreaming/types.ts b/server/private/lib/logStreaming/types.ts index 5eed79520..1bcd25a66 100644 --- a/server/private/lib/logStreaming/types.ts +++ b/server/private/lib/logStreaming/types.ts @@ -60,9 +60,9 @@ export type AuthType = "none" | "bearer" | "basic" | "custom"; /** * Controls how the batch of events is serialised into the HTTP request body. * - * - `json_array` – `[{…}, {…}]` — default; one POST per batch wrapped in a + * - `json_array` – `[{…}, {…}]` - default; one POST per batch wrapped in a * JSON array. Works with most generic webhooks and Datadog. - * - `ndjson` – `{…}\n{…}` — newline-delimited JSON, one object per + * - `ndjson` – `{…}\n{…}` - newline-delimited JSON, one object per * line. Required by Splunk HEC, Elastic/OpenSearch, Loki. * - `json_single` – one HTTP POST per event, body is a plain JSON object. * Use only for endpoints that cannot handle batches at all. @@ -131,4 +131,4 @@ export interface DestinationFailureState { nextRetryAt: number; /** Date.now() value of the very first failure in the current streak */ firstFailedAt: number; -} \ No newline at end of file +} diff --git a/server/private/lib/readConfigFile.ts b/server/private/lib/readConfigFile.ts index f239edd85..c9cb1535a 100644 --- a/server/private/lib/readConfigFile.ts +++ b/server/private/lib/readConfigFile.ts @@ -34,10 +34,6 @@ export const privateConfigSchema = z.object({ }), server: z .object({ - encryption_key: z - .string() - .optional() - .transform(getEnvOrYaml("SERVER_ENCRYPTION_KEY")), reo_client_id: z .string() .optional() @@ -95,10 +91,21 @@ export const privateConfigSchema = z.object({ .object({ enable_redis: z.boolean().optional().default(false), use_pangolin_dns: z.boolean().optional().default(false), - use_org_only_idp: z.boolean().optional() + use_org_only_idp: z.boolean().optional(), + enable_acme_cert_sync: z.boolean().optional().default(true) }) .optional() .prefault({}), + acme: z + .object({ + acme_json_path: z + .string() + .optional() + .default("config/letsencrypt/acme.json"), + resolver: z.string().optional().default("letsencrypt"), + sync_interval_ms: z.number().optional().default(5000) + }) + .optional(), branding: z .object({ app_name: z.string().optional(), diff --git a/server/private/lib/traefik/getTraefikConfig.ts b/server/private/lib/traefik/getTraefikConfig.ts index 5ab96d6d6..fb6e176b8 100644 --- a/server/private/lib/traefik/getTraefikConfig.ts +++ b/server/private/lib/traefik/getTraefikConfig.ts @@ -33,7 +33,7 @@ import { } from "drizzle-orm"; import logger from "@server/logger"; import config from "@server/lib/config"; -import { orgs, resources, sites, Target, targets } from "@server/db"; +import { orgs, resources, sites, siteNetworks, siteResources, Target, targets } from "@server/db"; import { sanitize, encodePath, @@ -267,6 +267,35 @@ export async function getTraefikConfig( }); }); + // Query siteResources in HTTP mode with SSL enabled and aliases - cert generation / HTTPS edge + const siteResourcesWithFullDomain = await db + .select({ + siteResourceId: siteResources.siteResourceId, + fullDomain: siteResources.fullDomain, + mode: siteResources.mode + }) + .from(siteResources) + .innerJoin(siteNetworks, eq(siteResources.networkId, siteNetworks.networkId)) + .innerJoin(sites, eq(siteNetworks.siteId, sites.siteId)) + .where( + and( + eq(siteResources.enabled, true), + isNotNull(siteResources.fullDomain), + eq(siteResources.mode, "http"), + eq(siteResources.ssl, true), + or( + eq(sites.exitNodeId, exitNodeId), + and( + isNull(sites.exitNodeId), + sql`(${siteTypes.includes("local") ? 1 : 0} = 1)`, + eq(sites.type, "local"), + sql`(${build != "saas" ? 1 : 0} = 1)` + ) + ), + inArray(sites.type, siteTypes) + ) + ); + let validCerts: CertificateResult[] = []; if (privateConfig.getRawPrivateConfig().flags.use_pangolin_dns) { // create a list of all domains to get certs for @@ -276,6 +305,12 @@ export async function getTraefikConfig( domains.add(resource.fullDomain); } } + // Include siteResource aliases so pangolin-dns also fetches certs for them + for (const sr of siteResourcesWithFullDomain) { + if (sr.fullDomain) { + domains.add(sr.fullDomain); + } + } // get the valid certs for these domains validCerts = await getValidCertificatesForDomains(domains, true); // we are caching here because this is called often // logger.debug(`Valid certs for domains: ${JSON.stringify(validCerts)}`); @@ -867,6 +902,139 @@ export async function getTraefikConfig( } } + // Add Traefik routes for siteResource aliases (HTTP mode + SSL) so that + // Traefik generates TLS certificates for those domains even when no + // matching resource exists yet. + if (siteResourcesWithFullDomain.length > 0) { + // Build a set of domains already covered by normal resources + const existingFullDomains = new Set(); + for (const resource of resourcesMap.values()) { + if (resource.fullDomain) { + existingFullDomains.add(resource.fullDomain); + } + } + + for (const sr of siteResourcesWithFullDomain) { + if (!sr.fullDomain) continue; + + // Skip if this alias is already handled by a resource router + if (existingFullDomains.has(sr.fullDomain)) continue; + + const fullDomain = sr.fullDomain; + const srKey = `site-resource-cert-${sr.siteResourceId}`; + const siteResourceServiceName = `${srKey}-service`; + const siteResourceRouterName = `${srKey}-router`; + const siteResourceRewriteMiddlewareName = `${srKey}-rewrite`; + + const maintenancePort = config.getRawConfig().server.next_port; + const maintenanceHost = + config.getRawConfig().server.internal_hostname; + + if (!config_output.http.routers) { + config_output.http.routers = {}; + } + if (!config_output.http.services) { + config_output.http.services = {}; + } + if (!config_output.http.middlewares) { + config_output.http.middlewares = {}; + } + + // Service pointing at the internal maintenance/Next.js page + config_output.http.services[siteResourceServiceName] = { + loadBalancer: { + servers: [ + { + url: `http://${maintenanceHost}:${maintenancePort}` + } + ], + passHostHeader: true + } + }; + + // Middleware that rewrites any path to /maintenance-screen + config_output.http.middlewares[ + siteResourceRewriteMiddlewareName + ] = { + replacePathRegex: { + regex: "^/(.*)", + replacement: "/private-maintenance-screen" + } + }; + + // HTTP -> HTTPS redirect so the ACME challenge can be served + config_output.http.routers[ + `${siteResourceRouterName}-redirect` + ] = { + entryPoints: [ + config.getRawConfig().traefik.http_entrypoint + ], + middlewares: [redirectHttpsMiddlewareName], + service: siteResourceServiceName, + rule: `Host(\`${fullDomain}\`)`, + priority: 100 + }; + + // Determine TLS / cert-resolver configuration + let tls: any = {}; + if ( + !privateConfig.getRawPrivateConfig().flags.use_pangolin_dns + ) { + const domainParts = fullDomain.split("."); + const wildCard = + domainParts.length <= 2 + ? `*.${domainParts.join(".")}` + : `*.${domainParts.slice(1).join(".")}`; + + const globalDefaultResolver = + config.getRawConfig().traefik.cert_resolver; + const globalDefaultPreferWildcard = + config.getRawConfig().traefik.prefer_wildcard_cert; + + tls = { + certResolver: globalDefaultResolver, + ...(globalDefaultPreferWildcard + ? { domains: [{ main: wildCard }] } + : {}) + }; + } else { + // pangolin-dns: only add route if we already have a valid cert + const matchingCert = validCerts.find( + (cert) => cert.queriedDomain === fullDomain + ); + if (!matchingCert) { + logger.debug( + `No matching certificate found for siteResource alias: ${fullDomain}` + ); + continue; + } + } + + // HTTPS router - presence of this entry triggers cert generation + config_output.http.routers[siteResourceRouterName] = { + entryPoints: [ + config.getRawConfig().traefik.https_entrypoint + ], + service: siteResourceServiceName, + middlewares: [siteResourceRewriteMiddlewareName], + rule: `Host(\`${fullDomain}\`)`, + priority: 100, + tls + }; + + // Assets bypass router - lets Next.js static files load without rewrite + config_output.http.routers[`${siteResourceRouterName}-assets`] = { + entryPoints: [ + config.getRawConfig().traefik.https_entrypoint + ], + service: siteResourceServiceName, + rule: `Host(\`${fullDomain}\`) && (PathPrefix(\`/_next\`) || PathRegexp(\`^/__nextjs*\`))`, + priority: 101, + tls + }; + } + } + if (generateLoginPageRouters) { const exitNodeLoginPages = await db .select({ diff --git a/server/private/routers/alertEvents/index.ts b/server/private/routers/alertEvents/index.ts new file mode 100644 index 000000000..485b434eb --- /dev/null +++ b/server/private/routers/alertEvents/index.ts @@ -0,0 +1,16 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +export * from "./triggerSiteAlert"; +export * from "./triggerResourceAlert"; +export * from "./triggerHealthCheckAlert"; \ No newline at end of file diff --git a/server/private/routers/alertEvents/triggerHealthCheckAlert.ts b/server/private/routers/alertEvents/triggerHealthCheckAlert.ts new file mode 100644 index 000000000..94202b0b2 --- /dev/null +++ b/server/private/routers/alertEvents/triggerHealthCheckAlert.ts @@ -0,0 +1,129 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db } from "@server/db"; +import { targetHealthCheck, statusHistory } from "@server/db"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { eq, and } from "drizzle-orm"; +import { + fireHealthCheckHealthyAlert, + fireHealthCheckUnhealthyAlert +} from "#private/lib/alerts/events/healthCheckEvents"; + +const paramsSchema = z.strictObject({ + orgId: z.string().nonempty(), + healthCheckId: z.coerce.number().int().positive() +}); + +const bodySchema = z.strictObject({ + eventType: z.enum(["health_check_healthy", "health_check_unhealthy"]) +}); + +export type TriggerHealthCheckAlertResponse = { + success: true; +}; + +export async function triggerHealthCheckAlert( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = paramsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + const { orgId, healthCheckId } = parsedParams.data; + + const parsedBody = bodySchema.safeParse(req.body); + if (!parsedBody.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedBody.error).toString() + ) + ); + } + const { eventType } = parsedBody.data; + + // Verify the health check exists and belongs to the org + const [healthCheck] = await db + .select() + .from(targetHealthCheck) + .where( + and( + eq( + targetHealthCheck.targetHealthCheckId, + healthCheckId + ), + eq(targetHealthCheck.orgId, orgId) + ) + ) + .limit(1); + + if (!healthCheck) { + return next( + createHttpError( + HttpCode.NOT_FOUND, + `Health check ${healthCheckId} not found in organization ${orgId}` + ) + ); + } + + await db.insert(statusHistory).values({ + entityType: "healthCheck", + entityId: healthCheckId, + orgId, + status: eventType === "health_check_healthy" ? "healthy" : "unhealthy", + timestamp: Math.floor(Date.now() / 1000) + }); + + if (eventType === "health_check_healthy") { + await fireHealthCheckHealthyAlert( + orgId, + healthCheckId, + healthCheck.name ?? undefined + ); + } else { + await fireHealthCheckUnhealthyAlert( + orgId, + healthCheckId, + healthCheck.name ?? undefined + ); + } + + return response(res, { + data: { success: true }, + success: true, + error: false, + message: "Alert triggered successfully", + status: HttpCode.OK + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} diff --git a/server/private/routers/alertEvents/triggerResourceAlert.ts b/server/private/routers/alertEvents/triggerResourceAlert.ts new file mode 100644 index 000000000..61b81d900 --- /dev/null +++ b/server/private/routers/alertEvents/triggerResourceAlert.ts @@ -0,0 +1,135 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db } from "@server/db"; +import { resources, statusHistory } from "@server/db"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { eq, and } from "drizzle-orm"; +import { + fireResourceHealthyAlert, + fireResourceUnhealthyAlert, + fireResourceToggleAlert +} from "#private/lib/alerts/events/resourceEvents"; + +const paramsSchema = z.strictObject({ + orgId: z.string().nonempty(), + resourceId: z.coerce.number().int().positive() +}); + +const bodySchema = z.strictObject({ + eventType: z.enum(["resource_healthy", "resource_unhealthy", "resource_toggle"]) +}); + +export type TriggerResourceAlertResponse = { + success: true; +}; + +export async function triggerResourceAlert( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = paramsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + const { orgId, resourceId } = parsedParams.data; + + const parsedBody = bodySchema.safeParse(req.body); + if (!parsedBody.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedBody.error).toString() + ) + ); + } + const { eventType } = parsedBody.data; + + // Verify the resource exists and belongs to the org + const [resource] = await db + .select() + .from(resources) + .where( + and( + eq(resources.resourceId, resourceId), + eq(resources.orgId, orgId) + ) + ) + .limit(1); + + if (!resource) { + return next( + createHttpError( + HttpCode.NOT_FOUND, + `Resource ${resourceId} not found in organization ${orgId}` + ) + ); + } + + if (eventType === "resource_healthy" || eventType === "resource_unhealthy") { + await db.insert(statusHistory).values({ + entityType: "resource", + entityId: resourceId, + orgId, + status: eventType === "resource_healthy" ? "healthy" : "unhealthy", + timestamp: Math.floor(Date.now() / 1000) + }); + } + + if (eventType === "resource_healthy") { + await fireResourceHealthyAlert( + orgId, + resourceId, + resource.name ?? undefined + ); + } else if (eventType === "resource_unhealthy") { + await fireResourceUnhealthyAlert( + orgId, + resourceId, + resource.name ?? undefined + ); + } else { + await fireResourceToggleAlert( + orgId, + resourceId, + resource.name ?? undefined + ); + } + + return response(res, { + data: { success: true }, + success: true, + error: false, + message: "Alert triggered successfully", + status: HttpCode.OK + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} \ No newline at end of file diff --git a/server/private/routers/alertEvents/triggerSiteAlert.ts b/server/private/routers/alertEvents/triggerSiteAlert.ts new file mode 100644 index 000000000..084fbc758 --- /dev/null +++ b/server/private/routers/alertEvents/triggerSiteAlert.ts @@ -0,0 +1,113 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db } from "@server/db"; +import { sites, statusHistory } from "@server/db"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { eq, and } from "drizzle-orm"; +import { + fireSiteOnlineAlert, + fireSiteOfflineAlert +} from "#private/lib/alerts/events/siteEvents"; + +const paramsSchema = z.strictObject({ + orgId: z.string().nonempty(), + siteId: z.coerce.number().int().positive() +}); + +const bodySchema = z.strictObject({ + eventType: z.enum(["site_online", "site_offline"]) +}); + +export type TriggerSiteAlertResponse = { + success: true; +}; + +export async function triggerSiteAlert( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = paramsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + const { orgId, siteId } = parsedParams.data; + + const parsedBody = bodySchema.safeParse(req.body); + if (!parsedBody.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedBody.error).toString() + ) + ); + } + const { eventType } = parsedBody.data; + + // Verify the site exists and belongs to the org + const [site] = await db + .select() + .from(sites) + .where(and(eq(sites.siteId, siteId), eq(sites.orgId, orgId))) + .limit(1); + + if (!site) { + return next( + createHttpError( + HttpCode.NOT_FOUND, + `Site ${siteId} not found in organization ${orgId}` + ) + ); + } + + await db.insert(statusHistory).values({ + entityType: "site", + entityId: siteId, + orgId, + status: eventType === "site_online" ? "online" : "offline", + timestamp: Math.floor(Date.now() / 1000) + }); + + if (eventType === "site_online") { + await fireSiteOnlineAlert(orgId, siteId, site.name ?? undefined); + } else { + await fireSiteOfflineAlert(orgId, siteId, site.name ?? undefined); + } + + return response(res, { + data: { success: true }, + success: true, + error: false, + message: "Alert triggered successfully", + status: HttpCode.OK + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} \ No newline at end of file diff --git a/server/private/routers/alertRule/createAlertRule.ts b/server/private/routers/alertRule/createAlertRule.ts new file mode 100644 index 000000000..b9d17d35d --- /dev/null +++ b/server/private/routers/alertRule/createAlertRule.ts @@ -0,0 +1,354 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db, roles } from "@server/db"; +import { + alertRules, + alertSites, + alertHealthChecks, + alertResources, + alertEmailActions, + alertEmailRecipients, + alertWebhookActions +} from "@server/db"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { OpenAPITags, registry } from "@server/openApi"; +import { encrypt } from "@server/lib/crypto"; +import config from "@server/lib/config"; + +export const SITE_EVENT_TYPES = ["site_online", "site_offline", "site_toggle"] as const; +export const HC_EVENT_TYPES = [ + "health_check_healthy", + "health_check_unhealthy", + "health_check_toggle" +] as const; +export const RESOURCE_EVENT_TYPES = [ + "resource_healthy", + "resource_unhealthy", + "resource_toggle" +] as const; + +const paramsSchema = z.strictObject({ + orgId: z.string().nonempty() +}); + +const webhookActionSchema = z.strictObject({ + webhookUrl: z.string().url(), + config: z.string().optional(), + enabled: z.boolean().optional().default(true) +}); + +const bodySchema = z + .strictObject({ + name: z.string().nonempty(), + eventType: z.enum([ + ...HC_EVENT_TYPES, + ...SITE_EVENT_TYPES, + ...RESOURCE_EVENT_TYPES + ]), + enabled: z.boolean().optional().default(true), + cooldownSeconds: z.number().int().nonnegative().optional().default(0), + // Source join tables - which is required depends on eventType + siteIds: z.array(z.number().int().positive()).optional().default([]), + allSites: z.boolean().optional().default(false), + healthCheckIds: z + .array(z.number().int().positive()) + .optional() + .default([]), + allHealthChecks: z.boolean().optional().default(false), + resourceIds: z + .array(z.number().int().positive()) + .optional() + .default([]), + allResources: z.boolean().optional().default(false), + // Email recipients (flat) + userIds: z.array(z.string().nonempty()).optional().default([]), + roleIds: z.array(z.number()).optional().default([]), + emails: z.array(z.string().email()).optional().default([]), + // Webhook actions + webhookActions: z.array(webhookActionSchema).optional().default([]) + }) + .superRefine((val, ctx) => { + const isSiteEvent = (SITE_EVENT_TYPES as readonly string[]).includes( + val.eventType + ); + const isHcEvent = (HC_EVENT_TYPES as readonly string[]).includes( + val.eventType + ); + const isResourceEvent = (RESOURCE_EVENT_TYPES as readonly string[]).includes( + val.eventType + ); + + if (isSiteEvent && !val.allSites && val.siteIds.length === 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "At least one siteId is required for site event types when allSites is false", + path: ["siteIds"] + }); + } + + if (isHcEvent && !val.allHealthChecks && val.healthCheckIds.length === 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: + "At least one healthCheckId is required for health check event types when allHealthChecks is false", + path: ["healthCheckIds"] + }); + } + + if (isSiteEvent && val.healthCheckIds.length > 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "healthCheckIds must not be set for site event types", + path: ["healthCheckIds"] + }); + } + + if (isHcEvent && val.siteIds.length > 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "siteIds must not be set for health check event types", + path: ["siteIds"] + }); + } + + if (isResourceEvent && !val.allResources && val.resourceIds.length === 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "At least one resourceId is required for resource event types when allResources is false", + path: ["resourceIds"] + }); + } + + if (isResourceEvent && val.siteIds.length > 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "siteIds must not be set for resource event types", + path: ["siteIds"] + }); + } + + if (isResourceEvent && val.healthCheckIds.length > 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "healthCheckIds must not be set for resource event types", + path: ["healthCheckIds"] + }); + } + + if (isSiteEvent && val.resourceIds.length > 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "resourceIds must not be set for site event types", + path: ["resourceIds"] + }); + } + + if (isHcEvent && val.resourceIds.length > 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "resourceIds must not be set for health check event types", + path: ["resourceIds"] + }); + } + }); + +export type CreateAlertRuleResponse = { + alertRuleId: number; +}; + +registry.registerPath({ + method: "put", + path: "/org/{orgId}/alert-rule", + description: "Create an alert rule for a specific organization.", + tags: [OpenAPITags.Org], + request: { + params: paramsSchema, + body: { + content: { + "application/json": { + schema: bodySchema + } + } + } + }, + responses: {} +}); + +export async function createAlertRule( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = paramsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + + const { orgId } = parsedParams.data; + + const parsedBody = bodySchema.safeParse(req.body); + if (!parsedBody.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedBody.error).toString() + ) + ); + } + + const { + name, + eventType, + enabled, + cooldownSeconds, + siteIds, + allSites, + healthCheckIds, + allHealthChecks, + resourceIds, + allResources, + userIds, + roleIds, + emails, + webhookActions + } = parsedBody.data; + + const now = Date.now(); + + const [rule] = await db + .insert(alertRules) + .values({ + orgId, + name, + eventType, + enabled, + cooldownSeconds, + allSites, + allHealthChecks, + allResources, + createdAt: now, + updatedAt: now + }) + .returning(); + + // Insert site associations (skipped when allSites=true — empty junction = match all) + if (!allSites && siteIds.length > 0) { + await db.insert(alertSites).values( + siteIds.map((siteId) => ({ + alertRuleId: rule.alertRuleId, + siteId + })) + ); + } + + // Insert health check associations (skipped when allHealthChecks=true) + if (!allHealthChecks && healthCheckIds.length > 0) { + await db.insert(alertHealthChecks).values( + healthCheckIds.map((healthCheckId) => ({ + alertRuleId: rule.alertRuleId, + healthCheckId + })) + ); + } + + // Insert resource associations (skipped when allResources=true) + if (!allResources && resourceIds.length > 0) { + await db.insert(alertResources).values( + resourceIds.map((resourceId) => ({ + alertRuleId: rule.alertRuleId, + resourceId + })) + ); + } + + // Create the email action pivot row and recipients if any recipients + // were supplied (userIds, roleIds, or raw emails). + const hasRecipients = + userIds.length > 0 || + roleIds.length > 0 || + emails.length > 0; + + if (hasRecipients) { + const [emailActionRow] = await db + .insert(alertEmailActions) + .values({ alertRuleId: rule.alertRuleId }) + .returning(); + + const recipientRows = [ + ...userIds.map((userId) => ({ + emailActionId: emailActionRow.emailActionId, + userId, + roleId: null as number | null, + email: null as string | null + })), + ...roleIds.map((roleId) => ({ + emailActionId: emailActionRow.emailActionId, + userId: null as string | null, + roleId, + email: null as string | null + })), + ...emails.map((email) => ({ + emailActionId: emailActionRow.emailActionId, + userId: null as string | null, + roleId: null as number | null, + email + })) + ]; + + await db.insert(alertEmailRecipients).values(recipientRows); + } + + if (webhookActions.length > 0) { + const serverSecret = config.getRawConfig().server.secret!; + await db.insert(alertWebhookActions).values( + webhookActions.map((wa) => ({ + alertRuleId: rule.alertRuleId, + webhookUrl: wa.webhookUrl, + config: + wa.config != null + ? encrypt(wa.config, serverSecret) + : null, + enabled: wa.enabled + })) + ); + } + + return response(res, { + data: { + alertRuleId: rule.alertRuleId + }, + success: true, + error: false, + message: "Alert rule created successfully", + status: HttpCode.CREATED + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} diff --git a/server/private/routers/alertRule/deleteAlertRule.ts b/server/private/routers/alertRule/deleteAlertRule.ts new file mode 100644 index 000000000..0988cd631 --- /dev/null +++ b/server/private/routers/alertRule/deleteAlertRule.ts @@ -0,0 +1,100 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db } from "@server/db"; +import { alertRules } from "@server/db"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { OpenAPITags, registry } from "@server/openApi"; +import { and, eq } from "drizzle-orm"; + +const paramsSchema = z + .object({ + orgId: z.string().nonempty(), + alertRuleId: z.coerce.number() + }) + .strict(); + +registry.registerPath({ + method: "delete", + path: "/org/{orgId}/alert-rule/{alertRuleId}", + description: "Delete an alert rule for a specific organization.", + tags: [OpenAPITags.Org], + request: { + params: paramsSchema + }, + responses: {} +}); + +export async function deleteAlertRule( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = paramsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + + const { orgId, alertRuleId } = parsedParams.data; + + const [existing] = await db + .select() + .from(alertRules) + .where( + and( + eq(alertRules.alertRuleId, alertRuleId), + eq(alertRules.orgId, orgId) + ) + ); + + if (!existing) { + return next( + createHttpError(HttpCode.NOT_FOUND, "Alert rule not found") + ); + } + + await db + .delete(alertRules) + .where( + and( + eq(alertRules.alertRuleId, alertRuleId), + eq(alertRules.orgId, orgId) + ) + ); + + return response(res, { + data: null, + success: true, + error: false, + message: "Alert rule deleted successfully", + status: HttpCode.OK + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} \ No newline at end of file diff --git a/server/private/routers/alertRule/getAlertRule.ts b/server/private/routers/alertRule/getAlertRule.ts new file mode 100644 index 000000000..06a97e880 --- /dev/null +++ b/server/private/routers/alertRule/getAlertRule.ts @@ -0,0 +1,227 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db } from "@server/db"; +import { + alertRules, + alertSites, + alertHealthChecks, + alertResources, + alertEmailActions, + alertEmailRecipients, + alertWebhookActions +} from "@server/db"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { OpenAPITags, registry } from "@server/openApi"; +import { and, eq } from "drizzle-orm"; +import { decrypt } from "@server/lib/crypto"; +import config from "@server/lib/config"; +import { WebhookAlertConfig } from "#private/lib/alerts/types"; + +const paramsSchema = z + .object({ + orgId: z.string().nonempty(), + alertRuleId: z.coerce.number() + }) + .strict(); + +export type GetAlertRuleResponse = { + alertRuleId: number; + orgId: string; + name: string; + eventType: + | "site_online" + | "site_offline" + | "site_toggle" + | "health_check_healthy" + | "health_check_unhealthy" + | "health_check_toggle" + | "resource_healthy" + | "resource_unhealthy" + | "resource_toggle"; + enabled: boolean; + cooldownSeconds: number; + lastTriggeredAt: number | null; + createdAt: number; + updatedAt: number; + siteIds: number[]; + healthCheckIds: number[]; + resourceIds: number[]; + recipients: { + recipientId: number; + userId: string | null; + roleId: number | null; + email: string | null; + }[]; + webhookActions: { + webhookActionId: number; + webhookUrl: string; + enabled: boolean; + lastSentAt: number | null; + config: WebhookAlertConfig | null; + }[]; +}; + +registry.registerPath({ + method: "get", + path: "/org/{orgId}/alert-rule/{alertRuleId}", + description: "Get a specific alert rule for an organization.", + tags: [OpenAPITags.Org], + request: { + params: paramsSchema + }, + responses: {} +}); + +export async function getAlertRule( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = paramsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + + const { orgId, alertRuleId } = parsedParams.data; + + const [rule] = await db + .select() + .from(alertRules) + .where( + and( + eq(alertRules.alertRuleId, alertRuleId), + eq(alertRules.orgId, orgId) + ) + ); + + if (!rule) { + return next( + createHttpError(HttpCode.NOT_FOUND, "Alert rule not found") + ); + } + + // Fetch site associations + const siteRows = await db + .select() + .from(alertSites) + .where(eq(alertSites.alertRuleId, alertRuleId)); + + // Fetch health check associations + const healthCheckRows = await db + .select() + .from(alertHealthChecks) + .where(eq(alertHealthChecks.alertRuleId, alertRuleId)); + + // Fetch resource associations + const resourceRows = await db + .select() + .from(alertResources) + .where(eq(alertResources.alertRuleId, alertRuleId)); + + // Resolve the single email action row for this rule, then collect all + // recipients into a flat list. The emailAction pivot row is an internal + // implementation detail and is not surfaced to callers. + const [emailAction] = await db + .select() + .from(alertEmailActions) + .where(eq(alertEmailActions.alertRuleId, alertRuleId)); + + let recipients: GetAlertRuleResponse["recipients"] = []; + if (emailAction) { + const rows = await db + .select() + .from(alertEmailRecipients) + .where( + eq( + alertEmailRecipients.emailActionId, + emailAction.emailActionId + ) + ); + + recipients = rows.map((r) => ({ + recipientId: r.recipientId, + userId: r.userId ?? null, + roleId: r.roleId ?? null, + email: r.email ?? null + })); + } + + // Fetch webhook actions + const webhooks = await db + .select() + .from(alertWebhookActions) + .where(eq(alertWebhookActions.alertRuleId, alertRuleId)); + + return response(res, { + data: { + alertRuleId: rule.alertRuleId, + orgId: rule.orgId, + name: rule.name, + eventType: rule.eventType, + enabled: rule.enabled, + cooldownSeconds: rule.cooldownSeconds, + lastTriggeredAt: rule.lastTriggeredAt ?? null, + createdAt: rule.createdAt, + updatedAt: rule.updatedAt, + siteIds: siteRows.map((r) => r.siteId), + healthCheckIds: healthCheckRows.map((r) => r.healthCheckId), + resourceIds: resourceRows.map((r) => r.resourceId), + recipients, + webhookActions: webhooks.map((w) => { + let parsedConfig: WebhookAlertConfig | null = null; + if (w.config) { + try { + const serverSecret = + config.getRawConfig().server.secret!; + const decrypted = decrypt(w.config, serverSecret); + parsedConfig = JSON.parse( + decrypted + ) as WebhookAlertConfig; + } catch { + // best-effort – return null if decryption fails + } + } + return { + webhookActionId: w.webhookActionId, + webhookUrl: w.webhookUrl, + enabled: w.enabled, + lastSentAt: w.lastSentAt ?? null, + config: parsedConfig + }; + }) + }, + success: true, + error: false, + message: "Alert rule retrieved successfully", + status: HttpCode.OK + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} diff --git a/server/private/routers/alertRule/index.ts b/server/private/routers/alertRule/index.ts new file mode 100644 index 000000000..19e35f7dc --- /dev/null +++ b/server/private/routers/alertRule/index.ts @@ -0,0 +1,18 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +export * from "./createAlertRule"; +export * from "./updateAlertRule"; +export * from "./deleteAlertRule"; +export * from "./listAlertRules"; +export * from "./getAlertRule"; \ No newline at end of file diff --git a/server/private/routers/alertRule/listAlertRules.ts b/server/private/routers/alertRule/listAlertRules.ts new file mode 100644 index 000000000..73f11ca03 --- /dev/null +++ b/server/private/routers/alertRule/listAlertRules.ts @@ -0,0 +1,370 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db } from "@server/db"; +import { + alertRules, + alertSites, + alertHealthChecks, + alertResources +} from "@server/db"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { OpenAPITags, registry } from "@server/openApi"; +import { and, asc, desc, eq, inArray, like, or, sql } from "drizzle-orm"; + +const paramsSchema = z.strictObject({ + orgId: z.string().nonempty() +}); + +const querySchema = z.strictObject({ + limit: z + .string() + .optional() + .default("1000") + .transform(Number) + .pipe(z.number().int().nonnegative()), + offset: z + .string() + .optional() + .default("0") + .transform(Number) + .pipe(z.number().int().nonnegative()), + query: z.string().optional(), + siteId: z + .string() + .optional() + .transform((v) => (v !== undefined ? Number(v) : undefined)) + .pipe(z.number().int().positive().optional()), + resourceId: z + .string() + .optional() + .transform((v) => (v !== undefined ? Number(v) : undefined)) + .pipe(z.number().int().positive().optional()), + healthCheckId: z + .string() + .optional() + .transform((v) => (v !== undefined ? Number(v) : undefined)) + .pipe(z.number().int().positive().optional()), + sort_by: z.enum(["name", "last_triggered_at"]).optional(), + order: z.enum(["asc", "desc"]).optional().default("asc"), + enabled: z.enum(["true", "false"]).optional() +}); + +const SITE_ALERT_EVENT_TYPES = [ + "site_online", + "site_offline", + "site_toggle" +] as const; + +const RESOURCE_ALERT_EVENT_TYPES = [ + "resource_healthy", + "resource_unhealthy", + "resource_toggle" +] as const; + +const HEALTH_CHECK_ALERT_EVENT_TYPES = [ + "health_check_healthy", + "health_check_unhealthy", + "health_check_toggle" +] as const; + +export type ListAlertRulesResponse = { + alertRules: { + alertRuleId: number; + orgId: string; + name: string; + eventType: string; + enabled: boolean; + cooldownSeconds: number; + lastTriggeredAt: number | null; + createdAt: number; + updatedAt: number; + siteIds: number[]; + healthCheckIds: number[]; + resourceIds: number[]; + }[]; + pagination: { + total: number; + limit: number; + offset: number; + }; +}; + +registry.registerPath({ + method: "get", + path: "/org/{orgId}/alert-rules", + description: "List all alert rules for a specific organization.", + tags: [OpenAPITags.Org], + request: { + query: querySchema, + params: paramsSchema + }, + responses: {} +}); + +export async function listAlertRules( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = paramsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + const { orgId } = parsedParams.data; + + const parsedQuery = querySchema.safeParse(req.query); + if (!parsedQuery.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedQuery.error).toString() + ) + ); + } + const { + limit, + offset, + query, + siteId, + resourceId, + healthCheckId, + sort_by, + order, + enabled: enabledFilter + } = parsedQuery.data; + + const explicitSiteRuleIds: number[] = + siteId !== undefined + ? ( + await db + .select({ alertRuleId: alertSites.alertRuleId }) + .from(alertSites) + .where(eq(alertSites.siteId, siteId)) + ).map((r) => r.alertRuleId) + : []; + + const explicitResourceRuleIds: number[] = + resourceId !== undefined + ? ( + await db + .select({ + alertRuleId: alertResources.alertRuleId + }) + .from(alertResources) + .where(eq(alertResources.resourceId, resourceId)) + ).map((r) => r.alertRuleId) + : []; + + const explicitHealthCheckRuleIds: number[] = + healthCheckId !== undefined + ? ( + await db + .select({ + alertRuleId: alertHealthChecks.alertRuleId + }) + .from(alertHealthChecks) + .where( + eq(alertHealthChecks.healthCheckId, healthCheckId) + ) + ).map((r) => r.alertRuleId) + : []; + + const allSitesWildcardClause = and( + eq(alertRules.allSites, true), + inArray(alertRules.eventType, SITE_ALERT_EVENT_TYPES) + ); + + const siteScopeClause = + siteId !== undefined + ? explicitSiteRuleIds.length > 0 + ? or( + allSitesWildcardClause, + inArray(alertRules.alertRuleId, explicitSiteRuleIds) + ) + : allSitesWildcardClause + : undefined; + + const allResourcesWildcardClause = and( + eq(alertRules.allResources, true), + inArray(alertRules.eventType, RESOURCE_ALERT_EVENT_TYPES) + ); + + const resourceScopeClause = + resourceId !== undefined + ? explicitResourceRuleIds.length > 0 + ? or( + allResourcesWildcardClause, + inArray( + alertRules.alertRuleId, + explicitResourceRuleIds + ) + ) + : allResourcesWildcardClause + : undefined; + + const allHealthChecksWildcardClause = and( + eq(alertRules.allHealthChecks, true), + inArray(alertRules.eventType, HEALTH_CHECK_ALERT_EVENT_TYPES) + ); + + const healthCheckScopeClause = + healthCheckId !== undefined + ? explicitHealthCheckRuleIds.length > 0 + ? or( + allHealthChecksWildcardClause, + inArray( + alertRules.alertRuleId, + explicitHealthCheckRuleIds + ) + ) + : allHealthChecksWildcardClause + : undefined; + + const whereClause = and( + eq(alertRules.orgId, orgId), + query + ? like( + sql`LOWER(${alertRules.name})`, + `%${query.toLowerCase()}%` + ) + : undefined, + siteScopeClause, + resourceScopeClause, + healthCheckScopeClause, + enabledFilter !== undefined + ? eq(alertRules.enabled, enabledFilter === "true") + : undefined + ); + + const orderByClause = + sort_by === "name" + ? order === "asc" + ? asc(alertRules.name) + : desc(alertRules.name) + : sort_by === "last_triggered_at" + ? order === "asc" + ? sql`${alertRules.lastTriggeredAt} ASC NULLS FIRST` + : sql`${alertRules.lastTriggeredAt} DESC NULLS LAST` + : sql`${alertRules.createdAt} DESC`; + + const list = await db + .select() + .from(alertRules) + .where(whereClause) + .orderBy(orderByClause) + .limit(limit) + .offset(offset); + + const [{ count }] = await db + .select({ count: sql`count(*)` }) + .from(alertRules) + .where(whereClause); + + // Batch-fetch site and health-check associations for all returned rules + // in two queries rather than N+1 individual lookups. + const ruleIds = list.map((r) => r.alertRuleId); + + const siteRows = + ruleIds.length > 0 + ? await db + .select() + .from(alertSites) + .where(inArray(alertSites.alertRuleId, ruleIds)) + : []; + + const healthCheckRows = + ruleIds.length > 0 + ? await db + .select() + .from(alertHealthChecks) + .where(inArray(alertHealthChecks.alertRuleId, ruleIds)) + : []; + + const resourceRows = + ruleIds.length > 0 + ? await db + .select() + .from(alertResources) + .where(inArray(alertResources.alertRuleId, ruleIds)) + : []; + + // Index by alertRuleId for O(1) lookup when building the response + const sitesByRule = new Map(); + for (const row of siteRows) { + const existing = sitesByRule.get(row.alertRuleId) ?? []; + existing.push(row.siteId); + sitesByRule.set(row.alertRuleId, existing); + } + + const healthChecksByRule = new Map(); + for (const row of healthCheckRows) { + const existing = healthChecksByRule.get(row.alertRuleId) ?? []; + existing.push(row.healthCheckId); + healthChecksByRule.set(row.alertRuleId, existing); + } + + const resourcesByRule = new Map(); + for (const row of resourceRows) { + const existing = resourcesByRule.get(row.alertRuleId) ?? []; + existing.push(row.resourceId); + resourcesByRule.set(row.alertRuleId, existing); + } + + return response(res, { + data: { + alertRules: list.map((rule) => ({ + alertRuleId: rule.alertRuleId, + orgId: rule.orgId, + name: rule.name, + eventType: rule.eventType, + enabled: rule.enabled, + cooldownSeconds: rule.cooldownSeconds, + lastTriggeredAt: rule.lastTriggeredAt ?? null, + createdAt: rule.createdAt, + updatedAt: rule.updatedAt, + siteIds: sitesByRule.get(rule.alertRuleId) ?? [], + healthCheckIds: + healthChecksByRule.get(rule.alertRuleId) ?? [], + resourceIds: resourcesByRule.get(rule.alertRuleId) ?? [] + })), + pagination: { + total: count, + limit, + offset + } + }, + success: true, + error: false, + message: "Alert rules retrieved successfully", + status: HttpCode.OK + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} diff --git a/server/private/routers/alertRule/updateAlertRule.ts b/server/private/routers/alertRule/updateAlertRule.ts new file mode 100644 index 000000000..358661ac9 --- /dev/null +++ b/server/private/routers/alertRule/updateAlertRule.ts @@ -0,0 +1,403 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db } from "@server/db"; +import { + alertRules, + alertSites, + alertHealthChecks, + alertResources, + alertEmailActions, + alertEmailRecipients, + alertWebhookActions +} from "@server/db"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { OpenAPITags, registry } from "@server/openApi"; +import { and, eq } from "drizzle-orm"; +import { encrypt } from "@server/lib/crypto"; +import config from "@server/lib/config"; +import { HC_EVENT_TYPES, SITE_EVENT_TYPES, RESOURCE_EVENT_TYPES } from "./createAlertRule"; +import { invalidateAllRemoteExitNodeSessions } from "@server/private/auth/sessions/remoteExitNode"; + +const paramsSchema = z + .object({ + orgId: z.string().nonempty(), + alertRuleId: z.coerce.number() + }) + .strict(); + +const webhookActionSchema = z.strictObject({ + webhookUrl: z.string().url(), + config: z.string().optional(), + enabled: z.boolean().optional().default(true) +}); + +const bodySchema = z + .strictObject({ + // Alert rule fields - all optional for partial updates + name: z.string().nonempty().optional(), + eventType: z + .enum([ + ...HC_EVENT_TYPES, + ...SITE_EVENT_TYPES, + ...RESOURCE_EVENT_TYPES + ]) + .optional(), + enabled: z.boolean().optional(), + cooldownSeconds: z.number().int().nonnegative().optional(), + // Source join tables - if provided the full set is replaced + siteIds: z.array(z.number().int().positive()).optional(), + allSites: z.boolean().optional(), + healthCheckIds: z.array(z.number().int().positive()).optional(), + allHealthChecks: z.boolean().optional(), + resourceIds: z.array(z.number().int().positive()).optional(), + allResources: z.boolean().optional(), + // Recipient arrays - if any are provided the full recipient set is replaced + userIds: z.array(z.string().nonempty()).optional(), + roleIds: z.array(z.number()).optional(), + emails: z.array(z.string().email()).optional(), + // Webhook actions - if provided the full webhook set is replaced + webhookActions: z.array(webhookActionSchema).optional() + }) + .superRefine((val, ctx) => { + if (!val.eventType) return; + + const isSiteEvent = (SITE_EVENT_TYPES as readonly string[]).includes( + val.eventType + ); + const isHcEvent = (HC_EVENT_TYPES as readonly string[]).includes( + val.eventType + ); + const isResourceEvent = (RESOURCE_EVENT_TYPES as readonly string[]).includes( + val.eventType + ); + + if (isSiteEvent && val.siteIds !== undefined && val.siteIds.length === 0 && !val.allSites) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "At least one siteId is required for site event types when allSites is false", + path: ["siteIds"] + }); + } + + if (isHcEvent && val.healthCheckIds !== undefined && val.healthCheckIds.length === 0 && !val.allHealthChecks) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "At least one healthCheckId is required for health check event types when allHealthChecks is false", + path: ["healthCheckIds"] + }); + } + + if (isResourceEvent && val.resourceIds !== undefined && val.resourceIds.length === 0 && !val.allResources) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "At least one resourceId is required for resource event types when allResources is false", + path: ["resourceIds"] + }); + } + + if (isSiteEvent && val.healthCheckIds !== undefined && val.healthCheckIds.length > 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "healthCheckIds must not be set for site event types", + path: ["healthCheckIds"] + }); + } + + if (isHcEvent && val.siteIds !== undefined && val.siteIds.length > 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "siteIds must not be set for health check event types", + path: ["siteIds"] + }); + } + + if (isResourceEvent && val.siteIds !== undefined && val.siteIds.length > 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "siteIds must not be set for resource event types", + path: ["siteIds"] + }); + } + + if (isResourceEvent && val.healthCheckIds !== undefined && val.healthCheckIds.length > 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "healthCheckIds must not be set for resource event types", + path: ["healthCheckIds"] + }); + } + }); + +export type UpdateAlertRuleResponse = { + alertRuleId: number; +}; + +registry.registerPath({ + method: "post", + path: "/org/{orgId}/alert-rule/{alertRuleId}", + description: "Update an alert rule for a specific organization.", + tags: [OpenAPITags.Org], + request: { + params: paramsSchema, + body: { + content: { + "application/json": { + schema: bodySchema + } + } + } + }, + responses: {} +}); + +export async function updateAlertRule( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = paramsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + + const { orgId, alertRuleId } = parsedParams.data; + + const parsedBody = bodySchema.safeParse(req.body); + if (!parsedBody.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedBody.error).toString() + ) + ); + } + + const [existing] = await db + .select() + .from(alertRules) + .where( + and( + eq(alertRules.alertRuleId, alertRuleId), + eq(alertRules.orgId, orgId) + ) + ); + + if (!existing) { + return next( + createHttpError(HttpCode.NOT_FOUND, "Alert rule not found") + ); + } + + const { + name, + eventType, + enabled, + cooldownSeconds, + siteIds, + allSites, + healthCheckIds, + allHealthChecks, + resourceIds, + allResources, + userIds, + roleIds, + emails, + webhookActions + } = parsedBody.data; + + // --- Update rule fields --- + const updateData: Record = { + updatedAt: Date.now() + }; + + if (name !== undefined) updateData.name = name; + if (eventType !== undefined) updateData.eventType = eventType; + if (enabled !== undefined) updateData.enabled = enabled; + if (cooldownSeconds !== undefined) updateData.cooldownSeconds = cooldownSeconds; + if (allSites !== undefined) updateData.allSites = allSites; + if (allHealthChecks !== undefined) updateData.allHealthChecks = allHealthChecks; + if (allResources !== undefined) updateData.allResources = allResources; + + await db + .update(alertRules) + .set(updateData) + .where( + and( + eq(alertRules.alertRuleId, alertRuleId), + eq(alertRules.orgId, orgId) + ) + ); + + // --- Full-replace site associations if siteIds was provided --- + if (siteIds !== undefined || allSites !== undefined) { + await db + .delete(alertSites) + .where(eq(alertSites.alertRuleId, alertRuleId)); + + // Only insert junction rows when allSites is not true + const effectiveAllSites = allSites ?? false; + if (!effectiveAllSites && siteIds !== undefined && siteIds.length > 0) { + await db.insert(alertSites).values( + siteIds.map((siteId) => ({ + alertRuleId, + siteId + })) + ); + } + } + + // --- Full-replace health check associations if healthCheckIds was provided --- + if (healthCheckIds !== undefined || allHealthChecks !== undefined) { + await db + .delete(alertHealthChecks) + .where(eq(alertHealthChecks.alertRuleId, alertRuleId)); + + const effectiveAllHealthChecks = allHealthChecks ?? false; + if (!effectiveAllHealthChecks && healthCheckIds !== undefined && healthCheckIds.length > 0) { + await db.insert(alertHealthChecks).values( + healthCheckIds.map((healthCheckId) => ({ + alertRuleId, + healthCheckId + })) + ); + } + } + + // --- Full-replace resource associations if resourceIds was provided --- + if (resourceIds !== undefined || allResources !== undefined) { + await db + .delete(alertResources) + .where(eq(alertResources.alertRuleId, alertRuleId)); + + const effectiveAllResources = allResources ?? false; + if (!effectiveAllResources && resourceIds !== undefined && resourceIds.length > 0) { + await db.insert(alertResources).values( + resourceIds.map((resourceId) => ({ + alertRuleId, + resourceId + })) + ); + } + } + + // --- Full-replace recipients if any recipient array was provided --- + const recipientsProvided = + userIds !== undefined || + roleIds !== undefined || + emails !== undefined; + + if (recipientsProvided) { + const newRecipients = [ + ...(userIds ?? []).map((userId) => ({ + userId, + roleId: null as number | null, + email: null as string | null + })), + ...(roleIds ?? []).map((roleId) => ({ + userId: null as string | null, + roleId, + email: null as string | null + })), + ...(emails ?? []).map((email) => ({ + userId: null as string | null, + roleId: null as number | null, + email + })) + ]; + + const [existingEmailAction] = await db + .select() + .from(alertEmailActions) + .where(eq(alertEmailActions.alertRuleId, alertRuleId)); + + if (existingEmailAction) { + await db + .delete(alertEmailRecipients) + .where( + eq( + alertEmailRecipients.emailActionId, + existingEmailAction.emailActionId + ) + ); + + if (newRecipients.length > 0) { + await db.insert(alertEmailRecipients).values( + newRecipients.map((r) => ({ + emailActionId: existingEmailAction.emailActionId, + ...r + })) + ); + } + } else if (newRecipients.length > 0) { + const [emailActionRow] = await db + .insert(alertEmailActions) + .values({ alertRuleId, enabled: true }) + .returning(); + + await db.insert(alertEmailRecipients).values( + newRecipients.map((r) => ({ + emailActionId: emailActionRow.emailActionId, + ...r + })) + ); + } + } + + // --- Full-replace webhook actions if the array was provided --- + if (webhookActions !== undefined) { + await db + .delete(alertWebhookActions) + .where(eq(alertWebhookActions.alertRuleId, alertRuleId)); + + if (webhookActions.length > 0) { + const serverSecret = config.getRawConfig().server.secret!; + await db.insert(alertWebhookActions).values( + webhookActions.map((wa) => ({ + alertRuleId, + webhookUrl: wa.webhookUrl, + config: wa.config != null ? encrypt(wa.config, serverSecret) : null, + enabled: wa.enabled + })) + ); + } + } + + return response(res, { + data: { + alertRuleId + }, + success: true, + error: false, + message: "Alert rule updated successfully", + status: HttpCode.OK + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} diff --git a/server/private/routers/billing/hooks/handleCustomerCreated.ts b/server/private/routers/billing/hooks/handleCustomerCreated.ts index 11405f392..66ad3a4fa 100644 --- a/server/private/routers/billing/hooks/handleCustomerCreated.ts +++ b/server/private/routers/billing/hooks/handleCustomerCreated.ts @@ -12,9 +12,10 @@ */ import Stripe from "stripe"; -import { customers, db } from "@server/db"; +import { customers, db, subscriptions } from "@server/db"; import { eq } from "drizzle-orm"; import logger from "@server/logger"; +import { generateId } from "@server/auth/sessions/app"; export async function handleCustomerCreated( customer: Stripe.Customer @@ -38,14 +39,31 @@ export async function handleCustomerCreated( return; } - await db.insert(customers).values({ - customerId: customer.id, - orgId: customer.metadata.orgId, - email: customer.email || null, - name: customer.name || null, - createdAt: customer.created, - updatedAt: customer.created + await db.transaction(async (trx) => { + await trx.insert(customers).values({ + customerId: customer.id, + orgId: customer.metadata.orgId, + email: customer.email || null, + name: customer.name || null, + createdAt: customer.created, + updatedAt: customer.created + }); + + // Insert a 14-day trial subscription at tier3 + const now = Math.floor(Date.now() / 1000); + const trialExpiresAt = now + 10 * 24 * 60 * 60; + const subscriptionId = `trial-${generateId(15)}`; + await trx.insert(subscriptions).values({ + subscriptionId, + customerId: customer.id, + status: "active", + type: "tier3", + createdAt: now, + expiresAt: trialExpiresAt, + trial: true + }); }); + logger.info(`Customer with ID ${customer.id} created successfully.`); } catch (error) { logger.error( diff --git a/server/private/routers/external.ts b/server/private/routers/external.ts index 7872da700..159ee2449 100644 --- a/server/private/routers/external.ts +++ b/server/private/routers/external.ts @@ -29,6 +29,8 @@ import * as ssh from "#private/routers/ssh"; import * as user from "#private/routers/user"; import * as siteProvisioning from "#private/routers/siteProvisioning"; import * as eventStreamingDestination from "#private/routers/eventStreamingDestination"; +import * as alertRule from "#private/routers/alertRule"; +import * as healthChecks from "#private/routers/healthChecks"; import { verifyOrgAccess, @@ -681,7 +683,96 @@ authenticated.delete( authenticated.get( "/org/:orgId/event-streaming-destinations", + verifyValidLicense, verifyOrgAccess, verifyUserHasAction(ActionsEnum.listEventStreamingDestinations), eventStreamingDestination.listEventStreamingDestinations ); + +authenticated.put( + "/org/:orgId/alert-rule", + verifyValidLicense, + verifyOrgAccess, + verifyLimits, + verifyUserHasAction(ActionsEnum.createAlertRule), + logActionAudit(ActionsEnum.createAlertRule), + alertRule.createAlertRule +); + +authenticated.post( + "/org/:orgId/alert-rule/:alertRuleId", + verifyValidLicense, + verifyOrgAccess, + verifyUserHasAction(ActionsEnum.updateAlertRule), + logActionAudit(ActionsEnum.updateAlertRule), + alertRule.updateAlertRule +); + +authenticated.delete( + "/org/:orgId/alert-rule/:alertRuleId", + verifyValidLicense, + verifyOrgAccess, + verifyUserHasAction(ActionsEnum.deleteAlertRule), + logActionAudit(ActionsEnum.deleteAlertRule), + alertRule.deleteAlertRule +); + +authenticated.get( + "/org/:orgId/alert-rules", + verifyValidLicense, + verifyOrgAccess, + verifyUserHasAction(ActionsEnum.listAlertRules), + alertRule.listAlertRules +); + +authenticated.get( + "/org/:orgId/alert-rule/:alertRuleId", + verifyValidLicense, + verifyOrgAccess, + verifyUserHasAction(ActionsEnum.getAlertRule), + alertRule.getAlertRule +); + +authenticated.get( + "/org/:orgId/health-checks", + verifyValidLicense, + verifyOrgAccess, + verifyUserHasAction(ActionsEnum.listHealthChecks), + healthChecks.listHealthChecks +); + +authenticated.put( + "/org/:orgId/health-check", + verifyValidLicense, + verifyOrgAccess, + verifyLimits, + verifyUserHasAction(ActionsEnum.createHealthCheck), + logActionAudit(ActionsEnum.createHealthCheck), + healthChecks.createHealthCheck +); + +authenticated.post( + "/org/:orgId/health-check/:healthCheckId", + verifyValidLicense, + verifyOrgAccess, + verifyUserHasAction(ActionsEnum.updateHealthCheck), + logActionAudit(ActionsEnum.updateHealthCheck), + healthChecks.updateHealthCheck +); + +authenticated.delete( + "/org/:orgId/health-check/:healthCheckId", + verifyValidLicense, + verifyOrgAccess, + verifyUserHasAction(ActionsEnum.deleteHealthCheck), + logActionAudit(ActionsEnum.deleteHealthCheck), + healthChecks.deleteHealthCheck +); + +authenticated.get( + "/org/:orgId/health-check/:healthCheckId/status-history", + verifyValidLicense, + verifyOrgAccess, + verifyUserHasAction(ActionsEnum.getTarget), + healthChecks.getHealthCheckStatusHistory +); diff --git a/server/private/routers/healthChecks/createHealthCheck.ts b/server/private/routers/healthChecks/createHealthCheck.ts new file mode 100644 index 000000000..374ec4ba4 --- /dev/null +++ b/server/private/routers/healthChecks/createHealthCheck.ts @@ -0,0 +1,188 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db, targetHealthCheck, newts, sites } from "@server/db"; +import { eq } from "drizzle-orm"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { OpenAPITags, registry } from "@server/openApi"; +import { addStandaloneHealthCheck } from "@server/routers/newt/targets"; + +const paramsSchema = z.strictObject({ + orgId: z.string().nonempty() +}); + +const bodySchema = z.strictObject({ + name: z.string().nonempty(), + siteId: z.number().int().positive(), + hcEnabled: z.boolean().default(false), + hcMode: z.string().default("http"), + hcHostname: z.string().optional(), + hcPort: z.number().int().min(1).max(65535).optional(), + hcPath: z.string().optional(), + hcScheme: z.string().optional(), + hcMethod: z.string().default("GET"), + hcInterval: z.number().int().positive().default(30), + hcUnhealthyInterval: z.number().int().positive().default(30), + hcTimeout: z.number().int().positive().default(1), + hcHeaders: z.string().optional().nullable(), + hcFollowRedirects: z.boolean().default(true), + hcStatus: z.number().int().optional().nullable(), + hcTlsServerName: z.string().optional(), + hcHealthyThreshold: z.number().int().positive().default(1), + hcUnhealthyThreshold: z.number().int().positive().default(1) +}); + +export type CreateHealthCheckResponse = { + targetHealthCheckId: number; +}; + +registry.registerPath({ + method: "put", + path: "/org/{orgId}/health-check", + description: "Create a health check for a specific organization.", + tags: [OpenAPITags.Org], + request: { + params: paramsSchema, + body: { + content: { + "application/json": { + schema: bodySchema + } + } + } + }, + responses: {} +}); + +export async function createHealthCheck( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = paramsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + + const { orgId } = parsedParams.data; + + const parsedBody = bodySchema.safeParse(req.body); + if (!parsedBody.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedBody.error).toString() + ) + ); + } + + const { + name, + siteId, + hcEnabled, + hcMode, + hcHostname, + hcPort, + hcPath, + hcScheme, + hcMethod, + hcInterval, + hcUnhealthyInterval, + hcTimeout, + hcHeaders, + hcFollowRedirects, + hcStatus, + hcTlsServerName, + hcHealthyThreshold, + hcUnhealthyThreshold + } = parsedBody.data; + + const [record] = await db + .insert(targetHealthCheck) + .values({ + targetId: null, + orgId, + siteId, + name, + hcEnabled, + hcMode, + hcHostname: hcHostname ?? null, + hcPort: hcPort ?? null, + hcPath: hcPath ?? null, + hcScheme: hcScheme ?? null, + hcMethod, + hcInterval, + hcUnhealthyInterval, + hcTimeout, + hcHeaders: hcHeaders ?? null, + hcFollowRedirects, + hcStatus: hcStatus ?? null, + hcTlsServerName: hcTlsServerName ?? null, + hcHealthyThreshold, + hcUnhealthyThreshold + }) + .returning(); + + // Push health check to newt if the site is a newt site + if (siteId) { + const [site] = await db + .select() + .from(sites) + .where(eq(sites.siteId, siteId)) + .limit(1); + + if (site && site.type === "newt") { + const [newt] = await db + .select() + .from(newts) + .where(eq(newts.siteId, site.siteId)) + .limit(1); + + if (newt) { + await addStandaloneHealthCheck( + newt.newtId, + record, + newt.version + ); + } + } + } + + return response(res, { + data: { + targetHealthCheckId: record.targetHealthCheckId + }, + success: true, + error: false, + message: "Standalone health check created successfully", + status: HttpCode.CREATED + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} diff --git a/server/private/routers/healthChecks/deleteHealthCheck.ts b/server/private/routers/healthChecks/deleteHealthCheck.ts new file mode 100644 index 000000000..530653aab --- /dev/null +++ b/server/private/routers/healthChecks/deleteHealthCheck.ts @@ -0,0 +1,123 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db, targetHealthCheck, newts, sites } from "@server/db"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { OpenAPITags, registry } from "@server/openApi"; +import { and, eq, isNull } from "drizzle-orm"; +import { removeStandaloneHealthCheck } from "@server/routers/newt/targets"; + +const paramsSchema = z + .object({ + orgId: z.string().nonempty(), + healthCheckId: z + .string() + .transform(Number) + .pipe(z.number().int().positive()) + }) + .strict(); + +registry.registerPath({ + method: "delete", + path: "/org/{orgId}/health-check/{healthCheckId}", + description: "Delete a health check for a specific organization.", + tags: [OpenAPITags.Org], + request: { + params: paramsSchema + }, + responses: {} +}); + +export async function deleteHealthCheck( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = paramsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + + const { orgId, healthCheckId } = parsedParams.data; + + const [existing] = await db + .select() + .from(targetHealthCheck) + .where( + and( + eq(targetHealthCheck.targetHealthCheckId, healthCheckId), + eq(targetHealthCheck.orgId, orgId), + isNull(targetHealthCheck.targetId) + ) + ); + + if (!existing) { + return next( + createHttpError( + HttpCode.NOT_FOUND, + "Standalone health check not found" + ) + ); + } + + await db + .delete(targetHealthCheck) + .where( + and( + eq(targetHealthCheck.targetHealthCheckId, healthCheckId), + eq(targetHealthCheck.orgId, orgId), + isNull(targetHealthCheck.targetId) + ) + ); + + // Remove health check from newt if the site is a newt site + const [newt] = await db + .select() + .from(newts) + .where(eq(newts.siteId, existing.siteId)) + .limit(1); + + if (newt) { + await removeStandaloneHealthCheck( + newt.newtId, + healthCheckId, + newt.version + ); + } + + return response(res, { + data: null, + success: true, + error: false, + message: "Standalone health check deleted successfully", + status: HttpCode.OK + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} diff --git a/server/private/routers/healthChecks/getStatusHistory.ts b/server/private/routers/healthChecks/getStatusHistory.ts new file mode 100644 index 000000000..2fa596950 --- /dev/null +++ b/server/private/routers/healthChecks/getStatusHistory.ts @@ -0,0 +1,106 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db, statusHistory } from "@server/db"; +import { and, eq, gte, asc } from "drizzle-orm"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { + computeBuckets, + statusHistoryQuerySchema, + StatusHistoryResponse +} from "@server/lib/statusHistory"; + +const healthCheckParamsSchema = z.object({ + healthCheckId: z.string().transform((v) => parseInt(v, 10)) +}); + +export async function getHealthCheckStatusHistory( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = healthCheckParamsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + const parsedQuery = statusHistoryQuerySchema.safeParse(req.query); + if (!parsedQuery.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedQuery.error).toString() + ) + ); + } + + const entityType = "healthCheck"; + const entityId = parsedParams.data.healthCheckId; + const { days } = parsedQuery.data; + + const nowSec = Math.floor(Date.now() / 1000); + const startSec = nowSec - days * 86400; + + const events = await db + .select() + .from(statusHistory) + .where( + and( + eq(statusHistory.entityType, entityType), + eq(statusHistory.entityId, entityId), + gte(statusHistory.timestamp, startSec) + ) + ) + .orderBy(asc(statusHistory.timestamp)); + + const { buckets, totalDowntime } = computeBuckets(events, days); + const totalWindow = days * 86400; + const overallUptime = + totalWindow > 0 + ? Math.max( + 0, + ((totalWindow - totalDowntime) / totalWindow) * 100 + ) + : 100; + + return response(res, { + data: { + entityType, + entityId, + days: buckets, + overallUptimePercent: Math.round(overallUptime * 100) / 100, + totalDowntimeSeconds: totalDowntime + }, + success: true, + error: false, + message: "Status history retrieved successfully", + status: HttpCode.OK + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} diff --git a/server/private/routers/healthChecks/index.ts b/server/private/routers/healthChecks/index.ts new file mode 100644 index 000000000..665ae5cca --- /dev/null +++ b/server/private/routers/healthChecks/index.ts @@ -0,0 +1,18 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +export * from "./listHealthChecks"; +export * from "./createHealthCheck"; +export * from "./updateHealthCheck"; +export * from "./deleteHealthCheck"; +export * from "./getStatusHistory"; diff --git a/server/private/routers/healthChecks/listHealthChecks.ts b/server/private/routers/healthChecks/listHealthChecks.ts new file mode 100644 index 000000000..26cb75e9c --- /dev/null +++ b/server/private/routers/healthChecks/listHealthChecks.ts @@ -0,0 +1,234 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { db, targetHealthCheck, targets, resources, sites } from "@server/db"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { OpenAPITags, registry } from "@server/openApi"; +import { and, eq, exists, isNotNull, like, sql } from "drizzle-orm"; +import { NextFunction, Request, Response } from "express"; +import { z } from "zod"; +import { fromError } from "zod-validation-error"; +import { ListHealthChecksResponse } from "@server/routers/healthChecks/types"; + +const paramsSchema = z.strictObject({ + orgId: z.string().nonempty() +}); + +const querySchema = z.object({ + limit: z + .string() + .optional() + .default("1000") + .transform(Number) + .pipe(z.int().positive()), + offset: z + .string() + .optional() + .default("0") + .transform(Number) + .pipe(z.int().nonnegative()), + query: z.string().optional(), + hcMode: z.enum(["http", "tcp", "snmp", "ping"]).optional(), + siteId: z + .string() + .optional() + .transform((s) => (s == null || s === "" ? undefined : Number(s))) + .pipe(z.union([z.undefined(), z.number().int().positive()])), + resourceId: z + .string() + .optional() + .transform((s) => (s == null || s === "" ? undefined : Number(s))) + .pipe(z.union([z.undefined(), z.number().int().positive()])), + hcHealth: z.enum(["healthy", "unhealthy", "unknown"]).optional(), + hcEnabled: z + .enum(["true", "false"]) + .optional() + .transform((v) => (v === undefined ? undefined : v === "true")) +}); + +registry.registerPath({ + method: "get", + path: "/org/{orgId}/health-checks", + description: "List health checks for an organization.", + tags: [OpenAPITags.Org], + request: { + params: paramsSchema, + query: querySchema + }, + responses: {} +}); + +export async function listHealthChecks( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = paramsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + const { orgId } = parsedParams.data; + + const parsedQuery = querySchema.safeParse(req.query); + if (!parsedQuery.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedQuery.error).toString() + ) + ); + } + const { + limit, + offset, + query, + hcMode, + siteId, + resourceId, + hcHealth, + hcEnabled + } = parsedQuery.data; + + const resourceIdFilter = resourceId + ? exists( + db + .select() + .from(targets) + .where( + and( + eq(targets.targetId, targetHealthCheck.targetId), + eq(targets.resourceId, resourceId) + ) + ) + ) + : undefined; + + const whereClause = and( + eq(targetHealthCheck.orgId, orgId), + isNotNull(targetHealthCheck.hcMode), // filter out the null ones attached to targets + query + ? like( + sql`LOWER(${targetHealthCheck.name})`, + `%${query.toLowerCase()}%` + ) + : undefined, + hcMode ? eq(targetHealthCheck.hcMode, hcMode) : undefined, + siteId ? eq(targetHealthCheck.siteId, siteId) : undefined, + resourceIdFilter, + hcHealth ? eq(targetHealthCheck.hcHealth, hcHealth) : undefined, + hcEnabled !== undefined + ? eq(targetHealthCheck.hcEnabled, hcEnabled) + : undefined + ); + + const list = await db + .select({ + targetHealthCheckId: targetHealthCheck.targetHealthCheckId, + name: targetHealthCheck.name, + siteId: targetHealthCheck.siteId, + siteName: sites.name, + siteNiceId: sites.niceId, + hcEnabled: targetHealthCheck.hcEnabled, + hcHealth: targetHealthCheck.hcHealth, + hcMode: targetHealthCheck.hcMode, + hcHostname: targetHealthCheck.hcHostname, + hcPort: targetHealthCheck.hcPort, + hcPath: targetHealthCheck.hcPath, + hcScheme: targetHealthCheck.hcScheme, + hcMethod: targetHealthCheck.hcMethod, + hcInterval: targetHealthCheck.hcInterval, + hcUnhealthyInterval: targetHealthCheck.hcUnhealthyInterval, + hcTimeout: targetHealthCheck.hcTimeout, + hcHeaders: targetHealthCheck.hcHeaders, + hcFollowRedirects: targetHealthCheck.hcFollowRedirects, + hcStatus: targetHealthCheck.hcStatus, + hcTlsServerName: targetHealthCheck.hcTlsServerName, + hcHealthyThreshold: targetHealthCheck.hcHealthyThreshold, + hcUnhealthyThreshold: targetHealthCheck.hcUnhealthyThreshold, + resourceId: resources.resourceId, + resourceName: resources.name, + resourceNiceId: resources.niceId + }) + .from(targetHealthCheck) + .leftJoin(targets, eq(targetHealthCheck.targetId, targets.targetId)) + .leftJoin(resources, eq(targets.resourceId, resources.resourceId)) + .leftJoin(sites, eq(targetHealthCheck.siteId, sites.siteId)) + .where(whereClause) + .orderBy(sql`${targetHealthCheck.targetHealthCheckId} DESC`) + .limit(limit) + .offset(offset); + + const [{ count }] = await db + .select({ count: sql`count(*)` }) + .from(targetHealthCheck) + .where(whereClause); + + return response(res, { + data: { + healthChecks: list.map((row) => ({ + targetHealthCheckId: row.targetHealthCheckId, + name: row.name ?? "", + siteId: row.siteId ?? null, + siteName: row.siteName ?? null, + siteNiceId: row.siteNiceId ?? null, + hcEnabled: row.hcEnabled, + hcHealth: (row.hcHealth ?? "unknown") as + | "unknown" + | "healthy" + | "unhealthy", + hcMode: row.hcMode ?? null, + hcHostname: row.hcHostname ?? null, + hcPort: row.hcPort ?? null, + hcPath: row.hcPath ?? null, + hcScheme: row.hcScheme ?? null, + hcMethod: row.hcMethod ?? null, + hcInterval: row.hcInterval ?? null, + hcUnhealthyInterval: row.hcUnhealthyInterval ?? null, + hcTimeout: row.hcTimeout ?? null, + hcHeaders: row.hcHeaders ?? null, + hcFollowRedirects: row.hcFollowRedirects ?? null, + hcStatus: row.hcStatus ?? null, + hcTlsServerName: row.hcTlsServerName ?? null, + hcHealthyThreshold: row.hcHealthyThreshold ?? null, + hcUnhealthyThreshold: row.hcUnhealthyThreshold ?? null, + resourceId: row.resourceId ?? null, + resourceName: row.resourceName ?? null, + resourceNiceId: row.resourceNiceId ?? null + })), + pagination: { + total: count, + limit, + offset + } + }, + success: true, + error: false, + message: "Standalone health checks retrieved successfully", + status: HttpCode.OK + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} diff --git a/server/private/routers/healthChecks/updateHealthCheck.ts b/server/private/routers/healthChecks/updateHealthCheck.ts new file mode 100644 index 000000000..713bf1e03 --- /dev/null +++ b/server/private/routers/healthChecks/updateHealthCheck.ts @@ -0,0 +1,250 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db, targetHealthCheck, newts, sites } from "@server/db"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { OpenAPITags, registry } from "@server/openApi"; +import { and, eq, isNull } from "drizzle-orm"; +import { addStandaloneHealthCheck } from "@server/routers/newt/targets"; + +const paramsSchema = z + .object({ + orgId: z.string().nonempty(), + healthCheckId: z + .string() + .transform(Number) + .pipe(z.number().int().positive()) + }) + .strict(); + +const bodySchema = z.strictObject({ + name: z.string().nonempty().optional(), + siteId: z.number().int().positive().optional(), + hcEnabled: z.boolean().optional(), + hcMode: z.string().optional(), + hcHostname: z.string().optional(), + hcPort: z.number().int().min(1).max(65535).optional(), + hcPath: z.string().optional(), + hcScheme: z.string().optional(), + hcMethod: z.string().optional(), + hcInterval: z.number().int().positive().optional(), + hcUnhealthyInterval: z.number().int().positive().optional(), + hcTimeout: z.number().int().positive().optional(), + hcHeaders: z.string().optional().nullable(), + hcFollowRedirects: z.boolean().optional(), + hcStatus: z.number().int().optional().nullable(), + hcTlsServerName: z.string().optional(), + hcHealthyThreshold: z.number().int().positive().optional(), + hcUnhealthyThreshold: z.number().int().positive().optional() +}); + +export type UpdateHealthCheckResponse = { + targetHealthCheckId: number; + name: string | null; + siteId: number | null; + hcEnabled: boolean; + hcHealth: string | null; + hcMode: string | null; + hcHostname: string | null; + hcPort: number | null; + hcPath: string | null; + hcScheme: string | null; + hcMethod: string | null; + hcInterval: number | null; + hcUnhealthyInterval: number | null; + hcTimeout: number | null; + hcHeaders: string | null; + hcFollowRedirects: boolean | null; + hcStatus: number | null; + hcTlsServerName: string | null; + hcHealthyThreshold: number | null; + hcUnhealthyThreshold: number | null; +}; + +registry.registerPath({ + method: "post", + path: "/org/{orgId}/health-check/{healthCheckId}", + description: "Update a health check for a specific organization.", + tags: [OpenAPITags.Org], + request: { + params: paramsSchema, + body: { + content: { + "application/json": { + schema: bodySchema + } + } + } + }, + responses: {} +}); + +export async function updateHealthCheck( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = paramsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + + const { orgId, healthCheckId } = parsedParams.data; + + const parsedBody = bodySchema.safeParse(req.body); + if (!parsedBody.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedBody.error).toString() + ) + ); + } + + const [existing] = await db + .select() + .from(targetHealthCheck) + .where( + and( + eq(targetHealthCheck.targetHealthCheckId, healthCheckId), + eq(targetHealthCheck.orgId, orgId), + isNull(targetHealthCheck.targetId) + ) + ); + + if (!existing) { + return next( + createHttpError( + HttpCode.NOT_FOUND, + "Standalone health check not found" + ) + ); + } + + const { + name, + siteId, + hcEnabled, + hcMode, + hcHostname, + hcPort, + hcPath, + hcScheme, + hcMethod, + hcInterval, + hcUnhealthyInterval, + hcTimeout, + hcHeaders, + hcFollowRedirects, + hcStatus, + hcTlsServerName, + hcHealthyThreshold, + hcUnhealthyThreshold + } = parsedBody.data; + + const updateData: Record = {}; + + if (name !== undefined) updateData.name = name; + if (siteId !== undefined) updateData.siteId = siteId; + if (hcEnabled !== undefined) updateData.hcEnabled = hcEnabled; + if (hcMode !== undefined) updateData.hcMode = hcMode; + if (hcHostname !== undefined) updateData.hcHostname = hcHostname; + if (hcPort !== undefined) updateData.hcPort = hcPort; + if (hcPath !== undefined) updateData.hcPath = hcPath; + if (hcScheme !== undefined) updateData.hcScheme = hcScheme; + if (hcMethod !== undefined) updateData.hcMethod = hcMethod; + if (hcInterval !== undefined) updateData.hcInterval = hcInterval; + if (hcUnhealthyInterval !== undefined) + updateData.hcUnhealthyInterval = hcUnhealthyInterval; + if (hcTimeout !== undefined) updateData.hcTimeout = hcTimeout; + if (hcHeaders !== undefined) updateData.hcHeaders = hcHeaders; + if (hcFollowRedirects !== undefined) + updateData.hcFollowRedirects = hcFollowRedirects; + if (hcStatus !== undefined) updateData.hcStatus = hcStatus; + if (hcTlsServerName !== undefined) + updateData.hcTlsServerName = hcTlsServerName; + if (hcHealthyThreshold !== undefined) + updateData.hcHealthyThreshold = hcHealthyThreshold; + if (hcUnhealthyThreshold !== undefined) + updateData.hcUnhealthyThreshold = hcUnhealthyThreshold; + + const [updated] = await db + .update(targetHealthCheck) + .set(updateData) + .where( + and( + eq(targetHealthCheck.targetHealthCheckId, healthCheckId), + eq(targetHealthCheck.orgId, orgId), + isNull(targetHealthCheck.targetId) + ) + ) + .returning(); + + // Push updated health check to newt if the site is a newt site + const [newt] = await db + .select() + .from(newts) + .where(eq(newts.siteId, updated.siteId)) + .limit(1); + + if (newt) { + await addStandaloneHealthCheck(newt.newtId, updated, newt.version); + } + + return response(res, { + data: { + targetHealthCheckId: updated.targetHealthCheckId, + siteId: updated.siteId ?? null, + name: updated.name ?? null, + hcEnabled: updated.hcEnabled, + hcHealth: updated.hcHealth ?? null, + hcMode: updated.hcMode ?? null, + hcHostname: updated.hcHostname ?? null, + hcPort: updated.hcPort ?? null, + hcPath: updated.hcPath ?? null, + hcScheme: updated.hcScheme ?? null, + hcMethod: updated.hcMethod ?? null, + hcInterval: updated.hcInterval ?? null, + hcUnhealthyInterval: updated.hcUnhealthyInterval ?? null, + hcTimeout: updated.hcTimeout ?? null, + hcHeaders: updated.hcHeaders ?? null, + hcFollowRedirects: updated.hcFollowRedirects ?? null, + hcStatus: updated.hcStatus ?? null, + hcTlsServerName: updated.hcTlsServerName ?? null, + hcHealthyThreshold: updated.hcHealthyThreshold ?? null, + hcUnhealthyThreshold: updated.hcUnhealthyThreshold ?? null + }, + success: true, + error: false, + message: "Standalone health check updated successfully", + status: HttpCode.OK + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} diff --git a/server/private/routers/hybrid.ts b/server/private/routers/hybrid.ts index f689df0a5..b3ef792d9 100644 --- a/server/private/routers/hybrid.ts +++ b/server/private/routers/hybrid.ts @@ -24,14 +24,8 @@ import { User, certificates, exitNodeOrgs, - RemoteExitNode, - olms, - newts, - clients, - sites, domains, orgDomains, - targets, loginPage, loginPageOrg, LoginPage, @@ -70,12 +64,9 @@ import { updateAndGenerateEndpointDestinations, updateSiteBandwidth } from "@server/routers/gerbil"; -import * as gerbil from "@server/routers/gerbil"; import logger from "@server/logger"; -import { decryptData } from "@server/lib/encryption"; +import { decrypt } from "@server/lib/crypto"; import config from "@server/lib/config"; -import privateConfig from "#private/lib/config"; -import * as fs from "fs"; import { exchangeSession } from "@server/routers/badger"; import { validateResourceSessionToken } from "@server/auth/sessions/resource"; import { checkExitNodeOrg, resolveExitNodes } from "#private/lib/exitNodes"; @@ -298,25 +289,11 @@ hybridRouter.get( } ); -let encryptionKeyHex = ""; -let encryptionKey: Buffer; -function loadEncryptData() { - if (encryptionKey) { - return; // already loaded - } - - encryptionKeyHex = - privateConfig.getRawPrivateConfig().server.encryption_key; - encryptionKey = Buffer.from(encryptionKeyHex, "hex"); -} - // Get valid certificates for given domains (supports wildcard certs) hybridRouter.get( "/certificates/domains", async (req: Request, res: Response, next: NextFunction) => { try { - loadEncryptData(); // Ensure encryption key is loaded - const parsed = getCertificatesByDomainsQuerySchema.safeParse( req.query ); @@ -447,13 +424,13 @@ hybridRouter.get( const result = filtered.map((cert) => { // Decrypt and save certificate file - const decryptedCert = decryptData( + const decryptedCert = decrypt( cert.certFile!, // is not null from query - encryptionKey + config.getRawConfig().server.secret! ); // Decrypt and save key file - const decryptedKey = decryptData(cert.keyFile!, encryptionKey); + const decryptedKey = decrypt(cert.keyFile!, config.getRawConfig().server.secret!); // Return only the certificate data without org information return { @@ -833,9 +810,12 @@ hybridRouter.get( ) ); - logger.debug(`User ${userId} has roles in org ${orgId}:`, userOrgRoleRows); + logger.debug( + `User ${userId} has roles in org ${orgId}:`, + userOrgRoleRows + ); - return response<{ roleId: number, roleName: string }[]>(res, { + return response<{ roleId: number; roleName: string }[]>(res, { data: userOrgRoleRows, success: true, error: false, diff --git a/server/private/routers/integration.ts b/server/private/routers/integration.ts index 8c1ce4d46..ed97b3751 100644 --- a/server/private/routers/integration.ts +++ b/server/private/routers/integration.ts @@ -14,6 +14,7 @@ import * as orgIdp from "#private/routers/orgIdp"; import * as org from "#private/routers/org"; import * as logs from "#private/routers/auditLogs"; +import * as alertEvents from "#private/routers/alertEvents"; import { verifyApiKeyHasAction, @@ -40,6 +41,27 @@ import { tierMatrix } from "@server/lib/billing/tierMatrix"; export const unauthenticated = ua; export const authenticated = a; +authenticated.post( + "/org/:orgId/site/:siteId/trigger-alert", + verifyApiKeyIsRoot, + verifyApiKeyHasAction(ActionsEnum.triggerSiteAlert), + alertEvents.triggerSiteAlert +); + +authenticated.post( + "/org/:orgId/resource/:resourceId/trigger-alert", + verifyApiKeyIsRoot, + verifyApiKeyHasAction(ActionsEnum.triggerResourceAlert), + alertEvents.triggerResourceAlert +); + +authenticated.post( + "/org/:orgId/health-check/:healthCheckId/trigger-alert", + verifyApiKeyIsRoot, + verifyApiKeyHasAction(ActionsEnum.triggerHealthCheckAlert), + alertEvents.triggerHealthCheckAlert +); + authenticated.post( `/org/:orgId/send-usage-notification`, verifyApiKeyIsRoot, // We are the only ones who can use root key so its fine @@ -48,6 +70,14 @@ authenticated.post( org.sendUsageNotification ); +authenticated.post( + `/org/:orgId/send-trial-notification`, + verifyApiKeyIsRoot, + verifyApiKeyHasAction(ActionsEnum.sendTrialNotification), + logActionAudit(ActionsEnum.sendTrialNotification), + org.sendTrialNotification +); + authenticated.delete( "/idp/:idpId", verifyApiKeyIsRoot, diff --git a/server/private/routers/newt/handleConnectionLogMessage.ts b/server/private/routers/newt/handleConnectionLogMessage.ts index fb6ab3453..6355eb783 100644 --- a/server/private/routers/newt/handleConnectionLogMessage.ts +++ b/server/private/routers/newt/handleConnectionLogMessage.ts @@ -92,9 +92,14 @@ export const handleConnectionLogMessage: MessageHandler = async (context) => { return; } - // Look up the org for this site + // Look up the org for this site and check retention settings const [site] = await db - .select({ orgId: sites.orgId, orgSubnet: orgs.subnet }) + .select({ + orgId: sites.orgId, + orgSubnet: orgs.subnet, + settingsLogRetentionDaysConnection: + orgs.settingsLogRetentionDaysConnection + }) .from(sites) .innerJoin(orgs, eq(sites.orgId, orgs.orgId)) .where(eq(sites.siteId, newt.siteId)); @@ -108,6 +113,13 @@ export const handleConnectionLogMessage: MessageHandler = async (context) => { const orgId = site.orgId; + if (site.settingsLogRetentionDaysConnection === 0) { + logger.debug( + `Connection log retention is disabled for org ${orgId}, skipping` + ); + return; + } + // Extract the CIDR suffix (e.g. "/16") from the org subnet so we can // reconstruct the exact subnet string stored on each client record. const cidrSuffix = site.orgSubnet?.includes("/") diff --git a/server/private/routers/newt/handleRequestLogMessage.ts b/server/private/routers/newt/handleRequestLogMessage.ts new file mode 100644 index 000000000..f06c59bc6 --- /dev/null +++ b/server/private/routers/newt/handleRequestLogMessage.ts @@ -0,0 +1,238 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { db } from "@server/db"; +import { MessageHandler } from "@server/routers/ws"; +import { sites, Newt, orgs, clients, clientSitesAssociationsCache } from "@server/db"; +import { and, eq, inArray } from "drizzle-orm"; +import logger from "@server/logger"; +import { inflate } from "zlib"; +import { promisify } from "util"; +import { logRequestAudit } from "@server/routers/badger/logRequestAudit"; +import { getCountryCodeForIp } from "@server/lib/geoip"; + +export async function flushRequestLogToDb(): Promise { + return; +} + +const zlibInflate = promisify(inflate); + +interface HTTPRequestLogData { + requestId: string; + resourceId: number; // siteResourceId + timestamp: string; // ISO 8601 + method: string; + scheme: string; // "http" or "https" + host: string; + path: string; + rawQuery?: string; + userAgent?: string; + sourceAddr: string; // ip:port + tls: boolean; +} + +/** + * Decompress a base64-encoded zlib-compressed string into parsed JSON. + */ +async function decompressRequestLog( + compressed: string +): Promise { + const compressedBuffer = Buffer.from(compressed, "base64"); + const decompressed = await zlibInflate(compressedBuffer); + const jsonString = decompressed.toString("utf-8"); + const parsed = JSON.parse(jsonString); + + if (!Array.isArray(parsed)) { + throw new Error("Decompressed request log data is not an array"); + } + + return parsed; +} + +export const handleRequestLogMessage: MessageHandler = async (context) => { + const { message, client } = context; + const newt = client as Newt; + + if (!newt) { + logger.warn("Request log received but no newt client in context"); + return; + } + + if (!newt.siteId) { + logger.warn("Request log received but newt has no siteId"); + return; + } + + if (!message.data?.compressed) { + logger.warn("Request log message missing compressed data"); + return; + } + + // Look up the org for this site and check retention settings + const [site] = await db + .select({ + orgId: sites.orgId, + orgSubnet: orgs.subnet, + settingsLogRetentionDaysRequest: + orgs.settingsLogRetentionDaysRequest + }) + .from(sites) + .innerJoin(orgs, eq(sites.orgId, orgs.orgId)) + .where(eq(sites.siteId, newt.siteId)); + + if (!site) { + logger.warn( + `Request log received but site ${newt.siteId} not found in database` + ); + return; + } + + const orgId = site.orgId; + + if (site.settingsLogRetentionDaysRequest === 0) { + logger.debug( + `Request log retention is disabled for org ${orgId}, skipping` + ); + return; + } + + let entries: HTTPRequestLogData[]; + try { + entries = await decompressRequestLog(message.data.compressed); + } catch (error) { + logger.error("Failed to decompress request log data:", error); + return; + } + + if (entries.length === 0) { + return; + } + + logger.debug(`Request log entries: ${JSON.stringify(entries)}`); + + // Build a map from sourceIp → external endpoint string by joining clients + // with clientSitesAssociationsCache. The endpoint is the real-world IP:port + // of the client device and is used for GeoIP lookup. + const ipToEndpoint = new Map(); + + const cidrSuffix = site.orgSubnet?.includes("/") + ? site.orgSubnet.substring(site.orgSubnet.indexOf("/")) + : null; + + if (cidrSuffix) { + const uniqueSourceAddrs = new Set(); + for (const entry of entries) { + if (entry.sourceAddr) { + uniqueSourceAddrs.add(entry.sourceAddr); + } + } + + if (uniqueSourceAddrs.size > 0) { + const subnetQueries = Array.from(uniqueSourceAddrs).map((addr) => { + const ip = addr.includes(":") ? addr.split(":")[0] : addr; + return `${ip}${cidrSuffix}`; + }); + + const matchedClients = await db + .select({ + subnet: clients.subnet, + endpoint: clientSitesAssociationsCache.endpoint + }) + .from(clients) + .innerJoin( + clientSitesAssociationsCache, + and( + eq( + clientSitesAssociationsCache.clientId, + clients.clientId + ), + eq(clientSitesAssociationsCache.siteId, newt.siteId) + ) + ) + .where( + and( + eq(clients.orgId, orgId), + inArray(clients.subnet, subnetQueries) + ) + ); + + for (const c of matchedClients) { + if (c.endpoint) { + const ip = c.subnet.split("/")[0]; + ipToEndpoint.set(ip, c.endpoint); + } + } + } + } + + for (const entry of entries) { + if ( + !entry.requestId || + !entry.resourceId || + !entry.method || + !entry.scheme || + !entry.host || + !entry.path || + !entry.sourceAddr + ) { + logger.debug( + `Skipping request log entry with missing required fields: ${JSON.stringify(entry)}` + ); + continue; + } + + const originalRequestURL = + entry.scheme + + "://" + + entry.host + + entry.path + + (entry.rawQuery ? "?" + entry.rawQuery : ""); + + // Resolve the client's external endpoint for GeoIP lookup. + // sourceAddr is the WireGuard IP (possibly ip:port), so strip the port. + const sourceIp = entry.sourceAddr.includes(":") + ? entry.sourceAddr.split(":")[0] + : entry.sourceAddr; + const endpoint = ipToEndpoint.get(sourceIp); + let location: string | undefined; + if (endpoint) { + const endpointIp = endpoint.includes(":") + ? endpoint.split(":")[0] + : endpoint; + location = await getCountryCodeForIp(endpointIp); + } + + await logRequestAudit( + { + action: true, + reason: 108, + siteResourceId: entry.resourceId, + orgId, + location + }, + { + path: entry.path, + originalRequestURL, + scheme: entry.scheme, + host: entry.host, + method: entry.method, + tls: entry.tls, + requestIp: entry.sourceAddr + } + ); + } + + logger.debug( + `Buffered ${entries.length} request log entry/entries from newt ${newt.newtId} (site ${newt.siteId})` + ); +}; diff --git a/server/private/routers/newt/index.ts b/server/private/routers/newt/index.ts index 59d8e980a..94dfc8f05 100644 --- a/server/private/routers/newt/index.ts +++ b/server/private/routers/newt/index.ts @@ -12,3 +12,4 @@ */ export * from "./handleConnectionLogMessage"; +export * from "./handleRequestLogMessage"; diff --git a/server/private/routers/org/index.ts b/server/private/routers/org/index.ts index 7a23be693..5dc0faed8 100644 --- a/server/private/routers/org/index.ts +++ b/server/private/routers/org/index.ts @@ -12,3 +12,4 @@ */ export * from "./sendUsageNotifications"; +export * from "./sendTrialNotification"; diff --git a/server/private/routers/org/sendTrialNotification.ts b/server/private/routers/org/sendTrialNotification.ts new file mode 100644 index 000000000..c3b7f6518 --- /dev/null +++ b/server/private/routers/org/sendTrialNotification.ts @@ -0,0 +1,224 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db } from "@server/db"; +import { userOrgs, userOrgRoles, users, roles, orgs } from "@server/db"; +import { eq, and, or } from "drizzle-orm"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { sendEmail } from "@server/emails"; +import NotifyTrialExpiring from "@server/emails/templates/NotifyTrialExpiring"; +import config from "@server/lib/config"; + +const sendTrialNotificationParamsSchema = z.object({ + orgId: z.string() +}); + +const sendTrialNotificationBodySchema = z.object({ + notificationType: z.enum(["trial_ending_5d", "trial_ending_24h", "trial_ended"]), + orgName: z.string(), + trialEndsAt: z.number(), + billingLink: z.string().optional() +}); + +export type SendTrialNotificationResponse = { + success: boolean; + emailsSent: number; + adminEmails: string[]; +}; + +async function getOrgAdmins(orgId: string) { + const admins = await db + .select({ + userId: users.userId, + email: users.email, + name: users.name, + isOwner: userOrgs.isOwner, + roleName: roles.name, + isAdminRole: roles.isAdmin + }) + .from(userOrgs) + .innerJoin(users, eq(userOrgs.userId, users.userId)) + .leftJoin( + userOrgRoles, + and( + eq(userOrgs.userId, userOrgRoles.userId), + eq(userOrgs.orgId, userOrgRoles.orgId) + ) + ) + .leftJoin(roles, eq(userOrgRoles.roleId, roles.roleId)) + .where( + and( + eq(userOrgs.orgId, orgId), + or(eq(userOrgs.isOwner, true), eq(roles.isAdmin, true)) + ) + ); + + const byUserId = new Map( + admins.map((a) => [a.userId, a]) + ); + const orgAdmins = Array.from(byUserId.values()).filter( + (admin) => admin.email && admin.email.length > 0 + ); + + return orgAdmins; +} + +export async function sendTrialNotification( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = sendTrialNotificationParamsSchema.safeParse( + req.params + ); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + + const parsedBody = sendTrialNotificationBodySchema.safeParse(req.body); + if (!parsedBody.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedBody.error).toString() + ) + ); + } + + const { orgId } = parsedParams.data; + const { notificationType, orgName, trialEndsAt, billingLink: bodyBillingLink } = + parsedBody.data; + + // Verify organization exists + const org = await db + .select() + .from(orgs) + .where(eq(orgs.orgId, orgId)) + .limit(1); + + if (org.length === 0) { + return next( + createHttpError(HttpCode.NOT_FOUND, "Organization not found") + ); + } + + // Get all admin users for this organization + const orgAdmins = await getOrgAdmins(orgId); + + if (orgAdmins.length === 0) { + logger.warn(`No admin users found for organization ${orgId}`); + return response(res, { + data: { + success: true, + emailsSent: 0, + adminEmails: [] + }, + success: true, + error: false, + message: "No admin users found to notify", + status: HttpCode.OK + }); + } + + const billingLink = + bodyBillingLink ?? + `${config.getRawConfig().app.dashboard_url}/${orgId}/settings/billing`; + + const trialEndsAtFormatted = new Date(trialEndsAt * 1000).toLocaleDateString( + "en-US", + { year: "numeric", month: "long", day: "numeric" } + ); + + let daysRemaining: number | null; + let subject: string; + + if (notificationType === "trial_ending_5d") { + daysRemaining = 5; + subject = "Your trial ends in 5 days"; + } else if (notificationType === "trial_ending_24h") { + daysRemaining = 1; + subject = "Your trial ends tomorrow"; + } else { + daysRemaining = null; + subject = "Your trial has ended"; + } + + let emailsSent = 0; + const adminEmails: string[] = []; + + for (const admin of orgAdmins) { + if (!admin.email) continue; + + try { + const template = NotifyTrialExpiring({ + email: admin.email, + orgName, + trialEndsAt: trialEndsAtFormatted, + daysRemaining, + billingLink + }); + + await sendEmail(template, { + to: admin.email, + from: config.getNoReplyEmail(), + subject + }); + + emailsSent++; + adminEmails.push(admin.email); + + logger.info( + `Trial notification sent to admin ${admin.email} for org ${orgId}` + ); + } catch (emailError) { + logger.error( + `Failed to send trial notification to ${admin.email}:`, + emailError + ); + // Continue with other admins even if one fails + } + } + + return response(res, { + data: { + success: true, + emailsSent, + adminEmails + }, + success: true, + error: false, + message: `Trial notifications sent to ${emailsSent} administrators`, + status: HttpCode.OK + }); + } catch (error) { + logger.error("Error sending trial notifications:", error); + return next( + createHttpError( + HttpCode.INTERNAL_SERVER_ERROR, + "Failed to send trial notifications" + ) + ); + } +} \ No newline at end of file diff --git a/server/private/routers/remoteExitNode/handleRemoteExitNodePingMessage.ts b/server/private/routers/remoteExitNode/handleRemoteExitNodePingMessage.ts index cc7578791..c2c710e11 100644 --- a/server/private/routers/remoteExitNode/handleRemoteExitNodePingMessage.ts +++ b/server/private/routers/remoteExitNode/handleRemoteExitNodePingMessage.ts @@ -11,78 +11,12 @@ * This file is not licensed under the AGPLv3. */ -import { db, exitNodes, sites } from "@server/db"; +import { db, exitNodes } from "@server/db"; import { MessageHandler } from "@server/routers/ws"; -import { clients, RemoteExitNode } from "@server/db"; -import { eq, lt, isNull, and, or, inArray } from "drizzle-orm"; +import { RemoteExitNode } from "@server/db"; +import { eq } from "drizzle-orm"; import logger from "@server/logger"; -// Track if the offline checker interval is running -let offlineCheckerInterval: NodeJS.Timeout | null = null; -const OFFLINE_CHECK_INTERVAL = 30 * 1000; // Check every 30 seconds -const OFFLINE_THRESHOLD_MS = 2 * 60 * 1000; // 2 minutes - -/** - * Starts the background interval that checks for clients that haven't pinged recently - * and marks them as offline - */ -export const startRemoteExitNodeOfflineChecker = (): void => { - if (offlineCheckerInterval) { - return; // Already running - } - - offlineCheckerInterval = setInterval(async () => { - try { - const twoMinutesAgo = Math.floor( - (Date.now() - OFFLINE_THRESHOLD_MS) / 1000 - ); - - // Find clients that haven't pinged in the last 2 minutes and mark them as offline - const offlineNodes = await db - .update(exitNodes) - .set({ online: false }) - .where( - and( - eq(exitNodes.online, true), - eq(exitNodes.type, "remoteExitNode"), - or( - lt(exitNodes.lastPing, twoMinutesAgo), - isNull(exitNodes.lastPing) - ) - ) - ) - .returning(); - - if (offlineNodes.length > 0) { - logger.info( - `checkRemoteExitNodeOffline: Marked ${offlineNodes.length} remoteExitNode client(s) offline due to inactivity` - ); - - for (const offlineClient of offlineNodes) { - logger.debug( - `checkRemoteExitNodeOffline: Client ${offlineClient.exitNodeId} marked offline (lastPing: ${offlineClient.lastPing})` - ); - } - } - } catch (error) { - logger.error("Error in offline checker interval", { error }); - } - }, OFFLINE_CHECK_INTERVAL); - - logger.debug("Started offline checker interval"); -}; - -/** - * Stops the background interval that checks for offline clients - */ -export const stopRemoteExitNodeOfflineChecker = (): void => { - if (offlineCheckerInterval) { - clearInterval(offlineCheckerInterval); - offlineCheckerInterval = null; - logger.info("Stopped offline checker interval"); - } -}; - /** * Handles ping messages from clients and responds with pong */ diff --git a/server/private/routers/remoteExitNode/index.ts b/server/private/routers/remoteExitNode/index.ts index bfbf98fed..730f6b693 100644 --- a/server/private/routers/remoteExitNode/index.ts +++ b/server/private/routers/remoteExitNode/index.ts @@ -21,3 +21,4 @@ export * from "./deleteRemoteExitNode"; export * from "./listRemoteExitNodes"; export * from "./pickRemoteExitNodeDefaults"; export * from "./quickStartRemoteExitNode"; +export * from "./offlineChecker"; diff --git a/server/private/routers/remoteExitNode/offlineChecker.ts b/server/private/routers/remoteExitNode/offlineChecker.ts new file mode 100644 index 000000000..7f5e906f8 --- /dev/null +++ b/server/private/routers/remoteExitNode/offlineChecker.ts @@ -0,0 +1,82 @@ +/* + * This file is part of a proprietary work. + * + * Copyright (c) 2025-2026 Fossorial, Inc. + * All rights reserved. + * + * This file is licensed under the Fossorial Commercial License. + * You may not use this file except in compliance with the License. + * Unauthorized use, copying, modification, or distribution is strictly prohibited. + * + * This file is not licensed under the AGPLv3. + */ + +import { db, exitNodes } from "@server/db"; +import { eq, lt, isNull, and, or } from "drizzle-orm"; +import logger from "@server/logger"; + +// Track if the offline checker interval is running +let offlineCheckerInterval: NodeJS.Timeout | null = null; +const OFFLINE_CHECK_INTERVAL = 30 * 1000; // Check every 30 seconds +const OFFLINE_THRESHOLD_MS = 2 * 60 * 1000; // 2 minutes + +/** + * Starts the background interval that checks for clients that haven't pinged recently + * and marks them as offline + */ +export const startRemoteExitNodeOfflineChecker = (): void => { + if (offlineCheckerInterval) { + return; // Already running + } + + offlineCheckerInterval = setInterval(async () => { + try { + const twoMinutesAgo = Math.floor( + (Date.now() - OFFLINE_THRESHOLD_MS) / 1000 + ); + + // Find clients that haven't pinged in the last 2 minutes and mark them as offline + const offlineNodes = await db + .update(exitNodes) + .set({ online: false }) + .where( + and( + eq(exitNodes.online, true), + eq(exitNodes.type, "remoteExitNode"), + or( + lt(exitNodes.lastPing, twoMinutesAgo), + isNull(exitNodes.lastPing) + ) + ) + ) + .returning(); + + if (offlineNodes.length > 0) { + logger.info( + `checkRemoteExitNodeOffline: Marked ${offlineNodes.length} remoteExitNode client(s) offline due to inactivity` + ); + + for (const offlineClient of offlineNodes) { + logger.debug( + `checkRemoteExitNodeOffline: Client ${offlineClient.exitNodeId} marked offline (lastPing: ${offlineClient.lastPing})` + ); + } + } + } catch (error) { + logger.error("Error in offline checker interval", { error }); + } + }, OFFLINE_CHECK_INTERVAL); + + logger.debug("Started offline checker interval"); +}; + +/** + * Stops the background interval that checks for offline clients + */ +export const stopRemoteExitNodeOfflineChecker = (): void => { + if (offlineCheckerInterval) { + clearInterval(offlineCheckerInterval); + offlineCheckerInterval = null; + logger.info("Stopped offline checker interval"); + } +}; diff --git a/server/private/routers/ssh/signSshKey.ts b/server/private/routers/ssh/signSshKey.ts index f929aeca5..82044c0ad 100644 --- a/server/private/routers/ssh/signSshKey.ts +++ b/server/private/routers/ssh/signSshKey.ts @@ -21,7 +21,7 @@ import { roles, roundTripMessageTracker, siteResources, - sites, + siteNetworks, userOrgs } from "@server/db"; import { logAccessAudit } from "#private/lib/logAccessAudit"; @@ -63,10 +63,12 @@ const bodySchema = z export type SignSshKeyResponse = { certificate: string; + messageIds: number[]; messageId: number; sshUsername: string; sshHost: string; resourceId: number; + siteIds: number[]; siteId: number; keyId: string; validPrincipals: string[]; @@ -260,10 +262,7 @@ export async function signSshKey( .update(userOrgs) .set({ pamUsername: usernameToUse }) .where( - and( - eq(userOrgs.orgId, orgId), - eq(userOrgs.userId, userId) - ) + and(eq(userOrgs.orgId, orgId), eq(userOrgs.userId, userId)) ); } else { usernameToUse = userOrg.pamUsername; @@ -395,21 +394,12 @@ export async function signSshKey( homedir = roleRows[0].sshCreateHomeDir ?? null; } - // get the site - const [newt] = await db - .select() - .from(newts) - .where(eq(newts.siteId, resource.siteId)) - .limit(1); + const sites = await db + .select({ siteId: siteNetworks.siteId }) + .from(siteNetworks) + .where(eq(siteNetworks.networkId, resource.networkId!)); - if (!newt) { - return next( - createHttpError( - HttpCode.INTERNAL_SERVER_ERROR, - "Site associated with resource not found" - ) - ); - } + const siteIds = sites.map((site) => site.siteId); // Sign the public key const now = BigInt(Math.floor(Date.now() / 1000)); @@ -423,43 +413,64 @@ export async function signSshKey( validBefore: now + validFor }); - const [message] = await db - .insert(roundTripMessageTracker) - .values({ - wsClientId: newt.newtId, - messageType: `newt/pam/connection`, - sentAt: Math.floor(Date.now() / 1000) - }) - .returning(); + const messageIds: number[] = []; + for (const siteId of siteIds) { + // get the site + const [newt] = await db + .select() + .from(newts) + .where(eq(newts.siteId, siteId)) + .limit(1); - if (!message) { - return next( - createHttpError( - HttpCode.INTERNAL_SERVER_ERROR, - "Failed to create message tracker entry" - ) - ); - } - - await sendToClient(newt.newtId, { - type: `newt/pam/connection`, - data: { - messageId: message.messageId, - orgId: orgId, - agentPort: resource.authDaemonPort ?? 22123, - externalAuthDaemon: resource.authDaemonMode === "remote", - agentHost: resource.destination, - caCert: caKeys.publicKeyOpenSSH, - username: usernameToUse, - niceId: resource.niceId, - metadata: { - sudoMode: sudoMode, - sudoCommands: parsedSudoCommands, - homedir: homedir, - groups: parsedGroups - } + if (!newt) { + return next( + createHttpError( + HttpCode.INTERNAL_SERVER_ERROR, + "Site associated with resource not found" + ) + ); } - }); + + const [message] = await db + .insert(roundTripMessageTracker) + .values({ + wsClientId: newt.newtId, + messageType: `newt/pam/connection`, + sentAt: Math.floor(Date.now() / 1000) + }) + .returning(); + + if (!message) { + return next( + createHttpError( + HttpCode.INTERNAL_SERVER_ERROR, + "Failed to create message tracker entry" + ) + ); + } + + messageIds.push(message.messageId); + + await sendToClient(newt.newtId, { + type: `newt/pam/connection`, + data: { + messageId: message.messageId, + orgId: orgId, + agentPort: resource.authDaemonPort ?? 22123, + externalAuthDaemon: resource.authDaemonMode === "remote", + agentHost: resource.destination, + caCert: caKeys.publicKeyOpenSSH, + username: usernameToUse, + niceId: resource.niceId, + metadata: { + sudoMode: sudoMode, + sudoCommands: parsedSudoCommands, + homedir: homedir, + groups: parsedGroups + } + } + }); + } const expiresIn = Number(validFor); // seconds @@ -480,7 +491,7 @@ export async function signSshKey( metadata: JSON.stringify({ resourceId: resource.siteResourceId, resource: resource.name, - siteId: resource.siteId, + siteIds: siteIds }) }); @@ -494,7 +505,7 @@ export async function signSshKey( : undefined, metadata: { resourceName: resource.name, - siteId: resource.siteId, + siteId: siteIds[0], sshUsername: usernameToUse, sshHost: sshHost }, @@ -505,11 +516,13 @@ export async function signSshKey( return response(res, { data: { certificate: cert.certificate, - messageId: message.messageId, + messageIds: messageIds, + messageId: messageIds[0], // just pick the first one for backward compatibility sshUsername: usernameToUse, sshHost: sshHost, resourceId: resource.siteResourceId, - siteId: resource.siteId, + siteIds: siteIds, + siteId: siteIds[0], // just pick the first one for backward compatibility keyId: cert.keyId, validPrincipals: cert.validPrincipals, validAfter: cert.validAfter.toISOString(), diff --git a/server/private/routers/ws/messageHandlers.ts b/server/private/routers/ws/messageHandlers.ts index 00a9a0ad6..b2553871e 100644 --- a/server/private/routers/ws/messageHandlers.ts +++ b/server/private/routers/ws/messageHandlers.ts @@ -18,12 +18,13 @@ import { } from "#private/routers/remoteExitNode"; import { MessageHandler } from "@server/routers/ws"; import { build } from "@server/build"; -import { handleConnectionLogMessage } from "#private/routers/newt"; +import { handleConnectionLogMessage, handleRequestLogMessage } from "#private/routers/newt"; export const messageHandlers: Record = { "remoteExitNode/register": handleRemoteExitNodeRegisterMessage, "remoteExitNode/ping": handleRemoteExitNodePingMessage, "newt/access-log": handleConnectionLogMessage, + "newt/request-log": handleRequestLogMessage, }; if (build != "saas") { diff --git a/server/routers/auditLogs/queryRequestAuditLog.ts b/server/routers/auditLogs/queryRequestAuditLog.ts index 176a9e5d3..000ec9815 100644 --- a/server/routers/auditLogs/queryRequestAuditLog.ts +++ b/server/routers/auditLogs/queryRequestAuditLog.ts @@ -1,8 +1,8 @@ -import { logsDb, primaryLogsDb, requestAuditLog, resources, db, primaryDb } from "@server/db"; +import { logsDb, primaryLogsDb, requestAuditLog, resources, siteResources, db, primaryDb } from "@server/db"; import { registry } from "@server/openApi"; import { NextFunction } from "express"; import { Request, Response } from "express"; -import { eq, gt, lt, and, count, desc, inArray } from "drizzle-orm"; +import { eq, gt, lt, and, count, desc, inArray, isNull, or } from "drizzle-orm"; import { OpenAPITags } from "@server/openApi"; import { z } from "zod"; import createHttpError from "http-errors"; @@ -92,7 +92,10 @@ function getWhere(data: Q) { lt(requestAuditLog.timestamp, data.timeEnd), eq(requestAuditLog.orgId, data.orgId), data.resourceId - ? eq(requestAuditLog.resourceId, data.resourceId) + ? or( + eq(requestAuditLog.resourceId, data.resourceId), + eq(requestAuditLog.siteResourceId, data.resourceId) + ) : undefined, data.actor ? eq(requestAuditLog.actor, data.actor) : undefined, data.method ? eq(requestAuditLog.method, data.method) : undefined, @@ -110,15 +113,16 @@ export function queryRequest(data: Q) { return primaryLogsDb .select({ id: requestAuditLog.id, - timestamp: requestAuditLog.timestamp, - orgId: requestAuditLog.orgId, - action: requestAuditLog.action, - reason: requestAuditLog.reason, - actorType: requestAuditLog.actorType, - actor: requestAuditLog.actor, - actorId: requestAuditLog.actorId, - resourceId: requestAuditLog.resourceId, - ip: requestAuditLog.ip, + timestamp: requestAuditLog.timestamp, + orgId: requestAuditLog.orgId, + action: requestAuditLog.action, + reason: requestAuditLog.reason, + actorType: requestAuditLog.actorType, + actor: requestAuditLog.actor, + actorId: requestAuditLog.actorId, + resourceId: requestAuditLog.resourceId, + siteResourceId: requestAuditLog.siteResourceId, + ip: requestAuditLog.ip, location: requestAuditLog.location, userAgent: requestAuditLog.userAgent, metadata: requestAuditLog.metadata, @@ -137,37 +141,73 @@ export function queryRequest(data: Q) { } async function enrichWithResourceDetails(logs: Awaited>) { - // If logs database is the same as main database, we can do a join - // Otherwise, we need to fetch resource details separately const resourceIds = logs .map(log => log.resourceId) .filter((id): id is number => id !== null && id !== undefined); - if (resourceIds.length === 0) { + const siteResourceIds = logs + .filter(log => log.resourceId == null && log.siteResourceId != null) + .map(log => log.siteResourceId) + .filter((id): id is number => id !== null && id !== undefined); + + if (resourceIds.length === 0 && siteResourceIds.length === 0) { return logs.map(log => ({ ...log, resourceName: null, resourceNiceId: null })); } - // Fetch resource details from main database - const resourceDetails = await primaryDb - .select({ - resourceId: resources.resourceId, - name: resources.name, - niceId: resources.niceId - }) - .from(resources) - .where(inArray(resources.resourceId, resourceIds)); + const resourceMap = new Map(); - // Create a map for quick lookup - const resourceMap = new Map( - resourceDetails.map(r => [r.resourceId, { name: r.name, niceId: r.niceId }]) - ); + if (resourceIds.length > 0) { + const resourceDetails = await primaryDb + .select({ + resourceId: resources.resourceId, + name: resources.name, + niceId: resources.niceId + }) + .from(resources) + .where(inArray(resources.resourceId, resourceIds)); + + for (const r of resourceDetails) { + resourceMap.set(r.resourceId, { name: r.name, niceId: r.niceId }); + } + } + + const siteResourceMap = new Map(); + + if (siteResourceIds.length > 0) { + const siteResourceDetails = await primaryDb + .select({ + siteResourceId: siteResources.siteResourceId, + name: siteResources.name, + niceId: siteResources.niceId + }) + .from(siteResources) + .where(inArray(siteResources.siteResourceId, siteResourceIds)); + + for (const r of siteResourceDetails) { + siteResourceMap.set(r.siteResourceId, { name: r.name, niceId: r.niceId }); + } + } // Enrich logs with resource details - return logs.map(log => ({ - ...log, - resourceName: log.resourceId ? resourceMap.get(log.resourceId)?.name ?? null : null, - resourceNiceId: log.resourceId ? resourceMap.get(log.resourceId)?.niceId ?? null : null - })); + return logs.map(log => { + if (log.resourceId != null) { + const details = resourceMap.get(log.resourceId); + return { + ...log, + resourceName: details?.name ?? null, + resourceNiceId: details?.niceId ?? null + }; + } else if (log.siteResourceId != null) { + const details = siteResourceMap.get(log.siteResourceId); + return { + ...log, + resourceId: log.siteResourceId, + resourceName: details?.name ?? null, + resourceNiceId: details?.niceId ?? null + }; + } + return { ...log, resourceName: null, resourceNiceId: null }; + }); } export function countRequestQuery(data: Q) { @@ -211,7 +251,8 @@ async function queryUniqueFilterAttributes( uniqueLocations, uniqueHosts, uniquePaths, - uniqueResources + uniqueResources, + uniqueSiteResources ] = await Promise.all([ primaryLogsDb .selectDistinct({ actor: requestAuditLog.actor }) @@ -239,6 +280,13 @@ async function queryUniqueFilterAttributes( }) .from(requestAuditLog) .where(baseConditions) + .limit(DISTINCT_LIMIT + 1), + primaryLogsDb + .selectDistinct({ + id: requestAuditLog.siteResourceId + }) + .from(requestAuditLog) + .where(and(baseConditions, isNull(requestAuditLog.resourceId))) .limit(DISTINCT_LIMIT + 1) ]); @@ -259,6 +307,10 @@ async function queryUniqueFilterAttributes( .map(row => row.id) .filter((id): id is number => id !== null); + const siteResourceIds = uniqueSiteResources + .map(row => row.id) + .filter((id): id is number => id !== null); + let resourcesWithNames: Array<{ id: number; name: string | null }> = []; if (resourceIds.length > 0) { @@ -270,10 +322,31 @@ async function queryUniqueFilterAttributes( .from(resources) .where(inArray(resources.resourceId, resourceIds)); - resourcesWithNames = resourceDetails.map(r => ({ - id: r.resourceId, - name: r.name - })); + resourcesWithNames = [ + ...resourcesWithNames, + ...resourceDetails.map(r => ({ + id: r.resourceId, + name: r.name + })) + ]; + } + + if (siteResourceIds.length > 0) { + const siteResourceDetails = await primaryDb + .select({ + siteResourceId: siteResources.siteResourceId, + name: siteResources.name + }) + .from(siteResources) + .where(inArray(siteResources.siteResourceId, siteResourceIds)); + + resourcesWithNames = [ + ...resourcesWithNames, + ...siteResourceDetails.map(r => ({ + id: r.siteResourceId, + name: r.name + })) + ]; } return { diff --git a/server/routers/auditLogs/types.ts b/server/routers/auditLogs/types.ts index 4c278cba5..972eebfe3 100644 --- a/server/routers/auditLogs/types.ts +++ b/server/routers/auditLogs/types.ts @@ -28,6 +28,7 @@ export type QueryRequestAuditLogResponse = { actor: string | null; actorId: string | null; resourceId: number | null; + siteResourceId: number | null; resourceNiceId: string | null; resourceName: string | null; ip: string | null; diff --git a/server/routers/badger/logRequestAudit.ts b/server/routers/badger/logRequestAudit.ts index 92d01332e..884fb7ae4 100644 --- a/server/routers/badger/logRequestAudit.ts +++ b/server/routers/badger/logRequestAudit.ts @@ -18,6 +18,7 @@ Reasons: 105 - Valid Password 106 - Valid email 107 - Valid SSO +108 - Connected Client 201 - Resource Not Found 202 - Resource Blocked @@ -38,6 +39,7 @@ const auditLogBuffer: Array<{ metadata: any; action: boolean; resourceId?: number; + siteResourceId?: number; reason: number; location?: string; originalRequestURL: string; @@ -186,6 +188,7 @@ export async function logRequestAudit( action: boolean; reason: number; resourceId?: number; + siteResourceId?: number; orgId?: string; location?: string; user?: { username: string; userId: string }; @@ -262,6 +265,7 @@ export async function logRequestAudit( metadata: sanitizeString(metadata), action: data.action, resourceId: data.resourceId, + siteResourceId: data.siteResourceId, reason: data.reason, location: sanitizeString(data.location), originalRequestURL: sanitizeString(body.originalRequestURL) ?? "", diff --git a/server/routers/domain/listDomains.ts b/server/routers/domain/listDomains.ts index 085acf0c6..94dddb1cf 100644 --- a/server/routers/domain/listDomains.ts +++ b/server/routers/domain/listDomains.ts @@ -103,7 +103,8 @@ export async function listDomains( const [{ count }] = await db .select({ count: sql`count(*)` }) - .from(domains); + .from(orgDomains) + .where(eq(orgDomains.orgId, orgId)); return response(res, { data: { diff --git a/server/routers/external.ts b/server/routers/external.ts index d7729bca5..a17c88fb1 100644 --- a/server/routers/external.ts +++ b/server/routers/external.ts @@ -285,6 +285,13 @@ authenticated.get( site.listContainers ); +authenticated.get( + "/site/:siteId/status-history", + verifySiteAccess, + verifyUserHasAction(ActionsEnum.getSite), + site.getSiteStatusHistory +); + // Site Resource endpoints authenticated.put( "/org/:orgId/site-resource", @@ -420,6 +427,13 @@ authenticated.get( resource.listResources ); +authenticated.get( + "/resource/:resourceId/status-history", + verifyResourceAccess, + verifyUserHasAction(ActionsEnum.getResource), + resource.getResourceStatusHistory +); + authenticated.get( "/org/:orgId/resources", verifyOrgAccess, diff --git a/server/routers/gerbil/receiveBandwidth.ts b/server/routers/gerbil/receiveBandwidth.ts index dcd897471..eacf3dad4 100644 --- a/server/routers/gerbil/receiveBandwidth.ts +++ b/server/routers/gerbil/receiveBandwidth.ts @@ -88,11 +88,11 @@ async function dbQueryRows>( ): Promise { const anyDb = db as any; if (typeof anyDb.execute === "function") { - // PostgreSQL (node-postgres via Drizzle) — returns { rows: [...] } or an array + // PostgreSQL (node-postgres via Drizzle) - returns { rows: [...] } or an array const result = await anyDb.execute(query); return (Array.isArray(result) ? result : (result.rows ?? [])) as T[]; } - // SQLite (better-sqlite3 via Drizzle) — returns an array directly + // SQLite (better-sqlite3 via Drizzle) - returns an array directly return (await anyDb.all(query)) as T[]; } @@ -106,7 +106,7 @@ function isSQLite(): boolean { * Swaps out the accumulator before writing so that any bandwidth messages * received during the flush are captured in the new accumulator rather than * being lost or causing contention. Sites are updated in chunks via a single - * batch UPDATE per chunk. Failed chunks are discarded — exact per-flush + * batch UPDATE per chunk. Failed chunks are discarded - exact per-flush * accuracy is not critical and re-queuing is not worth the added complexity. * * This function is exported so that the application's graceful-shutdown @@ -125,7 +125,7 @@ export async function flushSiteBandwidthToDb(): Promise { const currentTime = new Date().toISOString(); // Sort by publicKey for consistent lock ordering across concurrent - // writers — deadlock-prevention strategy. + // writers - deadlock-prevention strategy. const sortedEntries = [...snapshot.entries()].sort(([a], [b]) => a.localeCompare(b) ); @@ -150,7 +150,7 @@ export async function flushSiteBandwidthToDb(): Promise { try { rows = await withDeadlockRetry(async () => { if (isSQLite()) { - // SQLite: one UPDATE per row — no need for batch efficiency here. + // SQLite: one UPDATE per row - no need for batch efficiency here. const results: { orgId: string; pubKey: string }[] = []; for (const [publicKey, { bytesIn, bytesOut }] of chunk) { const result = await dbQueryRows<{ @@ -170,7 +170,7 @@ export async function flushSiteBandwidthToDb(): Promise { return results; } - // PostgreSQL: batch UPDATE … FROM (VALUES …) — single round-trip per chunk. + // PostgreSQL: batch UPDATE … FROM (VALUES …) - single round-trip per chunk. const valuesList = chunk.map(([publicKey, { bytesIn, bytesOut }]) => sql`(${publicKey}::text, ${bytesIn}::real, ${bytesOut}::real)` ); @@ -191,7 +191,7 @@ export async function flushSiteBandwidthToDb(): Promise { `Failed to flush bandwidth chunk [${i}–${chunkEnd}], discarding ${chunk.length} site(s):`, error ); - // Discard the chunk — exact per-flush accuracy is not critical. + // Discard the chunk - exact per-flush accuracy is not critical. continue; } @@ -232,7 +232,7 @@ export async function flushSiteBandwidthToDb(): Promise { totalBandwidth ); if (bandwidthUsage) { - // Fire-and-forget — don't block the flush on limit checking. + // Fire-and-forget - don't block the flush on limit checking. usageService .checkLimitSet( orgId, @@ -298,7 +298,7 @@ export async function updateSiteBandwidth( exitNodeId?: number ): Promise { for (const { publicKey, bytesIn, bytesOut } of bandwidthData) { - // Skip peers that haven't transferred any data — writing zeros to the + // Skip peers that haven't transferred any data - writing zeros to the // database would be a no-op anyway. if (bytesIn <= 0 && bytesOut <= 0) { continue; diff --git a/server/routers/healthChecks/types.ts b/server/routers/healthChecks/types.ts new file mode 100644 index 000000000..0def60833 --- /dev/null +++ b/server/routers/healthChecks/types.ts @@ -0,0 +1,34 @@ +export type ListHealthChecksResponse = { + healthChecks: { + targetHealthCheckId: number; + name: string; + siteId: number | null; + siteName: string | null; + siteNiceId: string | null; + hcEnabled: boolean; + hcHealth: "unknown" | "healthy" | "unhealthy"; + hcMode: string | null; + hcHostname: string | null; + hcPort: number | null; + hcPath: string | null; + hcScheme: string | null; + hcMethod: string | null; + hcInterval: number | null; + hcUnhealthyInterval: number | null; + hcTimeout: number | null; + hcHeaders: string | null; + hcFollowRedirects: boolean | null; + hcStatus: number | null; + hcTlsServerName: string | null; + hcHealthyThreshold: number | null; + hcUnhealthyThreshold: number | null; + resourceId: number | null; + resourceName: string | null; + resourceNiceId: string | null; + }[]; + pagination: { + total: number; + limit: number; + offset: number; + }; +}; diff --git a/server/routers/newt/buildConfiguration.ts b/server/routers/newt/buildConfiguration.ts index afb196152..f87d38450 100644 --- a/server/routers/newt/buildConfiguration.ts +++ b/server/routers/newt/buildConfiguration.ts @@ -4,8 +4,10 @@ import { clientSitesAssociationsCache, db, ExitNode, + networks, resources, Site, + siteNetworks, siteResources, targetHealthCheck, targets @@ -84,7 +86,8 @@ export async function buildClientConfigurationForNewtClient( // ) // ); - if (!client.clientSitesAssociationsCache.isJitMode) { // if we are adding sites through jit then dont add the site to the olm + if (!client.clientSitesAssociationsCache.isJitMode) { + // if we are adding sites through jit then dont add the site to the olm // update the peer info on the olm // if the peer has not been added yet this will be a no-op await updatePeer(client.clients.clientId, { @@ -137,11 +140,14 @@ export async function buildClientConfigurationForNewtClient( // Filter out any null values from peers that didn't have an olm const validPeers = peers.filter((peer) => peer !== null); - // Get all enabled site resources for this site + // Get all enabled site resources for this site by joining through siteNetworks and networks const allSiteResources = await db .select() .from(siteResources) - .where(eq(siteResources.siteId, siteId)); + .innerJoin(networks, eq(siteResources.networkId, networks.networkId)) + .innerJoin(siteNetworks, eq(networks.networkId, siteNetworks.networkId)) + .where(eq(siteNetworks.siteId, siteId)) + .then((rows) => rows.map((r) => r.siteResources)); const targetsToSend: SubnetProxyTargetV2[] = []; @@ -168,7 +174,7 @@ export async function buildClientConfigurationForNewtClient( ) ); - const resourceTargets = generateSubnetProxyTargetV2( + const resourceTargets = await generateSubnetProxyTargetV2( resource, resourceClients ); @@ -184,7 +190,10 @@ export async function buildClientConfigurationForNewtClient( }; } -export async function buildTargetConfigurationForNewtClient(siteId: number) { +export async function buildTargetConfigurationForNewtClient( + siteId: number, + version?: string | null +) { // Get all enabled targets with their resource protocol information const allTargets = await db .select({ @@ -195,7 +204,15 @@ export async function buildTargetConfigurationForNewtClient(siteId: number) { port: targets.port, internalPort: targets.internalPort, enabled: targets.enabled, - protocol: resources.protocol, + protocol: resources.protocol + }) + .from(targets) + .innerJoin(resources, eq(targets.resourceId, resources.resourceId)) + .where(and(eq(targets.siteId, siteId), eq(targets.enabled, true))); + + const allHealthChecks = await db + .select({ + targetHealthCheckId: targetHealthCheck.targetHealthCheckId, hcEnabled: targetHealthCheck.hcEnabled, hcPath: targetHealthCheck.hcPath, hcScheme: targetHealthCheck.hcScheme, @@ -206,17 +223,15 @@ export async function buildTargetConfigurationForNewtClient(siteId: number) { hcUnhealthyInterval: targetHealthCheck.hcUnhealthyInterval, hcTimeout: targetHealthCheck.hcTimeout, hcHeaders: targetHealthCheck.hcHeaders, + hcFollowRedirects: targetHealthCheck.hcFollowRedirects, hcMethod: targetHealthCheck.hcMethod, hcTlsServerName: targetHealthCheck.hcTlsServerName, - hcStatus: targetHealthCheck.hcStatus + hcStatus: targetHealthCheck.hcStatus, + hcHealthyThreshold: targetHealthCheck.hcHealthyThreshold, + hcUnhealthyThreshold: targetHealthCheck.hcUnhealthyThreshold }) - .from(targets) - .innerJoin(resources, eq(targets.resourceId, resources.resourceId)) - .leftJoin( - targetHealthCheck, - eq(targets.targetId, targetHealthCheck.targetId) - ) - .where(and(eq(targets.siteId, siteId), eq(targets.enabled, true))); + .from(targetHealthCheck) + .where(eq(targetHealthCheck.siteId, siteId)); const { tcpTargets, udpTargets } = allTargets.reduce( (acc, target) => { @@ -240,19 +255,14 @@ export async function buildTargetConfigurationForNewtClient(siteId: number) { { tcpTargets: [] as string[], udpTargets: [] as string[] } ); - const healthCheckTargets = allTargets.map((target) => { + const healthCheckTargets = allHealthChecks.map((target) => { // make sure the stuff is defined - if ( - !target.hcPath || - !target.hcHostname || - !target.hcPort || - !target.hcInterval || - !target.hcMethod - ) { - // logger.debug( - // `Skipping adding target health check ${target.targetId} due to missing health check fields` - // ); - return null; // Skip targets with missing health check fields + const isTCP = target.hcMode?.toLowerCase() === "tcp"; + if (!target.hcHostname || !target.hcPort || !target.hcInterval) { + return null; + } + if (!isTCP && (!target.hcPath || !target.hcMethod)) { + return null; } // parse headers @@ -269,7 +279,7 @@ export async function buildTargetConfigurationForNewtClient(siteId: number) { } return { - id: target.targetId, + id: target.targetHealthCheckId, hcEnabled: target.hcEnabled, hcPath: target.hcPath, hcScheme: target.hcScheme, @@ -280,9 +290,12 @@ export async function buildTargetConfigurationForNewtClient(siteId: number) { hcUnhealthyInterval: target.hcUnhealthyInterval, // in seconds hcTimeout: target.hcTimeout, // in seconds hcHeaders: hcHeadersSend, + hcFollowRedirects: target.hcFollowRedirects, hcMethod: target.hcMethod, hcTlsServerName: target.hcTlsServerName, - hcStatus: target.hcStatus + hcStatus: target.hcStatus, + hcHealthyThreshold: target.hcHealthyThreshold, + hcUnhealthyThreshold: target.hcUnhealthyThreshold }; }); diff --git a/server/routers/newt/handleNewtDisconnectingMessage.ts b/server/routers/newt/handleNewtDisconnectingMessage.ts index 02c5a95ac..302738f19 100644 --- a/server/routers/newt/handleNewtDisconnectingMessage.ts +++ b/server/routers/newt/handleNewtDisconnectingMessage.ts @@ -2,6 +2,7 @@ import { MessageHandler } from "@server/routers/ws"; import { db, Newt, sites } from "@server/db"; import { eq } from "drizzle-orm"; import logger from "@server/logger"; +import { fireSiteOfflineAlert } from "@server/lib/alerts"; /** * Handles disconnecting messages from sites to show disconnected in the ui @@ -24,12 +25,15 @@ export const handleNewtDisconnectingMessage: MessageHandler = async ( try { // Update the client's last ping timestamp - await db + const [site] = await db .update(sites) .set({ online: false }) - .where(eq(sites.siteId, newt.siteId)); + .where(eq(sites.siteId, newt.siteId)) + .returning(); + + await fireSiteOfflineAlert(site.orgId, site.siteId, site.name); } catch (error) { logger.error("Error handling disconnecting message", { error }); } diff --git a/server/routers/newt/handleGetConfigMessage.ts b/server/routers/newt/handleNewtGetConfigMessage.ts similarity index 92% rename from server/routers/newt/handleGetConfigMessage.ts rename to server/routers/newt/handleNewtGetConfigMessage.ts index 9c67f53ee..787151a5a 100644 --- a/server/routers/newt/handleGetConfigMessage.ts +++ b/server/routers/newt/handleNewtGetConfigMessage.ts @@ -10,7 +10,7 @@ import { convertTargetsIfNessicary } from "../client/targets"; import { canCompress } from "@server/lib/clientVersionChecks"; import config from "@server/lib/config"; -export const handleGetConfigMessage: MessageHandler = async (context) => { +export const handleNewtGetConfigMessage: MessageHandler = async (context) => { const { message, client, sendToClient } = context; const newt = client as Newt; @@ -56,7 +56,7 @@ export const handleGetConfigMessage: MessageHandler = async (context) => { if (existingSite.lastHolePunch && now - existingSite.lastHolePunch > 5) { logger.warn( - `Site last hole punch is too old; skipping this register. The site is failing to hole punch and identify its network address with the server. Can the client reach the server on UDP port ${config.getRawConfig().gerbil.clients_start_port}?` + `Site last hole punch is too old; skipping this register. The site is failing to hole punch and identify its network address with the server. Can the site reach the server on UDP port ${config.getRawConfig().gerbil.clients_start_port}?` ); return; } @@ -113,7 +113,7 @@ export const handleGetConfigMessage: MessageHandler = async (context) => { exitNode ); - const targetsToSend = await convertTargetsIfNessicary(newt.newtId, targets); + const targetsToSend = await convertTargetsIfNessicary(newt.newtId, targets); // for backward compatibility with old newt versions that don't support the new target format return { message: { diff --git a/server/routers/newt/handleNewtPingMessage.ts b/server/routers/newt/handleNewtPingMessage.ts index 32f665758..56b8a2a24 100644 --- a/server/routers/newt/handleNewtPingMessage.ts +++ b/server/routers/newt/handleNewtPingMessage.ts @@ -1,180 +1,12 @@ -import { db, newts, sites, targetHealthCheck, targets } from "@server/db"; -import { - hasActiveConnections, - getClientConfigVersion -} from "#dynamic/routers/ws"; +import { db, sites } from "@server/db"; +import { getClientConfigVersion } from "#dynamic/routers/ws"; import { MessageHandler } from "@server/routers/ws"; import { Newt } from "@server/db"; -import { eq, lt, isNull, and, or, ne, not } from "drizzle-orm"; +import { eq } from "drizzle-orm"; import logger from "@server/logger"; import { sendNewtSyncMessage } from "./sync"; import { recordPing } from "./pingAccumulator"; -// Track if the offline checker interval is running -let offlineCheckerInterval: NodeJS.Timeout | null = null; -const OFFLINE_CHECK_INTERVAL = 30 * 1000; // Check every 30 seconds -const OFFLINE_THRESHOLD_MS = 2 * 60 * 1000; // 2 minutes -const OFFLINE_THRESHOLD_BANDWIDTH_MS = 8 * 60 * 1000; // 8 minutes - -/** - * Starts the background interval that checks for newt sites that haven't - * pinged recently and marks them as offline. For backward compatibility, - * a site is only marked offline when there is no active WebSocket connection - * either — so older newt versions that don't send pings but remain connected - * continue to be treated as online. - */ -export const startNewtOfflineChecker = (): void => { - if (offlineCheckerInterval) { - return; // Already running - } - - offlineCheckerInterval = setInterval(async () => { - try { - const twoMinutesAgo = Math.floor( - (Date.now() - OFFLINE_THRESHOLD_MS) / 1000 - ); - - // Find all online newt-type sites that haven't pinged recently - // (or have never pinged at all). Join newts to obtain the newtId - // needed for the WebSocket connection check. - const staleSites = await db - .select({ - siteId: sites.siteId, - newtId: newts.newtId, - lastPing: sites.lastPing - }) - .from(sites) - .innerJoin(newts, eq(newts.siteId, sites.siteId)) - .where( - and( - eq(sites.online, true), - eq(sites.type, "newt"), - or( - lt(sites.lastPing, twoMinutesAgo), - isNull(sites.lastPing) - ) - ) - ); - - for (const staleSite of staleSites) { - // Backward-compatibility check: if the newt still has an - // active WebSocket connection (older clients that don't send - // pings), keep the site online. - const isConnected = await hasActiveConnections( - staleSite.newtId - ); - if (isConnected) { - logger.debug( - `Newt ${staleSite.newtId} has not pinged recently but is still connected via WebSocket — keeping site ${staleSite.siteId} online` - ); - continue; - } - - logger.info( - `Marking site ${staleSite.siteId} offline: newt ${staleSite.newtId} has no recent ping and no active WebSocket connection` - ); - - await db - .update(sites) - .set({ online: false }) - .where(eq(sites.siteId, staleSite.siteId)); - - const healthChecksOnSite = await db - .select() - .from(targetHealthCheck) - .innerJoin( - targets, - eq(targets.targetId, targetHealthCheck.targetId) - ) - .innerJoin(sites, eq(sites.siteId, targets.siteId)) - .where(eq(sites.siteId, staleSite.siteId)); - - for (const healthCheck of healthChecksOnSite) { - logger.info( - `Marking health check ${healthCheck.targetHealthCheck.targetHealthCheckId} offline due to site ${staleSite.siteId} being marked offline` - ); - await db - .update(targetHealthCheck) - .set({ hcHealth: "unknown" }) - .where( - eq( - targetHealthCheck.targetHealthCheckId, - healthCheck.targetHealthCheck - .targetHealthCheckId - ) - ); - } - } - - // this part only effects self hosted. Its not efficient but we dont expect people to have very many wireguard sites - // select all of the wireguard sites to evaluate if they need to be offline due to the last bandwidth update - const allWireguardSites = await db - .select({ - siteId: sites.siteId, - online: sites.online, - lastBandwidthUpdate: sites.lastBandwidthUpdate - }) - .from(sites) - .where( - and( - eq(sites.type, "wireguard"), - not(isNull(sites.lastBandwidthUpdate)) - ) - ); - - const wireguardOfflineThreshold = Math.floor( - (Date.now() - OFFLINE_THRESHOLD_BANDWIDTH_MS) / 1000 - ); - - // loop over each one. If its offline and there is a new update then mark it online. If its online and there is no update then mark it offline - for (const site of allWireguardSites) { - const lastBandwidthUpdate = - new Date(site.lastBandwidthUpdate!).getTime() / 1000; - if ( - lastBandwidthUpdate < wireguardOfflineThreshold && - site.online - ) { - logger.info( - `Marking wireguard site ${site.siteId} offline: no bandwidth update in over ${OFFLINE_THRESHOLD_BANDWIDTH_MS / 60000} minutes` - ); - - await db - .update(sites) - .set({ online: false }) - .where(eq(sites.siteId, site.siteId)); - } else if ( - lastBandwidthUpdate >= wireguardOfflineThreshold && - !site.online - ) { - logger.info( - `Marking wireguard site ${site.siteId} online: recent bandwidth update` - ); - - await db - .update(sites) - .set({ online: true }) - .where(eq(sites.siteId, site.siteId)); - } - } - } catch (error) { - logger.error("Error in newt offline checker interval", { error }); - } - }, OFFLINE_CHECK_INTERVAL); - - logger.debug("Started newt offline checker interval"); -}; - -/** - * Stops the background interval that checks for offline newt sites. - */ -export const stopNewtOfflineChecker = (): void => { - if (offlineCheckerInterval) { - clearInterval(offlineCheckerInterval); - offlineCheckerInterval = null; - logger.info("Stopped newt offline checker interval"); - } -}; - /** * Handles ping messages from newt clients. * diff --git a/server/routers/newt/handleNewtRegisterMessage.ts b/server/routers/newt/handleNewtRegisterMessage.ts index fce42caa3..f3902a35d 100644 --- a/server/routers/newt/handleNewtRegisterMessage.ts +++ b/server/routers/newt/handleNewtRegisterMessage.ts @@ -192,7 +192,7 @@ export const handleNewtRegisterMessage: MessageHandler = async (context) => { } const { tcpTargets, udpTargets, validHealthCheckTargets } = - await buildTargetConfigurationForNewtClient(siteId); + await buildTargetConfigurationForNewtClient(siteId, newtVersion); logger.debug( `Sending health check targets to newt ${newt.newtId}: ${JSON.stringify(validHealthCheckTargets)}` diff --git a/server/routers/newt/handleReceiveBandwidthMessage.ts b/server/routers/newt/handleReceiveBandwidthMessage.ts index f086333e7..2d5d99b09 100644 --- a/server/routers/newt/handleReceiveBandwidthMessage.ts +++ b/server/routers/newt/handleReceiveBandwidthMessage.ts @@ -88,7 +88,7 @@ export async function flushBandwidthToDb(): Promise { const currentTime = new Date().toISOString(); // Sort by publicKey for consistent lock ordering across concurrent - // writers — this is the same deadlock-prevention strategy used in the + // writers - this is the same deadlock-prevention strategy used in the // original per-message implementation. const sortedEntries = [...snapshot.entries()].sort(([a], [b]) => a.localeCompare(b) @@ -143,7 +143,7 @@ const flushTimer = setInterval(async () => { }, FLUSH_INTERVAL_MS); // Calling unref() means this timer will not keep the Node.js event loop alive -// on its own — the process can still exit normally when there is no other work +// on its own - the process can still exit normally when there is no other work // left. The graceful-shutdown path (see server/cleanup.ts) will call // flushBandwidthToDb() explicitly before process.exit(), so no data is lost. flushTimer.unref(); @@ -167,7 +167,7 @@ export const handleReceiveBandwidthMessage: MessageHandler = async ( // Accumulate the incoming data in memory; the periodic timer (and the // shutdown hook) will take care of writing it to the database. for (const { publicKey, bytesIn, bytesOut } of bandwidthData) { - // Skip peers that haven't transferred any data — writing zeros to the + // Skip peers that haven't transferred any data - writing zeros to the // database would be a no-op anyway. if (bytesIn <= 0 && bytesOut <= 0) { continue; diff --git a/server/routers/newt/handleRequestLogMessage.ts b/server/routers/newt/handleRequestLogMessage.ts new file mode 100644 index 000000000..190020ad1 --- /dev/null +++ b/server/routers/newt/handleRequestLogMessage.ts @@ -0,0 +1,9 @@ +import { MessageHandler } from "@server/routers/ws"; + +export async function flushRequestLogToDb(): Promise { + return; +} + +export const handleRequestLogMessage: MessageHandler = async (context) => { + return; +}; \ No newline at end of file diff --git a/server/routers/newt/index.ts b/server/routers/newt/index.ts index 33b5caf7c..368cdf636 100644 --- a/server/routers/newt/index.ts +++ b/server/routers/newt/index.ts @@ -2,11 +2,13 @@ export * from "./createNewt"; export * from "./getNewtToken"; export * from "./handleNewtRegisterMessage"; export * from "./handleReceiveBandwidthMessage"; -export * from "./handleGetConfigMessage"; +export * from "./handleNewtGetConfigMessage"; export * from "./handleSocketMessages"; export * from "./handleNewtPingRequestMessage"; export * from "./handleApplyBlueprintMessage"; export * from "./handleNewtPingMessage"; export * from "./handleNewtDisconnectingMessage"; export * from "./handleConnectionLogMessage"; +export * from "./handleRequestLogMessage"; export * from "./registerNewt"; +export * from "./offlineChecker"; diff --git a/server/routers/newt/offlineChecker.ts b/server/routers/newt/offlineChecker.ts new file mode 100644 index 000000000..426d80323 --- /dev/null +++ b/server/routers/newt/offlineChecker.ts @@ -0,0 +1,208 @@ +import { db, newts, sites, targetHealthCheck, targets, statusHistory } from "@server/db"; +import { + hasActiveConnections, +} from "#dynamic/routers/ws"; +import { eq, lt, isNull, and, or, ne, not } from "drizzle-orm"; +import logger from "@server/logger"; +import { fireSiteOfflineAlert, fireSiteOnlineAlert } from "#dynamic/lib/alerts"; + +// Track if the offline checker interval is running +let offlineCheckerInterval: NodeJS.Timeout | null = null; +const OFFLINE_CHECK_INTERVAL = 30 * 1000; // Check every 30 seconds +const OFFLINE_THRESHOLD_MS = 2 * 60 * 1000; // 2 minutes +const OFFLINE_THRESHOLD_BANDWIDTH_MS = 8 * 60 * 1000; // 8 minutes + +/** + * Starts the background interval that checks for newt sites that haven't + * pinged recently and marks them as offline. For backward compatibility, + * a site is only marked offline when there is no active WebSocket connection + * either - so older newt versions that don't send pings but remain connected + * continue to be treated as online. + */ +export const startNewtOfflineChecker = (): void => { + if (offlineCheckerInterval) { + return; // Already running + } + + offlineCheckerInterval = setInterval(async () => { + try { + const twoMinutesAgo = Math.floor( + (Date.now() - OFFLINE_THRESHOLD_MS) / 1000 + ); + + // Find all online newt-type sites that haven't pinged recently + // (or have never pinged at all). Join newts to obtain the newtId + // needed for the WebSocket connection check. + const staleSites = await db + .select({ + siteId: sites.siteId, + orgId: sites.orgId, + name: sites.name, + newtId: newts.newtId, + lastPing: sites.lastPing + }) + .from(sites) + .innerJoin(newts, eq(newts.siteId, sites.siteId)) + .where( + and( + eq(sites.online, true), + eq(sites.type, "newt"), + or( + lt(sites.lastPing, twoMinutesAgo), + isNull(sites.lastPing) + ) + ) + ); + + for (const staleSite of staleSites) { + // Backward-compatibility check: if the newt still has an + // active WebSocket connection (older clients that don't send + // pings), keep the site online. + const isConnected = await hasActiveConnections( + staleSite.newtId + ); + if (isConnected) { + logger.debug( + `Newt ${staleSite.newtId} has not pinged recently but is still connected via WebSocket - keeping site ${staleSite.siteId} online` + ); + continue; + } + + logger.info( + `Marking site ${staleSite.siteId} offline: newt ${staleSite.newtId} has no recent ping and no active WebSocket connection` + ); + + await db + .update(sites) + .set({ online: false }) + .where(eq(sites.siteId, staleSite.siteId)); + + await db.insert(statusHistory).values({ + entityType: "site", + entityId: staleSite.siteId, + orgId: staleSite.orgId, + status: "offline", + timestamp: Math.floor(Date.now() / 1000), + }).execute(); + + const healthChecksOnSite = await db + .select() + .from(targetHealthCheck) + .innerJoin( + targets, + eq(targets.targetId, targetHealthCheck.targetId) + ) + .innerJoin(sites, eq(sites.siteId, targets.siteId)) + .where(eq(sites.siteId, staleSite.siteId)); + + for (const healthCheck of healthChecksOnSite) { + logger.info( + `Marking health check ${healthCheck.targetHealthCheck.targetHealthCheckId} offline due to site ${staleSite.siteId} being marked offline` + ); + await db + .update(targetHealthCheck) + .set({ hcHealth: "unknown" }) + .where( + eq( + targetHealthCheck.targetHealthCheckId, + healthCheck.targetHealthCheck + .targetHealthCheckId + ) + ); + + // TODO: should we be firing an alert here when the health check goes to unknown? + } + + await fireSiteOfflineAlert(staleSite.orgId, staleSite.siteId, staleSite.name); + } + + // this part only effects self hosted. Its not efficient but we dont expect people to have very many wireguard sites + // select all of the wireguard sites to evaluate if they need to be offline due to the last bandwidth update + const allWireguardSites = await db + .select({ + siteId: sites.siteId, + orgId: sites.orgId, + name: sites.name, + online: sites.online, + lastBandwidthUpdate: sites.lastBandwidthUpdate + }) + .from(sites) + .where( + and( + eq(sites.type, "wireguard"), + not(isNull(sites.lastBandwidthUpdate)) + ) + ); + + const wireguardOfflineThreshold = Math.floor( + (Date.now() - OFFLINE_THRESHOLD_BANDWIDTH_MS) / 1000 + ); + + // loop over each one. If its offline and there is a new update then mark it online. If its online and there is no update then mark it offline + for (const site of allWireguardSites) { + const lastBandwidthUpdate = + new Date(site.lastBandwidthUpdate!).getTime() / 1000; + if ( + lastBandwidthUpdate < wireguardOfflineThreshold && + site.online + ) { + logger.info( + `Marking wireguard site ${site.siteId} offline: no bandwidth update in over ${OFFLINE_THRESHOLD_BANDWIDTH_MS / 60000} minutes` + ); + + await db + .update(sites) + .set({ online: false }) + .where(eq(sites.siteId, site.siteId)); + + await db.insert(statusHistory).values({ + entityType: "site", + entityId: site.siteId, + orgId: site.orgId, + status: "offline", + timestamp: Math.floor(Date.now() / 1000), + }).execute(); + + await fireSiteOfflineAlert(site.orgId, site.siteId, site.name); + } else if ( + lastBandwidthUpdate >= wireguardOfflineThreshold && + !site.online + ) { + logger.info( + `Marking wireguard site ${site.siteId} online: recent bandwidth update` + ); + + await db + .update(sites) + .set({ online: true }) + .where(eq(sites.siteId, site.siteId)); + + await db.insert(statusHistory).values({ + entityType: "site", + entityId: site.siteId, + orgId: site.orgId, + status: "online", + timestamp: Math.floor(Date.now() / 1000), + }).execute(); + + await fireSiteOnlineAlert(site.orgId, site.siteId, site.name); + } + } + } catch (error) { + logger.error("Error in newt offline checker interval", { error }); + } + }, OFFLINE_CHECK_INTERVAL); + + logger.debug("Started newt offline checker interval"); +}; + +/** + * Stops the background interval that checks for offline newt sites. + */ +export const stopNewtOfflineChecker = (): void => { + if (offlineCheckerInterval) { + clearInterval(offlineCheckerInterval); + offlineCheckerInterval = null; + logger.info("Stopped newt offline checker interval"); + } +}; diff --git a/server/routers/newt/pingAccumulator.ts b/server/routers/newt/pingAccumulator.ts index fe2cde216..9b2f04c8e 100644 --- a/server/routers/newt/pingAccumulator.ts +++ b/server/routers/newt/pingAccumulator.ts @@ -1,7 +1,8 @@ import { db } from "@server/db"; -import { sites, clients, olms } from "@server/db"; -import { inArray } from "drizzle-orm"; +import { sites, clients, olms, statusHistory } from "@server/db"; +import { and, eq, inArray } from "drizzle-orm"; import logger from "@server/logger"; +import { fireSiteOnlineAlert } from "#dynamic/lib/alerts"; /** * Ping Accumulator @@ -110,15 +111,51 @@ async function flushSitePingsToDb(): Promise { const siteIds = batch.map(([id]) => id); try { - await withRetry(async () => { - await db + const newlyOnlineSites = await withRetry(async () => { + // Only update sites that were offline - these are the + // offline→online transitions. .returning() gives us exactly + // the site IDs that changed state. + const transitioned = await db .update(sites) .set({ online: true, lastPing: maxTimestamp }) - .where(inArray(sites.siteId, siteIds)); + .where( + and( + inArray(sites.siteId, siteIds), + eq(sites.online, false) + ) + ) + .returning({ siteId: sites.siteId, orgId: sites.orgId, name: sites.name }); + + // Update lastPing for sites that were already online. + // After the update above, the newly-online sites now have + // online = true, so this catches all remaining sites in the + // batch and keeps lastPing current for them too. + await db + .update(sites) + .set({ lastPing: maxTimestamp }) + .where( + and( + inArray(sites.siteId, siteIds), + eq(sites.online, true) + ) + ); + + return transitioned; }, "flushSitePingsToDb"); + + for (const site of newlyOnlineSites) { + await db.insert(statusHistory).values({ + entityType: "site", + entityId: site.siteId, + orgId: site.orgId, + status: "online", + timestamp: Math.floor(Date.now() / 1000), + }).execute(); + await fireSiteOnlineAlert(site.orgId, site.siteId, site.name); + } } catch (error) { logger.error( `Failed to flush site ping batch (${batch.length} sites), re-queuing for next cycle`, @@ -219,7 +256,7 @@ async function flushClientPingsToDb(): Promise { } /** - * Flush everything — called by the interval timer and during shutdown. + * Flush everything - called by the interval timer and during shutdown. */ export async function flushPingsToDb(): Promise { await flushSitePingsToDb(); @@ -284,7 +321,7 @@ function isTransientError(error: any): boolean { return true; } - // PostgreSQL deadlock detected — always safe to retry (one winner guaranteed) + // PostgreSQL deadlock detected - always safe to retry (one winner guaranteed) if (code === "40P01" || message.includes("deadlock")) { return true; } @@ -344,7 +381,7 @@ export function startPingAccumulator(): void { // Don't prevent the process from exiting flushTimer.unref(); - logger.info( + logger.debug( `Ping accumulator started (flush interval: ${FLUSH_INTERVAL_MS}ms)` ); } diff --git a/server/routers/newt/registerNewt.ts b/server/routers/newt/registerNewt.ts index de68ab2de..cc53e48df 100644 --- a/server/routers/newt/registerNewt.ts +++ b/server/routers/newt/registerNewt.ts @@ -249,7 +249,7 @@ export async function registerNewt( dateCreated: moment().toISOString() }); - // Consume the provisioning key — cascade removes siteProvisioningKeyOrg + // Consume the provisioning key - cascade removes siteProvisioningKeyOrg await trx .update(siteProvisioningKeys) .set({ diff --git a/server/routers/newt/targets.ts b/server/routers/newt/targets.ts index 6a523ebe9..25b520854 100644 --- a/server/routers/newt/targets.ts +++ b/server/routers/newt/targets.ts @@ -1,7 +1,6 @@ -import { Target, TargetHealthCheck, db, targetHealthCheck } from "@server/db"; +import { Target, TargetHealthCheck } from "@server/db"; import { sendToClient } from "#dynamic/routers/ws"; import logger from "@server/logger"; -import { eq, inArray } from "drizzle-orm"; import { canCompress } from "@server/lib/clientVersionChecks"; export async function addTargets( @@ -18,17 +17,23 @@ export async function addTargets( }:${target.port}`; }); - await sendToClient(newtId, { - type: `newt/${protocol}/add`, - data: { - targets: payloadTargets - } - }, { incrementConfigVersion: true, compress: canCompress(version, "newt") }); + await sendToClient( + newtId, + { + type: `newt/${protocol}/add`, + data: { + targets: payloadTargets + } + }, + { incrementConfigVersion: true, compress: canCompress(version, "newt") } + ); // Create a map for quick lookup const healthCheckMap = new Map(); healthCheckData.forEach((hc) => { - healthCheckMap.set(hc.targetId, hc); + if (hc.targetId !== null) { + healthCheckMap.set(hc.targetId, hc); + } }); const healthCheckTargets = targets.map((target) => { @@ -43,17 +48,18 @@ export async function addTargets( } // Ensure all necessary fields are present - if ( - !hc.hcPath || - !hc.hcHostname || - !hc.hcPort || - !hc.hcInterval || - !hc.hcMethod - ) { + const isTCP = hc.hcMode?.toLowerCase() === "tcp"; + if (!hc.hcHostname || !hc.hcPort || !hc.hcInterval) { logger.debug( `Skipping target ${target.targetId} due to missing health check fields` ); - return null; // Skip targets with missing health check fields + return null; + } + if (!isTCP && (!hc.hcPath || !hc.hcMethod)) { + logger.debug( + `Skipping target ${target.targetId} due to missing HTTP health check fields` + ); + return null; } const hcHeadersParse = hc.hcHeaders ? JSON.parse(hc.hcHeaders) : null; @@ -77,7 +83,7 @@ export async function addTargets( } return { - id: target.targetId, + id: hc.targetHealthCheckId, hcEnabled: hc.hcEnabled, hcPath: hc.hcPath, hcScheme: hc.hcScheme, @@ -88,9 +94,12 @@ export async function addTargets( hcUnhealthyInterval: hc.hcUnhealthyInterval, // in seconds hcTimeout: hc.hcTimeout, // in seconds hcHeaders: hcHeadersSend, + hcFollowRedirects: hc.hcFollowRedirects, hcMethod: hc.hcMethod, hcStatus: hcStatus, - hcTlsServerName: hc.hcTlsServerName + hcTlsServerName: hc.hcTlsServerName, + hcHealthyThreshold: hc.hcHealthyThreshold, + hcUnhealthyThreshold: hc.hcUnhealthyThreshold }; }); @@ -99,12 +108,106 @@ export async function addTargets( (target) => target !== null ); - await sendToClient(newtId, { - type: `newt/healthcheck/add`, - data: { - targets: validHealthCheckTargets + await sendToClient( + newtId, + { + type: `newt/healthcheck/add`, + data: { + targets: validHealthCheckTargets + } + }, + { incrementConfigVersion: true, compress: canCompress(version, "newt") } + ); +} + +export async function addStandaloneHealthCheck( + newtId: string, + healthCheck: TargetHealthCheck, + version?: string | null +) { + const isTCP = healthCheck.hcMode?.toLowerCase() === "tcp"; + if ( + !healthCheck.hcHostname || + !healthCheck.hcPort || + !healthCheck.hcInterval + ) { + logger.debug( + `Skipping standalone health check ${healthCheck.targetHealthCheckId} due to missing fields` + ); + return; + } + if (!isTCP && (!healthCheck.hcPath || !healthCheck.hcMethod)) { + logger.debug( + `Skipping standalone health check ${healthCheck.targetHealthCheckId} due to missing HTTP health check fields` + ); + return; + } + + const hcHeadersParse = healthCheck.hcHeaders + ? JSON.parse(healthCheck.hcHeaders) + : null; + const hcHeadersSend: { [key: string]: string } = {}; + if (hcHeadersParse) { + hcHeadersParse.forEach((header: { name: string; value: string }) => { + hcHeadersSend[header.name] = header.value; + }); + } + + let hcStatus: number | undefined = undefined; + if (healthCheck.hcStatus) { + const parsedStatus = parseInt(healthCheck.hcStatus.toString()); + if (!isNaN(parsedStatus)) { + hcStatus = parsedStatus; } - }, { incrementConfigVersion: true, compress: canCompress(version, "newt") }); + } + + await sendToClient( + newtId, + { + type: `newt/healthcheck/add`, + data: { + targets: [ + { + id: healthCheck.targetHealthCheckId, + hcEnabled: healthCheck.hcEnabled, + hcPath: healthCheck.hcPath, + hcScheme: healthCheck.hcScheme, + hcMode: healthCheck.hcMode, + hcHostname: healthCheck.hcHostname, + hcPort: healthCheck.hcPort, + hcInterval: healthCheck.hcInterval, + hcUnhealthyInterval: healthCheck.hcUnhealthyInterval, + hcTimeout: healthCheck.hcTimeout, + hcHeaders: hcHeadersSend, + hcFollowRedirects: healthCheck.hcFollowRedirects, + hcMethod: healthCheck.hcMethod, + hcStatus: hcStatus, + hcTlsServerName: healthCheck.hcTlsServerName, + hcHealthyThreshold: healthCheck.hcHealthyThreshold, + hcUnhealthyThreshold: healthCheck.hcUnhealthyThreshold + } + ] + } + }, + { incrementConfigVersion: true, compress: canCompress(version, "newt") } + ); +} + +export async function removeStandaloneHealthCheck( + newtId: string, + healthCheckId: number, + version?: string | null +) { + await sendToClient( + newtId, + { + type: `newt/healthcheck/remove`, + data: { + ids: [healthCheckId] + } + }, + { incrementConfigVersion: true, compress: canCompress(version, "newt") } + ); } export async function removeTargets( @@ -120,21 +223,29 @@ export async function removeTargets( }:${target.port}`; }); - await sendToClient(newtId, { - type: `newt/${protocol}/remove`, - data: { - targets: payloadTargets - } - }, { incrementConfigVersion: true }); + await sendToClient( + newtId, + { + type: `newt/${protocol}/remove`, + data: { + targets: payloadTargets + } + }, + { incrementConfigVersion: true } + ); const healthCheckTargets = targets.map((target) => { return target.targetId; }); - await sendToClient(newtId, { - type: `newt/healthcheck/remove`, - data: { - ids: healthCheckTargets - } - }, { incrementConfigVersion: true, compress: canCompress(version, "newt") }); + await sendToClient( + newtId, + { + type: `newt/healthcheck/remove`, + data: { + ids: healthCheckTargets + } + }, + { incrementConfigVersion: true, compress: canCompress(version, "newt") } + ); } diff --git a/server/routers/olm/buildConfiguration.ts b/server/routers/olm/buildConfiguration.ts index bc2611b1c..4182725d3 100644 --- a/server/routers/olm/buildConfiguration.ts +++ b/server/routers/olm/buildConfiguration.ts @@ -4,6 +4,8 @@ import { clientSitesAssociationsCache, db, exitNodes, + networks, + siteNetworks, siteResources, sites } from "@server/db"; @@ -59,9 +61,17 @@ export async function buildSiteConfigurationForOlmClient( clientSiteResourcesAssociationsCache.siteResourceId ) ) + .innerJoin( + networks, + eq(siteResources.networkId, networks.networkId) + ) + .innerJoin( + siteNetworks, + eq(networks.networkId, siteNetworks.networkId) + ) .where( and( - eq(siteResources.siteId, site.siteId), + eq(siteNetworks.siteId, site.siteId), eq( clientSiteResourcesAssociationsCache.clientId, client.clientId @@ -69,6 +79,7 @@ export async function buildSiteConfigurationForOlmClient( ) ); + if (jitMode) { // Add site configuration to the array siteConfigurations.push({ diff --git a/server/routers/olm/handleOlmPingMessage.ts b/server/routers/olm/handleOlmPingMessage.ts index 0f520b234..0e18c7f5b 100644 --- a/server/routers/olm/handleOlmPingMessage.ts +++ b/server/routers/olm/handleOlmPingMessage.ts @@ -1,104 +1,17 @@ -import { disconnectClient, getClientConfigVersion } from "#dynamic/routers/ws"; +import { getClientConfigVersion } from "#dynamic/routers/ws"; import { db } from "@server/db"; import { MessageHandler } from "@server/routers/ws"; -import { clients, olms, Olm } from "@server/db"; -import { eq, lt, isNull, and, or } from "drizzle-orm"; +import { clients, Olm } from "@server/db"; +import { eq } from "drizzle-orm"; import { recordClientPing } from "@server/routers/newt/pingAccumulator"; import logger from "@server/logger"; import { validateSessionToken } from "@server/auth/sessions/app"; import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy"; -import { sendTerminateClient } from "../client/terminate"; import { encodeHexLowerCase } from "@oslojs/encoding"; import { sha256 } from "@oslojs/crypto/sha2"; import { sendOlmSyncMessage } from "./sync"; -import { OlmErrorCodes } from "./error"; import { handleFingerprintInsertion } from "./fingerprintingUtils"; -// Track if the offline checker interval is running -let offlineCheckerInterval: NodeJS.Timeout | null = null; -const OFFLINE_CHECK_INTERVAL = 30 * 1000; // Check every 30 seconds -const OFFLINE_THRESHOLD_MS = 2 * 60 * 1000; // 2 minutes - -/** - * Starts the background interval that checks for clients that haven't pinged recently - * and marks them as offline - */ -export const startOlmOfflineChecker = (): void => { - if (offlineCheckerInterval) { - return; // Already running - } - - offlineCheckerInterval = setInterval(async () => { - try { - const twoMinutesAgo = Math.floor( - (Date.now() - OFFLINE_THRESHOLD_MS) / 1000 - ); - - // TODO: WE NEED TO MAKE SURE THIS WORKS WITH DISTRIBUTED NODES ALL DOING THE SAME THING - - // Find clients that haven't pinged in the last 2 minutes and mark them as offline - const offlineClients = await db - .update(clients) - .set({ online: false }) - .where( - and( - eq(clients.online, true), - or( - lt(clients.lastPing, twoMinutesAgo), - isNull(clients.lastPing) - ) - ) - ) - .returning(); - - for (const offlineClient of offlineClients) { - logger.info( - `Kicking offline olm client ${offlineClient.clientId} due to inactivity` - ); - - if (!offlineClient.olmId) { - logger.warn( - `Offline client ${offlineClient.clientId} has no olmId, cannot disconnect` - ); - continue; - } - - // Send a disconnect message to the client if connected - try { - await sendTerminateClient( - offlineClient.clientId, - OlmErrorCodes.TERMINATED_INACTIVITY, - offlineClient.olmId - ); // terminate first - // wait a moment to ensure the message is sent - await new Promise((resolve) => setTimeout(resolve, 1000)); - await disconnectClient(offlineClient.olmId); - } catch (error) { - logger.error( - `Error sending disconnect to offline olm ${offlineClient.clientId}`, - { error } - ); - } - } - } catch (error) { - logger.error("Error in offline checker interval", { error }); - } - }, OFFLINE_CHECK_INTERVAL); - - logger.debug("Started offline checker interval"); -}; - -/** - * Stops the background interval that checks for offline clients - */ -export const stopOlmOfflineChecker = (): void => { - if (offlineCheckerInterval) { - clearInterval(offlineCheckerInterval); - offlineCheckerInterval = null; - logger.info("Stopped offline checker interval"); - } -}; - /** * Handles ping messages from clients and responds with pong */ diff --git a/server/routers/olm/handleOlmRegisterMessage.ts b/server/routers/olm/handleOlmRegisterMessage.ts index 01495de3b..a4a62973d 100644 --- a/server/routers/olm/handleOlmRegisterMessage.ts +++ b/server/routers/olm/handleOlmRegisterMessage.ts @@ -17,7 +17,6 @@ import { getUserDeviceName } from "@server/db/names"; import { buildSiteConfigurationForOlmClient } from "./buildConfiguration"; import { OlmErrorCodes, sendOlmError } from "./error"; import { handleFingerprintInsertion } from "./fingerprintingUtils"; -import { Alias } from "@server/lib/ip"; import { build } from "@server/build"; import { canCompress } from "@server/lib/clientVersionChecks"; import config from "@server/lib/config"; diff --git a/server/routers/olm/handleOlmServerInitAddPeerHandshake.ts b/server/routers/olm/handleOlmServerInitAddPeerHandshake.ts index 54badb2dc..05a83a146 100644 --- a/server/routers/olm/handleOlmServerInitAddPeerHandshake.ts +++ b/server/routers/olm/handleOlmServerInitAddPeerHandshake.ts @@ -4,10 +4,12 @@ import { db, exitNodes, Site, - siteResources + siteNetworks, + siteResources, + sites } from "@server/db"; import { MessageHandler } from "@server/routers/ws"; -import { clients, Olm, sites } from "@server/db"; +import { clients, Olm } from "@server/db"; import { and, eq, or } from "drizzle-orm"; import logger from "@server/logger"; import { initPeerAddHandshake } from "./peers"; @@ -44,20 +46,31 @@ export const handleOlmServerInitAddPeerHandshake: MessageHandler = async ( const { siteId, resourceId, chainId } = message.data; - let site: Site | null = null; + const sendCancel = async () => { + await sendToClient( + olm.olmId, + { + type: "olm/wg/peer/chain/cancel", + data: { chainId } + }, + { incrementConfigVersion: false } + ).catch((error) => { + logger.warn(`Error sending message:`, error); + }); + }; + + let sitesToProcess: Site[] = []; + if (siteId) { - // get the site const [siteRes] = await db .select() .from(sites) .where(eq(sites.siteId, siteId)) .limit(1); if (siteRes) { - site = siteRes; + sitesToProcess = [siteRes]; } - } - - if (resourceId && !site) { + } else if (resourceId) { const resources = await db .select() .from(siteResources) @@ -72,27 +85,17 @@ export const handleOlmServerInitAddPeerHandshake: MessageHandler = async ( ); if (!resources || resources.length === 0) { - logger.error(`handleOlmServerPeerAddMessage: Resource not found`); - // cancel the request from the olm side to not keep doing this - await sendToClient( - olm.olmId, - { - type: "olm/wg/peer/chain/cancel", - data: { - chainId - } - }, - { incrementConfigVersion: false } - ).catch((error) => { - logger.warn(`Error sending message:`, error); - }); + logger.error( + `handleOlmServerInitAddPeerHandshake: Resource not found` + ); + await sendCancel(); return; } if (resources.length > 1) { // error but this should not happen because the nice id cant contain a dot and the alias has to have a dot and both have to be unique within the org so there should never be multiple matches logger.error( - `handleOlmServerPeerAddMessage: Multiple resources found matching the criteria` + `handleOlmServerInitAddPeerHandshake: Multiple resources found matching the criteria` ); return; } @@ -117,125 +120,120 @@ export const handleOlmServerInitAddPeerHandshake: MessageHandler = async ( if (currentResourceAssociationCaches.length === 0) { logger.error( - `handleOlmServerPeerAddMessage: Client ${client.clientId} does not have access to resource ${resource.siteResourceId}` + `handleOlmServerInitAddPeerHandshake: Client ${client.clientId} does not have access to resource ${resource.siteResourceId}` ); - // cancel the request from the olm side to not keep doing this - await sendToClient( - olm.olmId, - { - type: "olm/wg/peer/chain/cancel", - data: { - chainId - } - }, - { incrementConfigVersion: false } - ).catch((error) => { - logger.warn(`Error sending message:`, error); - }); + await sendCancel(); return; } - const siteIdFromResource = resource.siteId; - - // get the site - const [siteRes] = await db - .select() - .from(sites) - .where(eq(sites.siteId, siteIdFromResource)); - if (!siteRes) { + if (!resource.networkId) { logger.error( - `handleOlmServerPeerAddMessage: Site with ID ${site} not found` + `handleOlmServerInitAddPeerHandshake: Resource ${resource.siteResourceId} has no network` ); + await sendCancel(); return; } - site = siteRes; + // Get all sites associated with this resource's network via siteNetworks + const siteRows = await db + .select({ siteId: siteNetworks.siteId }) + .from(siteNetworks) + .where(eq(siteNetworks.networkId, resource.networkId)); + + if (!siteRows || siteRows.length === 0) { + logger.error( + `handleOlmServerInitAddPeerHandshake: No sites found for resource ${resource.siteResourceId}` + ); + await sendCancel(); + return; + } + + // Fetch full site objects for all network members + const foundSites = await Promise.all( + siteRows.map(async ({ siteId: sid }) => { + const [s] = await db + .select() + .from(sites) + .where(eq(sites.siteId, sid)) + .limit(1); + return s ?? null; + }) + ); + + sitesToProcess = foundSites.filter((s): s is Site => s !== null); } - if (!site) { - logger.error(`handleOlmServerPeerAddMessage: Site not found`); + if (sitesToProcess.length === 0) { + logger.error( + `handleOlmServerInitAddPeerHandshake: No sites to process` + ); + await sendCancel(); return; } - // check if the client can access this site using the cache - const currentSiteAssociationCaches = await db - .select() - .from(clientSitesAssociationsCache) - .where( - and( - eq(clientSitesAssociationsCache.clientId, client.clientId), - eq(clientSitesAssociationsCache.siteId, site.siteId) - ) - ); + let handshakeInitiated = false; - if (currentSiteAssociationCaches.length === 0) { - logger.error( - `handleOlmServerPeerAddMessage: Client ${client.clientId} does not have access to site ${site.siteId}` - ); - // cancel the request from the olm side to not keep doing this - await sendToClient( - olm.olmId, + for (const site of sitesToProcess) { + // Check if the client can access this site using the cache + const currentSiteAssociationCaches = await db + .select() + .from(clientSitesAssociationsCache) + .where( + and( + eq(clientSitesAssociationsCache.clientId, client.clientId), + eq(clientSitesAssociationsCache.siteId, site.siteId) + ) + ); + + if (currentSiteAssociationCaches.length === 0) { + logger.warn( + `handleOlmServerInitAddPeerHandshake: Client ${client.clientId} does not have access to site ${site.siteId}, skipping` + ); + continue; + } + + if (!site.exitNodeId) { + logger.error( + `handleOlmServerInitAddPeerHandshake: Site ${site.siteId} has no exit node, skipping` + ); + continue; + } + + const [exitNode] = await db + .select() + .from(exitNodes) + .where(eq(exitNodes.exitNodeId, site.exitNodeId)); + + if (!exitNode) { + logger.error( + `handleOlmServerInitAddPeerHandshake: Exit node not found for site ${site.siteId}, skipping` + ); + continue; + } + + // Trigger the peer add handshake - if the peer was already added this will be a no-op + await initPeerAddHandshake( + client.clientId, { - type: "olm/wg/peer/chain/cancel", - data: { - chainId + siteId: site.siteId, + exitNode: { + publicKey: exitNode.publicKey, + endpoint: exitNode.endpoint } }, - { incrementConfigVersion: false } - ).catch((error) => { - logger.warn(`Error sending message:`, error); - }); - return; - } - - if (!site.exitNodeId) { - logger.error( - `handleOlmServerPeerAddMessage: Site with ID ${site.siteId} has no exit node` - ); - // cancel the request from the olm side to not keep doing this - await sendToClient( olm.olmId, - { - type: "olm/wg/peer/chain/cancel", - data: { - chainId - } - }, - { incrementConfigVersion: false } - ).catch((error) => { - logger.warn(`Error sending message:`, error); - }); - return; - } - - // get the exit node from the side - const [exitNode] = await db - .select() - .from(exitNodes) - .where(eq(exitNodes.exitNodeId, site.exitNodeId)); - - if (!exitNode) { - logger.error( - `handleOlmServerPeerAddMessage: Site with ID ${site.siteId} has no exit node` + chainId ); - return; + + handshakeInitiated = true; } - // also trigger the peer add handshake in case the peer was not already added to the olm and we need to hole punch - // if it has already been added this will be a no-op - await initPeerAddHandshake( - // this will kick off the add peer process for the client - client.clientId, - { - siteId: site.siteId, - exitNode: { - publicKey: exitNode.publicKey, - endpoint: exitNode.endpoint - } - }, - olm.olmId, - chainId - ); + if (!handshakeInitiated) { + logger.error( + `handleOlmServerInitAddPeerHandshake: No accessible sites with valid exit nodes found, cancelling chain` + ); + await sendCancel(); + } return; }; diff --git a/server/routers/olm/handleOlmServerPeerAddMessage.ts b/server/routers/olm/handleOlmServerPeerAddMessage.ts index 64284f493..5f46ea84c 100644 --- a/server/routers/olm/handleOlmServerPeerAddMessage.ts +++ b/server/routers/olm/handleOlmServerPeerAddMessage.ts @@ -1,43 +1,25 @@ import { - Client, clientSiteResourcesAssociationsCache, db, - ExitNode, - Org, - orgs, - roleClients, - roles, + networks, + siteNetworks, siteResources, - Transaction, - userClients, - userOrgs, - users } from "@server/db"; import { MessageHandler } from "@server/routers/ws"; import { clients, clientSitesAssociationsCache, - exitNodes, Olm, - olms, sites } from "@server/db"; import { and, eq, inArray, isNotNull, isNull } from "drizzle-orm"; -import { addPeer, deletePeer } from "../newt/peers"; import logger from "@server/logger"; -import { listExitNodes } from "#dynamic/lib/exitNodes"; import { generateAliasConfig, - getNextAvailableClientSubnet } from "@server/lib/ip"; import { generateRemoteSubnets } from "@server/lib/ip"; -import { rebuildClientAssociationsFromClient } from "@server/lib/rebuildClientAssociations"; -import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy"; -import { validateSessionToken } from "@server/auth/sessions/app"; -import config from "@server/lib/config"; import { addPeer as newtAddPeer, - deletePeer as newtDeletePeer } from "@server/routers/newt/peers"; export const handleOlmServerPeerAddMessage: MessageHandler = async ( @@ -153,13 +135,21 @@ export const handleOlmServerPeerAddMessage: MessageHandler = async ( clientSiteResourcesAssociationsCache.siteResourceId ) ) - .where( + .innerJoin( + networks, + eq(siteResources.networkId, networks.networkId) + ) + .innerJoin( + siteNetworks, and( - eq(siteResources.siteId, site.siteId), - eq( - clientSiteResourcesAssociationsCache.clientId, - client.clientId - ) + eq(networks.networkId, siteNetworks.networkId), + eq(siteNetworks.siteId, site.siteId) + ) + ) + .where( + eq( + clientSiteResourcesAssociationsCache.clientId, + client.clientId ) ); diff --git a/server/routers/olm/index.ts b/server/routers/olm/index.ts index 322428572..5c151a8cf 100644 --- a/server/routers/olm/index.ts +++ b/server/routers/olm/index.ts @@ -12,3 +12,4 @@ export * from "./handleOlmUnRelayMessage"; export * from "./recoverOlmWithFingerprint"; export * from "./handleOlmDisconnectingMessage"; export * from "./handleOlmServerInitAddPeerHandshake"; +export * from "./offlineChecker"; diff --git a/server/routers/olm/offlineChecker.ts b/server/routers/olm/offlineChecker.ts new file mode 100644 index 000000000..7dd06a29c --- /dev/null +++ b/server/routers/olm/offlineChecker.ts @@ -0,0 +1,92 @@ +import { disconnectClient, getClientConfigVersion } from "#dynamic/routers/ws"; +import { db } from "@server/db"; +import { clients } from "@server/db"; +import { eq, lt, isNull, and, or } from "drizzle-orm"; +import logger from "@server/logger"; +import { sendTerminateClient } from "../client/terminate"; +import { OlmErrorCodes } from "./error"; + +// Track if the offline checker interval is running +let offlineCheckerInterval: NodeJS.Timeout | null = null; +const OFFLINE_CHECK_INTERVAL = 30 * 1000; // Check every 30 seconds +const OFFLINE_THRESHOLD_MS = 2 * 60 * 1000; // 2 minutes + +/** + * Starts the background interval that checks for clients that haven't pinged recently + * and marks them as offline + */ +export const startOlmOfflineChecker = (): void => { + if (offlineCheckerInterval) { + return; // Already running + } + + offlineCheckerInterval = setInterval(async () => { + try { + const twoMinutesAgo = Math.floor( + (Date.now() - OFFLINE_THRESHOLD_MS) / 1000 + ); + + // TODO: WE NEED TO MAKE SURE THIS WORKS WITH DISTRIBUTED NODES ALL DOING THE SAME THING + + // Find clients that haven't pinged in the last 2 minutes and mark them as offline + const offlineClients = await db + .update(clients) + .set({ online: false }) + .where( + and( + eq(clients.online, true), + or( + lt(clients.lastPing, twoMinutesAgo), + isNull(clients.lastPing) + ) + ) + ) + .returning(); + + for (const offlineClient of offlineClients) { + logger.info( + `Kicking offline olm client ${offlineClient.clientId} due to inactivity` + ); + + if (!offlineClient.olmId) { + logger.warn( + `Offline client ${offlineClient.clientId} has no olmId, cannot disconnect` + ); + continue; + } + + // Send a disconnect message to the client if connected + try { + await sendTerminateClient( + offlineClient.clientId, + OlmErrorCodes.TERMINATED_INACTIVITY, + offlineClient.olmId + ); // terminate first + // wait a moment to ensure the message is sent + await new Promise((resolve) => setTimeout(resolve, 1000)); + await disconnectClient(offlineClient.olmId); + } catch (error) { + logger.error( + `Error sending disconnect to offline olm ${offlineClient.clientId}`, + { error } + ); + } + } + } catch (error) { + logger.error("Error in offline checker interval", { error }); + } + }, OFFLINE_CHECK_INTERVAL); + + logger.debug("Started offline checker interval"); +}; + +/** + * Stops the background interval that checks for offline clients + */ +export const stopOlmOfflineChecker = (): void => { + if (offlineCheckerInterval) { + clearInterval(offlineCheckerInterval); + offlineCheckerInterval = null; + logger.info("Stopped offline checker interval"); + } +}; diff --git a/server/routers/org/createOrg.ts b/server/routers/org/createOrg.ts index 88f76c29c..5fccbcd1f 100644 --- a/server/routers/org/createOrg.ts +++ b/server/routers/org/createOrg.ts @@ -12,7 +12,9 @@ import { userOrgRoles, userOrgs, users, - actions + actions, + customers, + subscriptions } from "@server/db"; import response from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; @@ -31,6 +33,7 @@ import { calculateUserClientsForOrgs } from "@server/lib/calculateUserClientsFor import { doCidrsOverlap } from "@server/lib/ip"; import { generateCA } from "@server/lib/sshCA"; import { encrypt } from "@server/lib/crypto"; +import { generateId } from "@server/auth/sessions/app"; const validOrgIdRegex = /^[a-z0-9_]+(-[a-z0-9_]+)*$/; diff --git a/server/routers/resource/getStatusHistory.ts b/server/routers/resource/getStatusHistory.ts new file mode 100644 index 000000000..9aa548624 --- /dev/null +++ b/server/routers/resource/getStatusHistory.ts @@ -0,0 +1,93 @@ +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db, statusHistory } from "@server/db"; +import { and, eq, gte, asc } from "drizzle-orm"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { + computeBuckets, + statusHistoryQuerySchema, + StatusHistoryResponse +} from "@server/lib/statusHistory"; + +const resourceParamsSchema = z.object({ + resourceId: z.string().transform((v) => parseInt(v, 10)) +}); + +export async function getResourceStatusHistory( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = resourceParamsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + const parsedQuery = statusHistoryQuerySchema.safeParse(req.query); + if (!parsedQuery.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedQuery.error).toString() + ) + ); + } + + const entityType = "resource"; + const entityId = parsedParams.data.resourceId; + const { days } = parsedQuery.data; + + const nowSec = Math.floor(Date.now() / 1000); + const startSec = nowSec - days * 86400; + + const events = await db + .select() + .from(statusHistory) + .where( + and( + eq(statusHistory.entityType, entityType), + eq(statusHistory.entityId, entityId), + gte(statusHistory.timestamp, startSec) + ) + ) + .orderBy(asc(statusHistory.timestamp)); + + const { buckets, totalDowntime } = computeBuckets(events, days); + const totalWindow = days * 86400; + const overallUptime = + totalWindow > 0 + ? Math.max( + 0, + ((totalWindow - totalDowntime) / totalWindow) * 100 + ) + : 100; + + return response(res, { + data: { + entityType, + entityId, + days: buckets, + overallUptimePercent: Math.round(overallUptime * 100) / 100, + totalDowntimeSeconds: totalDowntime + }, + success: true, + error: false, + message: "Status history retrieved successfully", + status: HttpCode.OK + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} diff --git a/server/routers/resource/getUserResources.ts b/server/routers/resource/getUserResources.ts index 802fffb1b..1722a7993 100644 --- a/server/routers/resource/getUserResources.ts +++ b/server/routers/resource/getUserResources.ts @@ -145,7 +145,7 @@ export async function getUserResources( niceId: string; destination: string; mode: string; - protocol: string | null; + scheme: string | null; enabled: boolean; alias: string | null; aliasAddress: string | null; @@ -158,7 +158,7 @@ export async function getUserResources( niceId: siteResources.niceId, destination: siteResources.destination, mode: siteResources.mode, - protocol: siteResources.protocol, + scheme: siteResources.scheme, enabled: siteResources.enabled, alias: siteResources.alias, aliasAddress: siteResources.aliasAddress @@ -242,7 +242,7 @@ export async function getUserResources( name: siteResource.name, destination: siteResource.destination, mode: siteResource.mode, - protocol: siteResource.protocol, + protocol: siteResource.scheme, enabled: siteResource.enabled, alias: siteResource.alias, aliasAddress: siteResource.aliasAddress, @@ -291,7 +291,7 @@ export type GetUserResourcesResponse = { enabled: boolean; alias: string | null; aliasAddress: string | null; - type: 'site'; + type: "site"; }>; }; }; diff --git a/server/routers/resource/index.ts b/server/routers/resource/index.ts index 12e98a70d..6a259d7fe 100644 --- a/server/routers/resource/index.ts +++ b/server/routers/resource/index.ts @@ -32,3 +32,4 @@ export * from "./addUserToResource"; export * from "./removeUserFromResource"; export * from "./listAllResourceNames"; export * from "./removeEmailFromResourceWhitelist"; +export * from "./getStatusHistory"; diff --git a/server/routers/role/listRoles.ts b/server/routers/role/listRoles.ts index f1b057a11..ba46e40c4 100644 --- a/server/routers/role/listRoles.ts +++ b/server/routers/role/listRoles.ts @@ -3,34 +3,68 @@ import response from "@server/lib/response"; import logger from "@server/logger"; import { OpenAPITags, registry } from "@server/openApi"; import HttpCode from "@server/types/HttpCode"; -import { and, eq, inArray, sql } from "drizzle-orm"; +import { and, asc, desc, eq, inArray, like, sql } from "drizzle-orm"; import { ActionsEnum } from "@server/auth/actions"; import { NextFunction, Request, Response } from "express"; import createHttpError from "http-errors"; import { object, z } from "zod"; import { fromError } from "zod-validation-error"; +import type { PaginatedResponse } from "@server/types/Pagination"; const listRolesParamsSchema = z.strictObject({ orgId: z.string() }); const listRolesSchema = z.object({ - limit: z - .string() + pageSize: z.coerce + .number() // for prettier formatting + .int() + .positive() .optional() - .default("1000") - .transform(Number) - .pipe(z.int().nonnegative()), - offset: z - .string() + .catch(20) + .default(20) + .openapi({ + type: "integer", + default: 20, + description: "Number of items per page" + }), + page: z.coerce + .number() // for prettier formatting + .int() + .min(0) .optional() - .default("0") - .transform(Number) - .pipe(z.int().nonnegative()) + .catch(1) + .default(1) + .openapi({ + type: "integer", + default: 1, + description: "Page number to retrieve" + }), + query: z.string().optional(), + sort_by: z + .enum(["name"]) + .optional() + .catch(undefined) + .openapi({ + type: "string", + enum: ["name"], + description: "Field to sort by" + }), + order: z + .enum(["asc", "desc"]) + .optional() + .default("asc") + .catch("asc") + .openapi({ + type: "string", + enum: ["asc", "desc"], + default: "asc", + description: "Sort order" + }) }); -async function queryRoles(orgId: string, limit: number, offset: number) { - return await db +function queryRolesBase() { + return db .select({ roleId: roles.roleId, orgId: roles.orgId, @@ -45,20 +79,15 @@ async function queryRoles(orgId: string, limit: number, offset: number) { sshUnixGroups: roles.sshUnixGroups }) .from(roles) - .leftJoin(orgs, eq(roles.orgId, orgs.orgId)) - .where(eq(roles.orgId, orgId)) - .limit(limit) - .offset(offset); + .leftJoin(orgs, eq(roles.orgId, orgs.orgId)); + // .where(eq(roles.orgId, orgId)) + // .limit(limit) + // .offset(offset); } -export type ListRolesResponse = { - roles: NonNullable>>; - pagination: { - total: number; - limit: number; - offset: number; - }; -}; +export type ListRolesResponse = PaginatedResponse<{ + roles: NonNullable>>; +}>; registry.registerPath({ method: "get", @@ -88,7 +117,7 @@ export async function listRoles( ); } - const { limit, offset } = parsedQuery.data; + const { page, pageSize, query, sort_by, order } = parsedQuery.data; const parsedParams = listRolesParamsSchema.safeParse(req.params); if (!parsedParams.success) { @@ -102,14 +131,36 @@ export async function listRoles( const { orgId } = parsedParams.data; - const countQuery: any = db - .select({ count: sql`cast(count(*) as integer)` }) - .from(roles) - .where(eq(roles.orgId, orgId)); + const conditions = [and(eq(roles.orgId, orgId))]; - const rolesList = await queryRoles(orgId, limit, offset); - const totalCountResult = await countQuery; - const totalCount = totalCountResult[0].count; + if (query) { + conditions.push( + like(sql`LOWER(${roles.name})`, "%" + query.toLowerCase() + "%") + ); + } + + const countQuery = db.$count( + queryRolesBase() + .where(and(...conditions)) + .as("filtered_roles") + ); + + const rolesListQuery = queryRolesBase() + .where(and(...conditions)) + .limit(pageSize) + .offset(pageSize * (page - 1)) + .orderBy( + sort_by + ? order === "asc" + ? asc(roles[sort_by]) + : desc(roles[sort_by]) + : asc(roles.name) + ); + + const [totalCount, rolesList] = await Promise.all([ + countQuery, + rolesListQuery + ]); let rolesWithAllowSsh = rolesList; if (rolesList.length > 0) { @@ -135,8 +186,8 @@ export async function listRoles( roles: rolesWithAllowSsh, pagination: { total: totalCount, - limit, - offset + page, + pageSize } }, success: true, diff --git a/server/routers/site/deleteSite.ts b/server/routers/site/deleteSite.ts index 587572535..344f6b4e3 100644 --- a/server/routers/site/deleteSite.ts +++ b/server/routers/site/deleteSite.ts @@ -1,6 +1,6 @@ import { Request, Response, NextFunction } from "express"; import { z } from "zod"; -import { db, Site, siteResources } from "@server/db"; +import { db, Site, siteNetworks, siteResources } from "@server/db"; import { newts, newtSessions, sites } from "@server/db"; import { eq } from "drizzle-orm"; import response from "@server/lib/response"; @@ -71,18 +71,23 @@ export async function deleteSite( await deletePeer(site.exitNodeId!, site.pubKey); } } else if (site.type == "newt") { - // delete all of the site resources on this site - const siteResourcesOnSite = trx - .delete(siteResources) - .where(eq(siteResources.siteId, siteId)) - .returning(); + const networks = await trx + .select({ networkId: siteNetworks.networkId }) + .from(siteNetworks) + .where(eq(siteNetworks.siteId, siteId)); // loop through them - for (const removedSiteResource of await siteResourcesOnSite) { - await rebuildClientAssociationsFromSiteResource( - removedSiteResource, - trx - ); + for (const network of await networks) { + const [siteResource] = await trx + .select() + .from(siteResources) + .where(eq(siteResources.networkId, network.networkId)); + if (siteResource) { + await rebuildClientAssociationsFromSiteResource( + siteResource, + trx + ); + } } // get the newt on the site by querying the newt table for siteId diff --git a/server/routers/site/getStatusHistory.ts b/server/routers/site/getStatusHistory.ts new file mode 100644 index 000000000..f1717c8a9 --- /dev/null +++ b/server/routers/site/getStatusHistory.ts @@ -0,0 +1,93 @@ +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import { db, statusHistory } from "@server/db"; +import { and, eq, gte, asc } from "drizzle-orm"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import logger from "@server/logger"; +import { fromError } from "zod-validation-error"; +import { + computeBuckets, + statusHistoryQuerySchema, + StatusHistoryResponse +} from "@server/lib/statusHistory"; + +const siteParamsSchema = z.object({ + siteId: z.string().transform((v) => parseInt(v, 10)) +}); + +export async function getSiteStatusHistory( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedParams = siteParamsSchema.safeParse(req.params); + if (!parsedParams.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedParams.error).toString() + ) + ); + } + const parsedQuery = statusHistoryQuerySchema.safeParse(req.query); + if (!parsedQuery.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedQuery.error).toString() + ) + ); + } + + const entityType = "site"; + const entityId = parsedParams.data.siteId; + const { days } = parsedQuery.data; + + const nowSec = Math.floor(Date.now() / 1000); + const startSec = nowSec - days * 86400; + + const events = await db + .select() + .from(statusHistory) + .where( + and( + eq(statusHistory.entityType, entityType), + eq(statusHistory.entityId, entityId), + gte(statusHistory.timestamp, startSec) + ) + ) + .orderBy(asc(statusHistory.timestamp)); + + const { buckets, totalDowntime } = computeBuckets(events, days); + const totalWindow = days * 86400; + const overallUptime = + totalWindow > 0 + ? Math.max( + 0, + ((totalWindow - totalDowntime) / totalWindow) * 100 + ) + : 100; + + return response(res, { + data: { + entityType, + entityId, + days: buckets, + overallUptimePercent: Math.round(overallUptime * 100) / 100, + totalDowntimeSeconds: totalDowntime + }, + success: true, + error: false, + message: "Status history retrieved successfully", + status: HttpCode.OK + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} diff --git a/server/routers/site/index.ts b/server/routers/site/index.ts index 3edf67c14..00fdeda91 100644 --- a/server/routers/site/index.ts +++ b/server/routers/site/index.ts @@ -1,4 +1,5 @@ export * from "./getSite"; +export * from "./getStatusHistory"; export * from "./createSite"; export * from "./deleteSite"; export * from "./updateSite"; diff --git a/server/routers/site/listSites.ts b/server/routers/site/listSites.ts index b65182908..88bb233ed 100644 --- a/server/routers/site/listSites.ts +++ b/server/routers/site/listSites.ts @@ -28,7 +28,7 @@ let staleNewtVersion: string | null = null; async function getLatestNewtVersion(): Promise { try { - const cachedVersion = await cache.get("latestNewtVersion"); + const cachedVersion = await cache.get("cache:latestNewtVersion"); if (cachedVersion) { return cachedVersion; } diff --git a/server/routers/siteResource/createSiteResource.ts b/server/routers/siteResource/createSiteResource.ts index 1485a4192..29fc8c213 100644 --- a/server/routers/siteResource/createSiteResource.ts +++ b/server/routers/siteResource/createSiteResource.ts @@ -5,6 +5,8 @@ import { orgs, roles, roleSiteResources, + siteNetworks, + networks, SiteResource, siteResources, sites, @@ -17,17 +19,18 @@ import { portRangeStringSchema } from "@server/lib/ip"; import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed"; -import { tierMatrix } from "@server/lib/billing/tierMatrix"; +import { TierFeature, tierMatrix } from "@server/lib/billing/tierMatrix"; import { rebuildClientAssociationsFromSiteResource } from "@server/lib/rebuildClientAssociations"; import response from "@server/lib/response"; import logger from "@server/logger"; import { OpenAPITags, registry } from "@server/openApi"; import HttpCode from "@server/types/HttpCode"; -import { and, eq } from "drizzle-orm"; +import { and, eq, inArray } from "drizzle-orm"; import { NextFunction, Request, Response } from "express"; import createHttpError from "http-errors"; import { z } from "zod"; import { fromError } from "zod-validation-error"; +import { validateAndConstructDomain } from "@server/lib/domainUtils"; const createSiteResourceParamsSchema = z.strictObject({ orgId: z.string() @@ -36,11 +39,14 @@ const createSiteResourceParamsSchema = z.strictObject({ const createSiteResourceSchema = z .strictObject({ name: z.string().min(1).max(255), - mode: z.enum(["host", "cidr", "port"]), - siteId: z.int(), + niceId: z.string().optional(), // protocol: z.enum(["tcp", "udp"]).optional(), + mode: z.enum(["host", "cidr", "http"]), + ssl: z.boolean().optional(), // only used for http mode + scheme: z.enum(["http", "https"]).optional(), + siteIds: z.array(z.int()), // proxyPort: z.int().positive().optional(), - // destinationPort: z.int().positive().optional(), + destinationPort: z.int().positive().optional(), destination: z.string().min(1), enabled: z.boolean().default(true), alias: z @@ -57,20 +63,24 @@ const createSiteResourceSchema = z udpPortRangeString: portRangeStringSchema, disableIcmp: z.boolean().optional(), authDaemonPort: z.int().positive().optional(), - authDaemonMode: z.enum(["site", "remote"]).optional() + authDaemonMode: z.enum(["site", "remote"]).optional(), + domainId: z.string().optional(), // only used for http mode, we need this to verify the alias is unique within the org + subdomain: z.string().optional() // only used for http mode, we need this to verify the alias is unique within the org }) .strict() .refine( (data) => { if (data.mode === "host") { - // Check if it's a valid IP address using zod (v4 or v6) - const isValidIP = z - // .union([z.ipv4(), z.ipv6()]) - .union([z.ipv4()]) // for now lets just do ipv4 until we verify ipv6 works everywhere - .safeParse(data.destination).success; + if (data.mode == "host") { + // Check if it's a valid IP address using zod (v4 or v6) + const isValidIP = z + // .union([z.ipv4(), z.ipv6()]) + .union([z.ipv4()]) // for now lets just do ipv4 until we verify ipv6 works everywhere + .safeParse(data.destination).success; - if (isValidIP) { - return true; + if (isValidIP) { + return true; + } } // Check if it's a valid domain (hostname pattern, TLD not required) @@ -105,6 +115,21 @@ const createSiteResourceSchema = z { message: "Destination must be a valid CIDR notation for cidr mode" } + ) + .refine( + (data) => { + if (data.mode !== "http") return true; + return ( + data.scheme !== undefined && + data.destinationPort !== undefined && + data.destinationPort >= 1 && + data.destinationPort <= 65535 + ); + }, + { + message: + "HTTP mode requires scheme (http or https) and a valid destination port" + } ); export type CreateSiteResourceBody = z.infer; @@ -159,13 +184,15 @@ export async function createSiteResource( const { orgId } = parsedParams.data; const { name, - siteId, + niceId, + siteIds, mode, - // protocol, + scheme, // proxyPort, - // destinationPort, + destinationPort, destination, enabled, + ssl, alias, userIds, roleIds, @@ -174,18 +201,36 @@ export async function createSiteResource( udpPortRangeString, disableIcmp, authDaemonPort, - authDaemonMode + authDaemonMode, + domainId, + subdomain } = parsedBody.data; + if (mode == "http") { + const hasHttpFeature = await isLicensedOrSubscribed( + orgId, + tierMatrix[TierFeature.HTTPPrivateResources] + ); + if (!hasHttpFeature) { + return next( + createHttpError( + HttpCode.FORBIDDEN, + "HTTP private resources are not included in your current plan. Please upgrade." + ) + ); + } + } + // Verify the site exists and belongs to the org - const [site] = await db + const sitesToAssign = await db .select() .from(sites) - .where(and(eq(sites.siteId, siteId), eq(sites.orgId, orgId))) - .limit(1); + .where(and(inArray(sites.siteId, siteIds), eq(sites.orgId, orgId))); - if (!site) { - return next(createHttpError(HttpCode.NOT_FOUND, "Site not found")); + if (sitesToAssign.length !== siteIds.length) { + return next( + createHttpError(HttpCode.NOT_FOUND, "Some site not found") + ); } const [org] = await db @@ -226,29 +271,50 @@ export async function createSiteResource( ); } - // // check if resource with same protocol and proxy port already exists (only for port mode) - // if (mode === "port" && protocol && proxyPort) { - // const [existingResource] = await db - // .select() - // .from(siteResources) - // .where( - // and( - // eq(siteResources.siteId, siteId), - // eq(siteResources.orgId, orgId), - // eq(siteResources.protocol, protocol), - // eq(siteResources.proxyPort, proxyPort) - // ) - // ) - // .limit(1); - // if (existingResource && existingResource.siteResourceId) { - // return next( - // createHttpError( - // HttpCode.CONFLICT, - // "A resource with the same protocol and proxy port already exists" - // ) - // ); - // } - // } + if (domainId && alias) { + // throw an error because we can only have one or the other + return next( + createHttpError( + HttpCode.BAD_REQUEST, + "Alias and domain cannot both be set. Please choose one or the other." + ) + ); + } + + let fullDomain: string | null = null; + let finalSubdomain: string | null = null; + if (domainId) { + // Validate domain and construct full domain + const domainResult = await validateAndConstructDomain( + domainId, + orgId, + subdomain + ); + + if (!domainResult.success) { + return next( + createHttpError(HttpCode.BAD_REQUEST, domainResult.error) + ); + } + + fullDomain = domainResult.fullDomain; + finalSubdomain = domainResult.subdomain; + + // make sure the full domain is unique + const existingResource = await db + .select() + .from(siteResources) + .where(eq(siteResources.fullDomain, fullDomain)); + + if (existingResource.length > 0) { + return next( + createHttpError( + HttpCode.CONFLICT, + "Resource with that domain already exists" + ) + ); + } + } // make sure the alias is unique within the org if provided if (alias) { @@ -278,29 +344,55 @@ export async function createSiteResource( tierMatrix.sshPam ); - const niceId = await getUniqueSiteResourceName(orgId); + let updatedNiceId = niceId; + if (!niceId) { + updatedNiceId = await getUniqueSiteResourceName(orgId); + } + let aliasAddress: string | null = null; - if (mode == "host") { - // we can only have an alias on a host + if (mode === "host" || mode === "http") { aliasAddress = await getNextAvailableAliasAddress(orgId); } let newSiteResource: SiteResource | undefined; await db.transaction(async (trx) => { + const [network] = await trx + .insert(networks) + .values({ + scope: "resource", + orgId: orgId + }) + .returning(); + + if (!network) { + return next( + createHttpError( + HttpCode.INTERNAL_SERVER_ERROR, + `Failed to create network` + ) + ); + } + // Create the site resource const insertValues: typeof siteResources.$inferInsert = { - siteId, - niceId, + niceId: updatedNiceId!, orgId, name, - mode: mode as "host" | "cidr", + mode, + ssl, + networkId: network.networkId, destination, + scheme, + destinationPort, enabled, - alias, + alias: alias ? alias.trim() : null, aliasAddress, tcpPortRangeString, udpPortRangeString, - disableIcmp + disableIcmp, + domainId, + subdomain: finalSubdomain, + fullDomain }; if (isLicensedSshPam) { if (authDaemonPort !== undefined) @@ -317,6 +409,13 @@ export async function createSiteResource( //////////////////// update the associations //////////////////// + for (const siteId of siteIds) { + await trx.insert(siteNetworks).values({ + siteId: siteId, + networkId: network.networkId + }); + } + const [adminRole] = await trx .select() .from(roles) @@ -359,16 +458,21 @@ export async function createSiteResource( ); } - const [newt] = await trx - .select() - .from(newts) - .where(eq(newts.siteId, site.siteId)) - .limit(1); + for (const siteToAssign of sitesToAssign) { + const [newt] = await trx + .select() + .from(newts) + .where(eq(newts.siteId, siteToAssign.siteId)) + .limit(1); - if (!newt) { - return next( - createHttpError(HttpCode.NOT_FOUND, "Newt not found") - ); + if (!newt) { + return next( + createHttpError( + HttpCode.NOT_FOUND, + `Newt not found for site ${siteToAssign.siteId}` + ) + ); + } } await rebuildClientAssociationsFromSiteResource( @@ -387,7 +491,7 @@ export async function createSiteResource( } logger.info( - `Created site resource ${newSiteResource.siteResourceId} for site ${siteId}` + `Created site resource ${newSiteResource.siteResourceId} for org ${orgId}` ); return response(res, { diff --git a/server/routers/siteResource/deleteSiteResource.ts b/server/routers/siteResource/deleteSiteResource.ts index 5b50b0ea3..8d08d545d 100644 --- a/server/routers/siteResource/deleteSiteResource.ts +++ b/server/routers/siteResource/deleteSiteResource.ts @@ -70,17 +70,18 @@ export async function deleteSiteResource( .where(and(eq(siteResources.siteResourceId, siteResourceId))) .returning(); - const [newt] = await trx - .select() - .from(newts) - .where(eq(newts.siteId, removedSiteResource.siteId)) - .limit(1); + // not sure why this is here... + // const [newt] = await trx + // .select() + // .from(newts) + // .where(eq(newts.siteId, removedSiteResource.siteId)) + // .limit(1); - if (!newt) { - return next( - createHttpError(HttpCode.NOT_FOUND, "Newt not found") - ); - } + // if (!newt) { + // return next( + // createHttpError(HttpCode.NOT_FOUND, "Newt not found") + // ); + // } await rebuildClientAssociationsFromSiteResource( removedSiteResource, diff --git a/server/routers/siteResource/getSiteResource.ts b/server/routers/siteResource/getSiteResource.ts index be28d36e4..2e3dfe87b 100644 --- a/server/routers/siteResource/getSiteResource.ts +++ b/server/routers/siteResource/getSiteResource.ts @@ -17,38 +17,34 @@ const getSiteResourceParamsSchema = z.strictObject({ .transform((val) => (val ? Number(val) : undefined)) .pipe(z.int().positive().optional()) .optional(), - siteId: z.string().transform(Number).pipe(z.int().positive()), niceId: z.string().optional(), orgId: z.string() }); async function query( siteResourceId?: number, - siteId?: number, niceId?: string, orgId?: string ) { - if (siteResourceId && siteId && orgId) { + if (siteResourceId && orgId) { const [siteResource] = await db .select() .from(siteResources) .where( and( eq(siteResources.siteResourceId, siteResourceId), - eq(siteResources.siteId, siteId), eq(siteResources.orgId, orgId) ) ) .limit(1); return siteResource; - } else if (niceId && siteId && orgId) { + } else if (niceId && orgId) { const [siteResource] = await db .select() .from(siteResources) .where( and( eq(siteResources.niceId, niceId), - eq(siteResources.siteId, siteId), eq(siteResources.orgId, orgId) ) ) @@ -84,7 +80,6 @@ registry.registerPath({ request: { params: z.object({ niceId: z.string(), - siteId: z.number(), orgId: z.string() }) }, @@ -107,10 +102,10 @@ export async function getSiteResource( ); } - const { siteResourceId, siteId, niceId, orgId } = parsedParams.data; + const { siteResourceId, niceId, orgId } = parsedParams.data; // Get the site resource - const siteResource = await query(siteResourceId, siteId, niceId, orgId); + const siteResource = await query(siteResourceId, niceId, orgId); if (!siteResource) { return next( diff --git a/server/routers/siteResource/listAllSiteResourcesByOrg.ts b/server/routers/siteResource/listAllSiteResourcesByOrg.ts index 3320aa3b7..8750e7516 100644 --- a/server/routers/siteResource/listAllSiteResourcesByOrg.ts +++ b/server/routers/siteResource/listAllSiteResourcesByOrg.ts @@ -1,4 +1,4 @@ -import { db, SiteResource, siteResources, sites } from "@server/db"; +import { db, DB_TYPE, SiteResource, siteNetworks, siteResources, sites } from "@server/db"; import response from "@server/lib/response"; import logger from "@server/logger"; import { OpenAPITags, registry } from "@server/openApi"; @@ -41,12 +41,12 @@ const listAllSiteResourcesByOrgQuerySchema = z.object({ }), query: z.string().optional(), mode: z - .enum(["host", "cidr"]) + .enum(["host", "cidr", "http"]) .optional() .catch(undefined) .openapi({ type: "string", - enum: ["host", "cidr"], + enum: ["host", "cidr", "http"], description: "Filter site resources by mode" }), sort_by: z @@ -73,22 +73,58 @@ const listAllSiteResourcesByOrgQuerySchema = z.object({ export type ListAllSiteResourcesByOrgResponse = PaginatedResponse<{ siteResources: (SiteResource & { - siteName: string; - siteNiceId: string; - siteAddress: string | null; + siteOnlines: boolean[]; + siteIds: number[]; + siteNames: string[]; + siteNiceIds: string[]; + siteAddresses: (string | null)[]; })[]; }>; +/** + * Returns an aggregation expression compatible with both SQLite and PostgreSQL. + * - SQLite: json_group_array(col) → returns a JSON array string, parsed after fetch + * - PostgreSQL: array_agg(col) → returns a native array + */ +function aggCol(column: any) { + if (DB_TYPE === "sqlite") { + return sql`json_group_array(${column})`; + } + return sql`array_agg(${column})`; +} + +/** + * For SQLite the aggregated columns come back as JSON strings; parse them into + * proper arrays. For PostgreSQL the driver already returns native arrays, so + * the row is returned unchanged. + */ +function transformSiteResourceRow(row: any) { + if (DB_TYPE !== "sqlite") { + return row; + } + return { + ...row, + siteNames: JSON.parse(row.siteNames) as string[], + siteNiceIds: JSON.parse(row.siteNiceIds) as string[], + siteIds: JSON.parse(row.siteIds) as number[], + siteAddresses: JSON.parse(row.siteAddresses) as (string | null)[], + // SQLite stores booleans as 0/1 integers + siteOnlines: (JSON.parse(row.siteOnlines) as (0 | 1)[]).map( + (v) => v === 1 + ) as boolean[] + }; +} + function querySiteResourcesBase() { return db .select({ siteResourceId: siteResources.siteResourceId, - siteId: siteResources.siteId, orgId: siteResources.orgId, niceId: siteResources.niceId, name: siteResources.name, mode: siteResources.mode, - protocol: siteResources.protocol, + ssl: siteResources.ssl, + scheme: siteResources.scheme, proxyPort: siteResources.proxyPort, destinationPort: siteResources.destinationPort, destination: siteResources.destination, @@ -100,12 +136,24 @@ function querySiteResourcesBase() { disableIcmp: siteResources.disableIcmp, authDaemonMode: siteResources.authDaemonMode, authDaemonPort: siteResources.authDaemonPort, - siteName: sites.name, - siteNiceId: sites.niceId, - siteAddress: sites.address + subdomain: siteResources.subdomain, + domainId: siteResources.domainId, + fullDomain: siteResources.fullDomain, + networkId: siteResources.networkId, + defaultNetworkId: siteResources.defaultNetworkId, + siteNames: aggCol(sites.name), + siteNiceIds: aggCol(sites.niceId), + siteIds: aggCol(sites.siteId), + siteAddresses: aggCol<(string | null)[]>(sites.address), + siteOnlines: aggCol(sites.online) }) .from(siteResources) - .innerJoin(sites, eq(siteResources.siteId, sites.siteId)); + .innerJoin( + siteNetworks, + eq(siteResources.networkId, siteNetworks.networkId) + ) + .innerJoin(sites, eq(siteNetworks.siteId, sites.siteId)) + .groupBy(siteResources.siteResourceId); } registry.registerPath({ @@ -193,10 +241,12 @@ export async function listAllSiteResourcesByOrg( const baseQuery = querySiteResourcesBase().where(and(...conditions)); const countQuery = db.$count( - querySiteResourcesBase().where(and(...conditions)).as("filtered_site_resources") + querySiteResourcesBase() + .where(and(...conditions)) + .as("filtered_site_resources") ); - const [siteResourcesList, totalCount] = await Promise.all([ + const [siteResourcesRaw, totalCount] = await Promise.all([ baseQuery .limit(pageSize) .offset(pageSize * (page - 1)) @@ -210,6 +260,8 @@ export async function listAllSiteResourcesByOrg( countQuery ]); + const siteResourcesList = siteResourcesRaw.map(transformSiteResourceRow); + return response(res, { data: { siteResources: siteResourcesList, @@ -233,4 +285,4 @@ export async function listAllSiteResourcesByOrg( ) ); } -} +} \ No newline at end of file diff --git a/server/routers/siteResource/listSiteResources.ts b/server/routers/siteResource/listSiteResources.ts index 358aa0497..8a1469f76 100644 --- a/server/routers/siteResource/listSiteResources.ts +++ b/server/routers/siteResource/listSiteResources.ts @@ -1,6 +1,6 @@ import { Request, Response, NextFunction } from "express"; import { z } from "zod"; -import { db } from "@server/db"; +import { db, networks, siteNetworks } from "@server/db"; import { siteResources, sites, SiteResource } from "@server/db"; import response from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; @@ -108,13 +108,21 @@ export async function listSiteResources( return next(createHttpError(HttpCode.NOT_FOUND, "Site not found")); } - // Get site resources + // Get site resources by joining networks to siteResources via siteNetworks const siteResourcesList = await db .select() - .from(siteResources) + .from(siteNetworks) + .innerJoin( + networks, + eq(siteNetworks.networkId, networks.networkId) + ) + .innerJoin( + siteResources, + eq(siteResources.networkId, networks.networkId) + ) .where( and( - eq(siteResources.siteId, siteId), + eq(siteNetworks.siteId, siteId), eq(siteResources.orgId, orgId) ) ) @@ -128,6 +136,7 @@ export async function listSiteResources( .limit(limit) .offset(offset); + return response(res, { data: { siteResources: siteResourcesList }, success: true, diff --git a/server/routers/siteResource/updateSiteResource.ts b/server/routers/siteResource/updateSiteResource.ts index ab70d0fce..4335b55d3 100644 --- a/server/routers/siteResource/updateSiteResource.ts +++ b/server/routers/siteResource/updateSiteResource.ts @@ -1,4 +1,3 @@ -import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed"; import { clientSiteResources, clientSiteResourcesAssociationsCache, @@ -7,13 +6,21 @@ import { orgs, roles, roleSiteResources, + siteNetworks, SiteResource, siteResources, sites, + networks, Transaction, userSiteResources } from "@server/db"; -import { tierMatrix } from "@server/lib/billing/tierMatrix"; +import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed"; +import { TierFeature, tierMatrix } from "@server/lib/billing/tierMatrix"; +import { validateAndConstructDomain } from "@server/lib/domainUtils"; +import response from "@server/lib/response"; +import { eq, and, ne, inArray } from "drizzle-orm"; +import { OpenAPITags, registry } from "@server/openApi"; +import { updatePeerData, updateTargets } from "@server/routers/client/targets"; import { generateAliasConfig, generateRemoteSubnets, @@ -22,12 +29,8 @@ import { portRangeStringSchema } from "@server/lib/ip"; import { rebuildClientAssociationsFromSiteResource } from "@server/lib/rebuildClientAssociations"; -import response from "@server/lib/response"; import logger from "@server/logger"; -import { OpenAPITags, registry } from "@server/openApi"; -import { updatePeerData, updateTargets } from "@server/routers/client/targets"; import HttpCode from "@server/types/HttpCode"; -import { and, eq, ne } from "drizzle-orm"; import { NextFunction, Request, Response } from "express"; import createHttpError from "http-errors"; import { z } from "zod"; @@ -40,7 +43,8 @@ const updateSiteResourceParamsSchema = z.strictObject({ const updateSiteResourceSchema = z .strictObject({ name: z.string().min(1).max(255).optional(), - siteId: z.int(), + siteIds: z.array(z.int()), + // niceId: z.string().min(1).max(255).regex(/^[a-zA-Z0-9-]+$/, "niceId can only contain letters, numbers, and dashes").optional(), niceId: z .string() .min(1) @@ -51,10 +55,11 @@ const updateSiteResourceSchema = z ) .optional(), // mode: z.enum(["host", "cidr", "port"]).optional(), - mode: z.enum(["host", "cidr"]).optional(), - // protocol: z.enum(["tcp", "udp"]).nullish(), + mode: z.enum(["host", "cidr", "http"]).optional(), + ssl: z.boolean().optional(), + scheme: z.enum(["http", "https"]).nullish(), // proxyPort: z.int().positive().nullish(), - // destinationPort: z.int().positive().nullish(), + destinationPort: z.int().positive().nullish(), destination: z.string().min(1).optional(), enabled: z.boolean().optional(), alias: z @@ -71,7 +76,9 @@ const updateSiteResourceSchema = z udpPortRangeString: portRangeStringSchema, disableIcmp: z.boolean().optional(), authDaemonPort: z.int().positive().nullish(), - authDaemonMode: z.enum(["site", "remote"]).optional() + authDaemonMode: z.enum(["site", "remote"]).optional(), + domainId: z.string().optional(), + subdomain: z.string().optional() }) .strict() .refine( @@ -118,6 +125,23 @@ const updateSiteResourceSchema = z { message: "Destination must be a valid CIDR notation for cidr mode" } + ) + .refine( + (data) => { + if (data.mode !== "http") return true; + return ( + data.scheme !== undefined && + data.scheme !== null && + data.destinationPort !== undefined && + data.destinationPort !== null && + data.destinationPort >= 1 && + data.destinationPort <= 65535 + ); + }, + { + message: + "HTTP mode requires scheme (http or https) and a valid destination port" + } ); export type UpdateSiteResourceBody = z.infer; @@ -172,11 +196,14 @@ export async function updateSiteResource( const { siteResourceId } = parsedParams.data; const { name, - siteId, // because it can change + siteIds, // because it can change niceId, mode, + scheme, destination, + destinationPort, alias, + ssl, enabled, userIds, roleIds, @@ -185,19 +212,11 @@ export async function updateSiteResource( udpPortRangeString, disableIcmp, authDaemonPort, - authDaemonMode + authDaemonMode, + domainId, + subdomain } = parsedBody.data; - const [site] = await db - .select() - .from(sites) - .where(eq(sites.siteId, siteId)) - .limit(1); - - if (!site) { - return next(createHttpError(HttpCode.NOT_FOUND, "Site not found")); - } - // Check if site resource exists const [existingSiteResource] = await db .select() @@ -211,6 +230,21 @@ export async function updateSiteResource( ); } + if (mode == "http") { + const hasHttpFeature = await isLicensedOrSubscribed( + existingSiteResource.orgId, + tierMatrix[TierFeature.HTTPPrivateResources] + ); + if (!hasHttpFeature) { + return next( + createHttpError( + HttpCode.FORBIDDEN, + "HTTP private resources are not included in your current plan. Please upgrade." + ) + ); + } + } + const isLicensedSshPam = await isLicensedOrSubscribed( existingSiteResource.orgId, tierMatrix.sshPam @@ -237,6 +271,23 @@ export async function updateSiteResource( ); } + // Verify the site exists and belongs to the org + const sitesToAssign = await db + .select() + .from(sites) + .where( + and( + inArray(sites.siteId, siteIds), + eq(sites.orgId, existingSiteResource.orgId) + ) + ); + + if (sitesToAssign.length !== siteIds.length) { + return next( + createHttpError(HttpCode.NOT_FOUND, "Some site not found") + ); + } + // Only check if destination is an IP address const isIp = z .union([z.ipv4(), z.ipv6()]) @@ -254,22 +305,60 @@ export async function updateSiteResource( ); } - let existingSite = site; - let siteChanged = false; - if (existingSiteResource.siteId !== siteId) { - siteChanged = true; - // get the existing site - [existingSite] = await db - .select() - .from(sites) - .where(eq(sites.siteId, existingSiteResource.siteId)) - .limit(1); + let sitesChanged = false; + const existingSiteIds = existingSiteResource.networkId + ? await db + .select() + .from(siteNetworks) + .where( + eq(siteNetworks.networkId, existingSiteResource.networkId) + ) + : []; - if (!existingSite) { + const existingSiteIdSet = new Set(existingSiteIds.map((s) => s.siteId)); + const newSiteIdSet = new Set(siteIds); + + if ( + existingSiteIdSet.size !== newSiteIdSet.size || + ![...existingSiteIdSet].every((id) => newSiteIdSet.has(id)) + ) { + sitesChanged = true; + } + + let fullDomain: string | null = null; + let finalSubdomain: string | null = null; + if (domainId) { + // Validate domain and construct full domain + const domainResult = await validateAndConstructDomain( + domainId, + org.orgId, + subdomain + ); + + if (!domainResult.success) { + return next( + createHttpError(HttpCode.BAD_REQUEST, domainResult.error) + ); + } + + fullDomain = domainResult.fullDomain; + finalSubdomain = domainResult.subdomain; + + // make sure the full domain is unique + const [existingDomain] = await db + .select() + .from(siteResources) + .where(eq(siteResources.fullDomain, fullDomain)); + + if ( + existingDomain && + existingDomain.siteResourceId !== + existingSiteResource.siteResourceId + ) { return next( createHttpError( - HttpCode.NOT_FOUND, - "Existing site not found" + HttpCode.CONFLICT, + "Resource with that domain already exists" ) ); } @@ -302,7 +391,7 @@ export async function updateSiteResource( let updatedSiteResource: SiteResource | undefined; await db.transaction(async (trx) => { // if the site is changed we need to delete and recreate the resource to avoid complications with the rebuild function otherwise we can just update in place - if (siteChanged) { + if (sitesChanged) { // delete the existing site resource await trx .delete(siteResources) @@ -343,15 +432,20 @@ export async function updateSiteResource( .update(siteResources) .set({ name, - siteId, niceId, mode, + scheme, + ssl, destination, + destinationPort, enabled, - alias: alias && alias.trim() ? alias : null, + alias: alias ? alias.trim() : null, tcpPortRangeString, udpPortRangeString, disableIcmp, + domainId, + subdomain: finalSubdomain, + fullDomain, ...sshPamSet }) .where( @@ -372,6 +466,23 @@ export async function updateSiteResource( //////////////////// update the associations //////////////////// + // delete the site - site resources associations + await trx + .delete(siteNetworks) + .where( + eq( + siteNetworks.networkId, + updatedSiteResource.networkId! + ) + ); + + for (const siteId of siteIds) { + await trx.insert(siteNetworks).values({ + siteId: siteId, + networkId: updatedSiteResource.networkId! + }); + } + const [adminRole] = await trx .select() .from(roles) @@ -447,14 +558,20 @@ export async function updateSiteResource( .update(siteResources) .set({ name: name, - siteId: siteId, + niceId: niceId, mode: mode, + scheme, + ssl, destination: destination, + destinationPort: destinationPort, enabled: enabled, - alias: alias && alias.trim() ? alias : null, + alias: alias ? alias.trim() : null, tcpPortRangeString: tcpPortRangeString, udpPortRangeString: udpPortRangeString, disableIcmp: disableIcmp, + domainId, + subdomain: finalSubdomain, + fullDomain, ...sshPamSet }) .where( @@ -464,6 +581,23 @@ export async function updateSiteResource( //////////////////// update the associations //////////////////// + // delete the site - site resources associations + await trx + .delete(siteNetworks) + .where( + eq( + siteNetworks.networkId, + updatedSiteResource.networkId! + ) + ); + + for (const siteId of siteIds) { + await trx.insert(siteNetworks).values({ + siteId: siteId, + networkId: updatedSiteResource.networkId! + }); + } + await trx .delete(clientSiteResources) .where( @@ -533,14 +667,15 @@ export async function updateSiteResource( ); } - logger.info( - `Updated site resource ${siteResourceId} for site ${siteId}` - ); + logger.info(`Updated site resource ${siteResourceId}`); await handleMessagingForUpdatedSiteResource( existingSiteResource, updatedSiteResource, - { siteId: site.siteId, orgId: site.orgId }, + siteIds.map((siteId) => ({ + siteId, + orgId: existingSiteResource.orgId + })), trx ); } @@ -567,7 +702,7 @@ export async function updateSiteResource( export async function handleMessagingForUpdatedSiteResource( existingSiteResource: SiteResource | undefined, updatedSiteResource: SiteResource, - site: { siteId: number; orgId: string }, + sites: { siteId: number; orgId: string }[], trx: Transaction ) { logger.debug( @@ -589,9 +724,14 @@ export async function handleMessagingForUpdatedSiteResource( const destinationChanged = existingSiteResource && existingSiteResource.destination !== updatedSiteResource.destination; + const destinationPortChanged = + existingSiteResource && + existingSiteResource.destinationPort !== + updatedSiteResource.destinationPort; const aliasChanged = existingSiteResource && - existingSiteResource.alias !== updatedSiteResource.alias; + (existingSiteResource.alias !== updatedSiteResource.alias || + existingSiteResource.fullDomain !== updatedSiteResource.fullDomain); // because the full domain gets sent down to the stuff as an alias const portRangesChanged = existingSiteResource && (existingSiteResource.tcpPortRangeString !== @@ -603,106 +743,122 @@ export async function handleMessagingForUpdatedSiteResource( // if the existingSiteResource is undefined (new resource) we don't need to do anything here, the rebuild above handled it all - if (destinationChanged || aliasChanged || portRangesChanged) { - const [newt] = await trx - .select() - .from(newts) - .where(eq(newts.siteId, site.siteId)) - .limit(1); - - if (!newt) { - throw new Error( - "Newt not found for site during site resource update" - ); - } - - // Only update targets on newt if destination changed - if (destinationChanged || portRangesChanged) { - const oldTargets = generateSubnetProxyTargetV2( - existingSiteResource, - mergedAllClients - ); - const newTargets = generateSubnetProxyTargetV2( - updatedSiteResource, - mergedAllClients - ); - - await updateTargets( - newt.newtId, - { - oldTargets: oldTargets ? oldTargets : [], - newTargets: newTargets ? newTargets : [] - }, - newt.version - ); - } - - const olmJobs: Promise[] = []; - for (const client of mergedAllClients) { - // does this client have access to another resource on this site that has the same destination still? if so we dont want to remove it from their olm yet - // todo: optimize this query if needed - const oldDestinationStillInUseSites = await trx + if ( + destinationChanged || + aliasChanged || + portRangesChanged || + destinationPortChanged + ) { + for (const site of sites) { + const [newt] = await trx .select() - .from(siteResources) - .innerJoin( - clientSiteResourcesAssociationsCache, - eq( - clientSiteResourcesAssociationsCache.siteResourceId, - siteResources.siteResourceId - ) - ) - .where( - and( - eq( - clientSiteResourcesAssociationsCache.clientId, - client.clientId - ), - eq(siteResources.siteId, site.siteId), - eq( - siteResources.destination, - existingSiteResource.destination - ), - ne( - siteResources.siteResourceId, - existingSiteResource.siteResourceId - ) - ) + .from(newts) + .where(eq(newts.siteId, site.siteId)) + .limit(1); + + if (!newt) { + throw new Error( + "Newt not found for site during site resource update" + ); + } + + // Only update targets on newt if destination changed + if ( + destinationChanged || + portRangesChanged || + destinationPortChanged + ) { + const oldTargets = await generateSubnetProxyTargetV2( + existingSiteResource, + mergedAllClients + ); + const newTargets = await generateSubnetProxyTargetV2( + updatedSiteResource, + mergedAllClients ); - const oldDestinationStillInUseByASite = - oldDestinationStillInUseSites.length > 0; + await updateTargets( + newt.newtId, + { + oldTargets: oldTargets ? oldTargets : [], + newTargets: newTargets ? newTargets : [] + }, + newt.version + ); + } - // we also need to update the remote subnets on the olms for each client that has access to this site - olmJobs.push( - updatePeerData( - client.clientId, - updatedSiteResource.siteId, - destinationChanged - ? { - oldRemoteSubnets: !oldDestinationStillInUseByASite - ? generateRemoteSubnets([ - existingSiteResource - ]) - : [], - newRemoteSubnets: generateRemoteSubnets([ - updatedSiteResource - ]) - } - : undefined, - aliasChanged - ? { - oldAliases: generateAliasConfig([ - existingSiteResource - ]), - newAliases: generateAliasConfig([ - updatedSiteResource - ]) - } - : undefined - ) - ); + const olmJobs: Promise[] = []; + for (const client of mergedAllClients) { + // does this client have access to another resource on this site that has the same destination still? if so we dont want to remove it from their olm yet + // todo: optimize this query if needed + const oldDestinationStillInUseSites = await trx + .select() + .from(siteResources) + .innerJoin( + clientSiteResourcesAssociationsCache, + eq( + clientSiteResourcesAssociationsCache.siteResourceId, + siteResources.siteResourceId + ) + ) + .innerJoin( + siteNetworks, + eq(siteNetworks.networkId, siteResources.networkId) + ) + .where( + and( + eq( + clientSiteResourcesAssociationsCache.clientId, + client.clientId + ), + eq(siteNetworks.siteId, site.siteId), + eq( + siteResources.destination, + existingSiteResource.destination + ), + ne( + siteResources.siteResourceId, + existingSiteResource.siteResourceId + ) + ) + ); + + const oldDestinationStillInUseByASite = + oldDestinationStillInUseSites.length > 0; + + // we also need to update the remote subnets on the olms for each client that has access to this site + olmJobs.push( + updatePeerData( + client.clientId, + site.siteId, + destinationChanged + ? { + oldRemoteSubnets: + !oldDestinationStillInUseByASite + ? generateRemoteSubnets([ + existingSiteResource + ]) + : [], + newRemoteSubnets: generateRemoteSubnets([ + updatedSiteResource + ]) + } + : undefined, + aliasChanged + ? { + oldAliases: generateAliasConfig([ + existingSiteResource + ]), + newAliases: generateAliasConfig([ + updatedSiteResource + ]) + } + : undefined + ) + ); + } + + await Promise.all(olmJobs); } - - await Promise.all(olmJobs); } } diff --git a/server/routers/target/createTarget.ts b/server/routers/target/createTarget.ts index ba52d85a1..e5c1f246e 100644 --- a/server/routers/target/createTarget.ts +++ b/server/routers/target/createTarget.ts @@ -31,8 +31,8 @@ const createTargetSchema = z.strictObject({ hcMode: z.string().optional().nullable(), hcHostname: z.string().optional().nullable(), hcPort: z.int().positive().optional().nullable(), - hcInterval: z.int().positive().min(5).optional().nullable(), - hcUnhealthyInterval: z.int().positive().min(5).optional().nullable(), + hcInterval: z.int().positive().min(1).optional().nullable(), + hcUnhealthyInterval: z.int().positive().min(1).optional().nullable(), hcTimeout: z.int().positive().min(1).optional().nullable(), hcHeaders: z .array(z.strictObject({ name: z.string(), value: z.string() })) @@ -42,6 +42,8 @@ const createTargetSchema = z.strictObject({ hcMethod: z.string().min(1).optional().nullable(), hcStatus: z.int().optional().nullable(), hcTlsServerName: z.string().optional().nullable(), + hcHealthyThreshold: z.int().positive().min(1).optional().nullable(), + hcUnhealthyThreshold: z.int().positive().min(1).optional().nullable(), path: z.string().optional().nullable(), pathMatchType: z.enum(["exact", "prefix", "regex"]).optional().nullable(), rewritePath: z.string().optional().nullable(), @@ -226,7 +228,10 @@ export async function createTarget( healthCheck = await db .insert(targetHealthCheck) .values({ + orgId: resource.orgId, targetId: newTarget[0].targetId, + siteId: targetData.siteId, + name: `Resource ${resource.name} - ${targetData.ip}:${targetData.port}`, hcEnabled: targetData.hcEnabled ?? false, hcPath: targetData.hcPath ?? null, hcScheme: targetData.hcScheme ?? null, @@ -241,7 +246,9 @@ export async function createTarget( hcMethod: targetData.hcMethod ?? null, hcStatus: targetData.hcStatus ?? null, hcHealth: "unknown", - hcTlsServerName: targetData.hcTlsServerName ?? null + hcTlsServerName: targetData.hcTlsServerName ?? null, + hcHealthyThreshold: targetData.hcHealthyThreshold ?? null, + hcUnhealthyThreshold: targetData.hcUnhealthyThreshold ?? null }) .returning(); @@ -271,8 +278,8 @@ export async function createTarget( return response(res, { data: { - ...newTarget[0], - ...healthCheck[0] + ...healthCheck[0], + ...newTarget[0] }, success: true, error: false, diff --git a/server/routers/target/getTarget.ts b/server/routers/target/getTarget.ts index 749e1399b..281c39906 100644 --- a/server/routers/target/getTarget.ts +++ b/server/routers/target/getTarget.ts @@ -15,8 +15,8 @@ const getTargetSchema = z.strictObject({ }); type GetTargetResponse = Target & - Omit & { - hcHeaders: { name: string; value: string }[] | null; + Partial> & { + hcHeaders: { name: string; value: string }[] | null | undefined; }; registry.registerPath({ @@ -70,20 +70,19 @@ export async function getTarget( .limit(1); // Parse hcHeaders from JSON string back to array - let parsedHcHeaders = null; + let parsedHcHeaders: { name: string; value: string }[] | null = null; if (targetHc?.hcHeaders) { try { parsedHcHeaders = JSON.parse(targetHc.hcHeaders); } catch (error) { - // If parsing fails, keep as string for backward compatibility - parsedHcHeaders = targetHc.hcHeaders; + // If parsing fails, keep as null for safety } } return response(res, { data: { - ...target[0], ...targetHc, + ...target[0], hcHeaders: parsedHcHeaders }, success: true, diff --git a/server/routers/target/handleHealthcheckStatusMessage.ts b/server/routers/target/handleHealthcheckStatusMessage.ts index 7ea1730ce..b5ac7f79f 100644 --- a/server/routers/target/handleHealthcheckStatusMessage.ts +++ b/server/routers/target/handleHealthcheckStatusMessage.ts @@ -1,9 +1,20 @@ -import { db, targets, resources, sites, targetHealthCheck } from "@server/db"; +import { + db, + targets, + resources, + sites, + targetHealthCheck, + statusHistory +} from "@server/db"; import { MessageHandler } from "@server/routers/ws"; import { Newt } from "@server/db"; -import { eq, and } from "drizzle-orm"; +import { eq, and, ne } from "drizzle-orm"; import logger from "@server/logger"; -import { unknown } from "zod"; +import { + fireHealthCheckHealthyAlert, + fireHealthCheckUnhealthyAlert +} from "#dynamic/lib/alerts"; +import { fireResourceHealthyAlert, fireResourceUnhealthyAlert } from "@server/private/lib/alerts/events/resourceEvents"; interface TargetHealthStatus { status: string; @@ -11,7 +22,7 @@ interface TargetHealthStatus { checkCount: number; lastError?: string; config: { - id: string; + id: string; // this could be the hc id or the target id, depending on the version of newt hcEnabled: boolean; hcPath?: string; hcScheme?: string; @@ -22,7 +33,11 @@ interface TargetHealthStatus { hcUnhealthyInterval?: number; hcTimeout?: number; hcHeaders?: any; + hcFollowRedirects?: boolean; hcMethod?: string; + hcTlsServerName?: string; + hcHealthyThreshold?: number; + hcUnhealthyThreshold?: number; }; } @@ -78,18 +93,27 @@ export const handleHealthcheckStatusMessage: MessageHandler = async ( .select({ targetId: targets.targetId, siteId: targets.siteId, - hcStatus: targetHealthCheck.hcHealth + orgId: targetHealthCheck.orgId, + targetHealthCheckId: targetHealthCheck.targetHealthCheckId, + resourceOrgId: resources.orgId, + resourceId: resources.resourceId, + resourceName: resources.name, + name: targetHealthCheck.name, + hcHealth: targetHealthCheck.hcHealth }) - .from(targets) + .from(targetHealthCheck) + .innerJoin(sites, eq(targetHealthCheck.siteId, sites.siteId)) + .innerJoin( + targets, + eq(targetHealthCheck.targetId, targets.targetId) + ) .innerJoin( resources, eq(targets.resourceId, resources.resourceId) ) - .innerJoin(sites, eq(targets.siteId, sites.siteId)) - .innerJoin(targetHealthCheck, eq(targets.targetId, targetHealthCheck.targetId)) .where( and( - eq(targets.targetId, targetIdNum), + eq(targetHealthCheck.targetHealthCheckId, targetIdNum), eq(sites.siteId, newt.siteId) ) ) @@ -104,7 +128,7 @@ export const handleHealthcheckStatusMessage: MessageHandler = async ( } // check if the status has changed - if (targetCheck.hcStatus === healthStatus.status) { + if (targetCheck.hcHealth === healthStatus.status) { logger.debug( `Health status for target ${targetId} is already ${healthStatus.status}, skipping update` ); @@ -120,8 +144,94 @@ export const handleHealthcheckStatusMessage: MessageHandler = async ( | "healthy" | "unhealthy" }) - .where(eq(targetHealthCheck.targetId, targetIdNum)) - .execute(); + .where(eq(targetHealthCheck.targetId, targetCheck.targetId)); + + const orgId = targetCheck.orgId || targetCheck.resourceOrgId; // for backwards compatibility, check both orgId fields because the target health checks dont have the orgId + if (!orgId) { + logger.warn( + `No org ID found for target ${targetId}, skipping status history logging` + ); + continue; + } + + // Log the state change to status history + await db.insert(statusHistory).values({ + entityType: "healthCheck", + entityId: targetCheck.targetHealthCheckId, + orgId: orgId, + status: healthStatus.status, + timestamp: Math.floor(Date.now() / 1000) + }); + + if (targetCheck.resourceId) { + // Log the state change to status history for the resource as well + // so we can show the resource status along with the site + + // if the status is healthy we should check if ALL of the targets on the resource are currently healthy and if not then dont mark the resource as healthy yet, we want to wait until all targets are healthy to mark the resource as healthy + let status = healthStatus.status; + if (healthStatus.status === "healthy") { + const otherTargets = await db + .select({ hcHealth: targetHealthCheck.hcHealth }) + .from(targets) + .innerJoin( + targetHealthCheck, + eq(targets.targetId, targetHealthCheck.targetId) + ) + .where( + and( + eq(targets.resourceId, targetCheck.resourceId), + ne(targets.targetId, targetCheck.targetId) // only check the other targets, not the one we just updated + ) + ); + + const allHealthy = otherTargets.every( + (t) => t.hcHealth === "healthy" + ); + if (!allHealthy) { + logger.debug( + `Not marking resource ${targetCheck.resourceId} as healthy because not all targets are healthy` + ); + status = "unhealthy"; + } + } + + await db.insert(statusHistory).values({ + entityType: "resource", + entityId: targetCheck.resourceId, + orgId: orgId, + status: status, + timestamp: Math.floor(Date.now() / 1000) + }); + + if (status === "unhealthy") { + await fireResourceUnhealthyAlert( + orgId, + targetCheck.resourceId, + targetCheck.resourceName + ); + } else if (status === "healthy") { + await fireResourceHealthyAlert( + orgId, + targetCheck.resourceId, + targetCheck.resourceName + ); + } + } + + // because we are checking above if there was a change we can fire the alert here because it changed + if (healthStatus.status === "unhealthy") { + await fireHealthCheckUnhealthyAlert( + orgId, + targetCheck.targetHealthCheckId, + targetCheck.name + ); + } else if (healthStatus.status === "healthy") { + await fireHealthCheckHealthyAlert( + orgId, + targetCheck.targetHealthCheckId, + targetCheck.name + ); + } logger.debug( `Updated health status for target ${targetId} to ${healthStatus.status}` diff --git a/server/routers/target/updateTarget.ts b/server/routers/target/updateTarget.ts index 1f9eff716..a633deb4d 100644 --- a/server/routers/target/updateTarget.ts +++ b/server/routers/target/updateTarget.ts @@ -32,8 +32,8 @@ const updateTargetBodySchema = z hcMode: z.string().optional().nullable(), hcHostname: z.string().optional().nullable(), hcPort: z.int().positive().optional().nullable(), - hcInterval: z.int().positive().min(5).optional().nullable(), - hcUnhealthyInterval: z.int().positive().min(5).optional().nullable(), + hcInterval: z.int().positive().min(1).optional().nullable(), + hcUnhealthyInterval: z.int().positive().min(1).optional().nullable(), hcTimeout: z.int().positive().min(1).optional().nullable(), hcHeaders: z .array(z.strictObject({ name: z.string(), value: z.string() })) @@ -43,6 +43,8 @@ const updateTargetBodySchema = z hcMethod: z.string().min(1).optional().nullable(), hcStatus: z.int().optional().nullable(), hcTlsServerName: z.string().optional().nullable(), + hcHealthyThreshold: z.int().positive().min(1).optional().nullable(), + hcUnhealthyThreshold: z.int().positive().min(1).optional().nullable(), path: z.string().optional().nullable(), pathMatchType: z .enum(["exact", "prefix", "regex"]) @@ -226,6 +228,7 @@ export async function updateTarget( const [updatedHc] = await db .update(targetHealthCheck) .set({ + siteId: parsedBody.data.siteId, hcEnabled: parsedBody.data.hcEnabled || false, hcPath: parsedBody.data.hcPath, hcScheme: parsedBody.data.hcScheme, @@ -240,6 +243,8 @@ export async function updateTarget( hcMethod: parsedBody.data.hcMethod, hcStatus: parsedBody.data.hcStatus, hcTlsServerName: parsedBody.data.hcTlsServerName, + hcHealthyThreshold: parsedBody.data.hcHealthyThreshold, + hcUnhealthyThreshold: parsedBody.data.hcUnhealthyThreshold, ...(hcHealthValue !== undefined && { hcHealth: hcHealthValue }) }) .where(eq(targetHealthCheck.targetId, targetId)) diff --git a/server/routers/user/adminListUsers.ts b/server/routers/user/adminListUsers.ts index 3a965259c..3d7bac4b3 100644 --- a/server/routers/user/adminListUsers.ts +++ b/server/routers/user/adminListUsers.ts @@ -1,31 +1,98 @@ import { Request, Response, NextFunction } from "express"; import { z } from "zod"; -import { db } from "@server/db"; +import { db, idp, users } from "@server/db"; import response from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; import createHttpError from "http-errors"; -import { sql, eq } from "drizzle-orm"; +import { and, asc, desc, eq, like, or, sql } from "drizzle-orm"; import logger from "@server/logger"; -import { idp, users } from "@server/db"; import { fromZodError } from "zod-validation-error"; +import { OpenAPITags, registry } from "@server/openApi"; +import type { PaginatedResponse } from "@server/types/Pagination"; +import { UserType } from "@server/types/UserTypes"; const listUsersSchema = z.strictObject({ - limit: z - .string() + pageSize: z.coerce + .number() + .int() + .positive() .optional() - .default("1000") - .transform(Number) - .pipe(z.int().nonnegative()), - offset: z - .string() + .catch(20) + .default(20) + .openapi({ + type: "integer", + default: 20, + description: "Number of items per page" + }), + page: z.coerce + .number() + .int() + .min(0) .optional() - .default("0") - .transform(Number) - .pipe(z.int().nonnegative()) + .catch(1) + .default(1) + .openapi({ + type: "integer", + default: 1, + description: "Page number to retrieve" + }), + query: z.string().optional(), + sort_by: z + .enum(["username", "email", "name"]) + .optional() + .catch(undefined) + .openapi({ + type: "string", + enum: ["username", "email", "name"], + description: "Field to sort by" + }), + order: z + .enum(["asc", "desc"]) + .optional() + .default("asc") + .catch("asc") + .openapi({ + type: "string", + enum: ["asc", "desc"], + default: "asc", + description: "Sort order" + }), + idp_id: z + .preprocess( + (val) => { + if (val === undefined || val === null || val === "") { + return undefined; + } + if (val === "internal") { + return "internal"; + } + if (typeof val === "string" && /^\d+$/.test(val)) { + return parseInt(val, 10); + } + return undefined; + }, + z + .union([z.literal("internal"), z.number().int().positive()]) + .optional() + ) + .openapi({ + description: + 'Filter by identity provider id, or "internal" for internal users' + }), + two_factor: z + .enum(["true", "false"]) + .transform((v) => v === "true") + .optional() + .catch(undefined) + .openapi({ + type: "boolean", + description: + "Filter by 2FA state matching: enabled if twoFactorEnabled or twoFactorSetupRequested" + }) }); -async function queryUsers(limit: number, offset: number) { - return await db +function queryUsersBase() { + return db .select({ id: users.userId, email: users.email, @@ -40,17 +107,39 @@ async function queryUsers(limit: number, offset: number) { twoFactorSetupRequested: users.twoFactorSetupRequested }) .from(users) - .leftJoin(idp, eq(users.idpId, idp.idpId)) - .where(eq(users.serverAdmin, false)) - .limit(limit) - .offset(offset); + .leftJoin(idp, eq(users.idpId, idp.idpId)); } -export type AdminListUsersResponse = { - users: NonNullable>>; - pagination: { total: number; limit: number; offset: number }; +/** Row shape returned by `queryUsersBase()` (matches selected columns + join). */ +export type AdminListUserRow = { + id: string; + email: string | null; + username: string; + name: string | null; + dateCreated: string; + serverAdmin: boolean; + type: string; + idpName: string | null; + idpId: number | null; + twoFactorEnabled: boolean; + twoFactorSetupRequested: boolean | null; }; +export type AdminListUsersResponse = PaginatedResponse<{ + users: AdminListUserRow[]; +}>; + +registry.registerPath({ + method: "get", + path: "/users", + description: "List non–server-admin users (server admin).", + tags: [OpenAPITags.User], + request: { + query: listUsersSchema + }, + responses: {} +}); + export async function adminListUsers( req: Request, res: Response, @@ -66,21 +155,96 @@ export async function adminListUsers( ) ); } - const { limit, offset } = parsedQuery.data; + const { + page, + pageSize, + query, + sort_by, + order, + idp_id, + two_factor: twoFactorFilter + } = parsedQuery.data; - const allUsers = await queryUsers(limit, offset); + if (typeof idp_id === "number") { + const idpOk = await db + .select({ one: sql`1` }) + .from(idp) + .where(eq(idp.idpId, idp_id)) + .limit(1); + if (idpOk.length === 0) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + "idp_id does not exist" + ) + ); + } + } - const [{ count }] = await db - .select({ count: sql`count(*)` }) - .from(users); + const conditions = [eq(users.serverAdmin, false)]; + + if (query) { + const q = "%" + query.toLowerCase() + "%"; + conditions.push( + or( + like(sql`LOWER(${users.username})`, q), + like(sql`LOWER(${users.email})`, q), + like(sql`LOWER(${users.name})`, q) + )! + ); + } + + if (idp_id === "internal") { + conditions.push(eq(users.type, UserType.Internal)); + } else if (typeof idp_id === "number") { + conditions.push(eq(users.idpId, idp_id)); + } + + if (typeof twoFactorFilter === "boolean") { + if (twoFactorFilter) { + conditions.push( + or( + eq(users.twoFactorEnabled, true), + eq(users.twoFactorSetupRequested, true) + )! + ); + } else { + conditions.push( + and( + eq(users.twoFactorEnabled, false), + eq(users.twoFactorSetupRequested, false) + )! + ); + } + } + + const whereClause = and(...conditions); + + const countQuery = db.$count( + queryUsersBase().where(whereClause).as("filtered_admin_users") + ); + + const userListQuery = queryUsersBase() + .where(whereClause) + .limit(pageSize) + .offset(pageSize * (page - 1)) + .orderBy( + sort_by + ? order === "asc" + ? asc(users[sort_by]) + : desc(users[sort_by]) + : asc(users.username) + ); + + const [total, rows] = await Promise.all([countQuery, userListQuery]); return response(res, { data: { - users: allUsers, + users: rows, pagination: { - total: count, - limit, - offset + total, + page, + pageSize } }, success: true, diff --git a/server/routers/user/listUsers.ts b/server/routers/user/listUsers.ts index fe7f6b250..42a62636d 100644 --- a/server/routers/user/listUsers.ts +++ b/server/routers/user/listUsers.ts @@ -1,36 +1,113 @@ import { Request, Response, NextFunction } from "express"; import { z } from "zod"; import { db, idpOidcConfig } from "@server/db"; -import { idp, roles, userOrgRoles, userOrgs, users } from "@server/db"; +import { + idp, + idpOrg, + roles, + userOrgRoles, + userOrgs, + users +} from "@server/db"; import response from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; import createHttpError from "http-errors"; -import { and, eq, inArray, sql } from "drizzle-orm"; +import { and, asc, desc, eq, exists, inArray, like, or, sql } from "drizzle-orm"; import logger from "@server/logger"; import { fromZodError } from "zod-validation-error"; import { OpenAPITags, registry } from "@server/openApi"; +import type { PaginatedResponse } from "@server/types/Pagination"; +import { UserType } from "@server/types/UserTypes"; const listUsersParamsSchema = z.strictObject({ orgId: z.string() }); const listUsersSchema = z.strictObject({ - limit: z - .string() + pageSize: z.coerce + .number() // for prettier formatting + .int() + .positive() .optional() - .default("1000") - .transform(Number) - .pipe(z.int().nonnegative()), - offset: z - .string() + .catch(20) + .default(20) + .openapi({ + type: "integer", + default: 20, + description: "Number of items per page" + }), + page: z.coerce + .number() // for prettier formatting + .int() + .min(0) .optional() - .default("0") - .transform(Number) - .pipe(z.int().nonnegative()) + .catch(1) + .default(1) + .openapi({ + type: "integer", + default: 1, + description: "Page number to retrieve" + }), + query: z.string().optional(), + sort_by: z + .enum(["username"]) + .optional() + .catch(undefined) + .openapi({ + type: "string", + enum: ["username"], + description: "Field to sort by" + }), + order: z + .enum(["asc", "desc"]) + .optional() + .default("asc") + .catch("asc") + .openapi({ + type: "string", + enum: ["asc", "desc"], + default: "asc", + description: "Sort order" + }), + idp_id: z + .preprocess((val) => { + if (val === undefined || val === null || val === "") { + return undefined; + } + if (val === "internal") { + return "internal"; + } + if (typeof val === "string" && /^\d+$/.test(val)) { + return parseInt(val, 10); + } + return undefined; + }, z.union([z.literal("internal"), z.number().int().positive()]).optional()) + .openapi({ + description: + 'Filter by identity provider id, or "internal" for internal users' + }), + role_id: z + .preprocess((val) => { + if (val === undefined || val === null || val === "") { + return undefined; + } + const raw = Array.isArray(val) ? val : [val]; + const nums = raw + .map((v) => + typeof v === "string" ? parseInt(v, 10) : Number(v) + ) + .filter((n) => Number.isInteger(n) && n > 0); + const unique = [...new Set(nums)]; + return unique.length ? unique : undefined; + }, z.array(z.number().int().positive()).max(50).optional()) + .openapi({ + description: + "Filter users who have any of these role ids in the organization (repeat query param)" + }) }); -async function queryUsers(orgId: string, limit: number, offset: number) { - const rows = await db +function queryUsersBase() { + return db .select({ id: users.userId, email: users.email, @@ -50,53 +127,19 @@ async function queryUsers(orgId: string, limit: number, offset: number) { .from(users) .leftJoin(userOrgs, eq(users.userId, userOrgs.userId)) .leftJoin(idp, eq(users.idpId, idp.idpId)) - .leftJoin(idpOidcConfig, eq(idpOidcConfig.idpId, idp.idpId)) - .where(eq(userOrgs.orgId, orgId)) - .limit(limit) - .offset(offset); - - const userIds = rows.map((r) => r.id); - const roleRows = - userIds.length === 0 - ? [] - : await db - .select({ - userId: userOrgRoles.userId, - roleId: userOrgRoles.roleId, - roleName: roles.name - }) - .from(userOrgRoles) - .leftJoin(roles, eq(userOrgRoles.roleId, roles.roleId)) - .where( - and( - eq(userOrgRoles.orgId, orgId), - inArray(userOrgRoles.userId, userIds) - ) - ); - - const rolesByUser = new Map< - string, - { roleId: number; roleName: string }[] - >(); - for (const r of roleRows) { - const list = rolesByUser.get(r.userId) ?? []; - list.push({ roleId: r.roleId, roleName: r.roleName ?? "" }); - rolesByUser.set(r.userId, list); - } - - return rows.map((row) => { - const userRoles = rolesByUser.get(row.id) ?? []; - return { - ...row, - roles: userRoles - }; - }); + .leftJoin(idpOidcConfig, eq(idpOidcConfig.idpId, idp.idpId)); } -export type ListUsersResponse = { - users: NonNullable>>; - pagination: { total: number; limit: number; offset: number }; -}; +export type ListUsersResponse = PaginatedResponse<{ + users: Array< + NonNullable>>[number] & { + roles: Array<{ + roleId: number; + roleName: string; + }>; + } + >; +}>; registry.registerPath({ method: "get", @@ -125,7 +168,9 @@ export async function listUsers( ) ); } - const { limit, offset } = parsedQuery.data; + const { page, pageSize, sort_by, order, query, idp_id, role_id } = + parsedQuery.data; + const roleIds = role_id ?? []; const parsedParams = listUsersParamsSchema.safeParse(req.params); if (!parsedParams.success) { @@ -139,24 +184,154 @@ export async function listUsers( const { orgId } = parsedParams.data; - const usersWithRoles = await queryUsers( - orgId.toString(), - limit, - offset + if (typeof idp_id === "number") { + const idpOk = await db + .select({ one: sql`1` }) + .from(idpOrg) + .where( + and(eq(idpOrg.orgId, orgId), eq(idpOrg.idpId, idp_id)) + ) + .limit(1); + if (idpOk.length === 0) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + "idp_id is not linked to this organization" + ) + ); + } + } + + if (roleIds.length > 0) { + const validRoles = await db + .select({ roleId: roles.roleId }) + .from(roles) + .where( + and(eq(roles.orgId, orgId), inArray(roles.roleId, roleIds)) + ); + if (validRoles.length !== roleIds.length) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + "One or more role_id values are not valid for this organization" + ) + ); + } + } + + const conditions = [and(eq(userOrgs.orgId, orgId))]; + + if (query) { + conditions.push( + or( + like( + sql`LOWER(${users.name})`, + "%" + query.toLowerCase() + "%" + ), + like( + sql`LOWER(${users.username})`, + "%" + query.toLowerCase() + "%" + ), + like( + sql`LOWER(${users.email})`, + "%" + query.toLowerCase() + "%" + ) + ) + ); + } + + if (idp_id === "internal") { + conditions.push(eq(users.type, UserType.Internal)); + } else if (typeof idp_id === "number") { + conditions.push(eq(users.idpId, idp_id)); + } + + if (roleIds.length > 0) { + conditions.push( + exists( + db + .select() + .from(userOrgRoles) + .where( + and( + eq(userOrgRoles.userId, users.userId), + eq(userOrgRoles.orgId, orgId), + inArray(userOrgRoles.roleId, roleIds) + ) + ) + ) + ); + } + + const countQuery = db.$count( + queryUsersBase() + .where(and(...conditions)) + .as("filtered_users") ); - const [{ count }] = await db - .select({ count: sql`count(*)` }) - .from(userOrgs) - .where(eq(userOrgs.orgId, orgId)); + const userListQuery = queryUsersBase() + .where(and(...conditions)) + .limit(pageSize) + .offset(pageSize * (page - 1)) + .orderBy( + sort_by + ? order === "asc" + ? asc(users[sort_by]) + : desc(users[sort_by]) + : asc(users.name) + ); + + const [total, usersWithoutRoles] = await Promise.all([ + countQuery, + userListQuery + ]); + + const userIds = usersWithoutRoles.map((r) => r.id); + const roleRows = + userIds.length === 0 + ? [] + : await db + .select({ + userId: userOrgRoles.userId, + roleId: userOrgRoles.roleId, + roleName: roles.name + }) + .from(userOrgRoles) + .leftJoin(roles, eq(userOrgRoles.roleId, roles.roleId)) + .where( + and( + eq(userOrgRoles.orgId, orgId), + inArray(userOrgRoles.userId, userIds) + ) + ); + + const rolesByUser = new Map< + string, + { roleId: number; roleName: string }[] + >(); + for (const r of roleRows) { + const list = rolesByUser.get(r.userId) ?? []; + list.push({ roleId: r.roleId, roleName: r.roleName ?? "" }); + rolesByUser.set(r.userId, list); + } + + const usersWithRoles: ListUsersResponse["users"] = []; + + for (const user of usersWithoutRoles) { + const userRoles = rolesByUser.get(user.id) ?? []; + usersWithRoles.push({ + ...user, + roles: userRoles + }); + } return response(res, { data: { users: usersWithRoles, pagination: { - total: count, - limit, - offset + total, + page, + pageSize } }, success: true, diff --git a/server/routers/ws/messageHandlers.ts b/server/routers/ws/messageHandlers.ts index 143e4d516..f89284389 100644 --- a/server/routers/ws/messageHandlers.ts +++ b/server/routers/ws/messageHandlers.ts @@ -2,7 +2,7 @@ import { build } from "@server/build"; import { handleNewtRegisterMessage, handleReceiveBandwidthMessage, - handleGetConfigMessage, + handleNewtGetConfigMessage, handleDockerStatusMessage, handleDockerContainersMessage, handleNewtPingRequestMessage, @@ -37,7 +37,7 @@ export const messageHandlers: Record = { "newt/disconnecting": handleNewtDisconnectingMessage, "newt/ping": handleNewtPingMessage, "newt/wg/register": handleNewtRegisterMessage, - "newt/wg/get-config": handleGetConfigMessage, + "newt/wg/get-config": handleNewtGetConfigMessage, "newt/receive-bandwidth": handleReceiveBandwidthMessage, "newt/socket/status": handleDockerStatusMessage, "newt/socket/containers": handleDockerContainersMessage, @@ -47,7 +47,7 @@ export const messageHandlers: Record = { "ws/round-trip/complete": handleRoundTripMessage }; -// Start the ping accumulator for all builds — it batches per-site online/lastPing +// Start the ping accumulator for all builds - it batches per-site online/lastPing // updates into periodic bulk writes, preventing connection pool exhaustion. startPingAccumulator(); diff --git a/server/setup/ensureRootApiKey.ts b/server/setup/ensureRootApiKey.ts new file mode 100644 index 000000000..55f5186b3 --- /dev/null +++ b/server/setup/ensureRootApiKey.ts @@ -0,0 +1,106 @@ +import { db, apiKeys } from "@server/db"; +import { eq } from "drizzle-orm"; +import { generateRandomString, RandomReader } from "@oslojs/crypto/random"; +import moment from "moment"; +import logger from "@server/logger"; +import { hashPassword } from "@server/auth/password"; + +const random: RandomReader = { + read(bytes: Uint8Array): void { + crypto.getRandomValues(bytes); + } +}; + +function validateApiKeyId(id: string): boolean { + return /^[a-z0-9]{15}$/.test(id); +} + +function validateApiKeySecret(secret: string): boolean { + return secret.length > 0; +} + +function showRootApiKey(apiKeyId: string, source: string): void { + console.log(`=== ROOT API KEY ${source} ===`); + console.log("API Key ID:", apiKeyId); + console.log( + "The root API key from PANGOLIN_ROOT_API_KEY has been applied." + ); + console.log("Use the full key value (apiKeyId.apiKeySecret) in requests."); + console.log("================================"); +} + +export async function ensureRootApiKey() { + try { + const envApiKey = process.env.PANGOLIN_ROOT_API_KEY; + + if (!envApiKey) { + // logger.debug( + // "PANGOLIN_ROOT_API_KEY not set. Root API key from environment skipped." + // ); + return; + } + + const parts = envApiKey.split("."); + if (parts.length !== 2) { + throw new Error( + "Invalid format for PANGOLIN_ROOT_API_KEY. Expected format: {apiKeyId}.{apiKeySecret}" + ); + } + + const [apiKeyId, apiKeySecret] = parts; + + if (!validateApiKeyId(apiKeyId)) { + throw new Error( + "Invalid apiKeyId in PANGOLIN_ROOT_API_KEY. Must be 15 lowercase alphanumeric characters." + ); + } + + if (!validateApiKeySecret(apiKeySecret)) { + throw new Error( + "Invalid apiKeySecret in PANGOLIN_ROOT_API_KEY. Secret must not be empty." + ); + } + + const apiKeyHash = await hashPassword(apiKeySecret); + const lastChars = apiKeySecret.slice(-4); + const createdAt = moment().toISOString(); + + const [existingKey] = await db + .select() + .from(apiKeys) + .where(eq(apiKeys.apiKeyId, apiKeyId)); + + if (existingKey) { + if (!existingKey.isRoot) { + console.warn( + `API key with ID ${apiKeyId} exists but is not a root key. Promoting to root and updating hash.` + ); + } else { + console.warn( + `Overwriting existing root API key hash since PANGOLIN_ROOT_API_KEY is set (apiKeyId: ${apiKeyId})` + ); + } + + await db + .update(apiKeys) + .set({ apiKeyHash, lastChars, isRoot: true }) + .where(eq(apiKeys.apiKeyId, apiKeyId)); + + showRootApiKey(apiKeyId, "UPDATED FROM ENVIRONMENT"); + } else { + await db.insert(apiKeys).values({ + apiKeyId, + name: "Root API Key (Environment)", + apiKeyHash, + lastChars, + createdAt, + isRoot: true + }); + + showRootApiKey(apiKeyId, "CREATED FROM ENVIRONMENT"); + } + } catch (error) { + console.error("Failed to ensure root API key:", error); + throw error; + } +} diff --git a/server/setup/index.ts b/server/setup/index.ts index 2dfb633e5..c46e6b8fd 100644 --- a/server/setup/index.ts +++ b/server/setup/index.ts @@ -2,10 +2,12 @@ import { ensureActions } from "./ensureActions"; import { copyInConfig } from "./copyInConfig"; import { clearStaleData } from "./clearStaleData"; import { ensureSetupToken } from "./ensureSetupToken"; +import { ensureRootApiKey } from "./ensureRootApiKey"; export async function runSetupFunctions() { await copyInConfig(); // copy in the config to the db as needed await ensureActions(); // make sure all of the actions are in the db and the roles await clearStaleData(); await ensureSetupToken(); // ensure setup token exists for initial setup + await ensureRootApiKey(); } diff --git a/server/setup/migrationsPg.ts b/server/setup/migrationsPg.ts index 9ba0b9767..992cc2583 100644 --- a/server/setup/migrationsPg.ts +++ b/server/setup/migrationsPg.ts @@ -22,6 +22,7 @@ import m13 from "./scriptsPg/1.15.3"; import m14 from "./scriptsPg/1.15.4"; import m15 from "./scriptsPg/1.16.0"; import m16 from "./scriptsPg/1.17.0"; +import m17 from "./scriptsPg/1.18.0"; // THIS CANNOT IMPORT ANYTHING FROM THE SERVER // EXCEPT FOR THE DATABASE AND THE SCHEMA @@ -43,7 +44,8 @@ const migrations = [ { version: "1.15.3", run: m13 }, { version: "1.15.4", run: m14 }, { version: "1.16.0", run: m15 }, - { version: "1.17.0", run: m16 } + { version: "1.17.0", run: m16 }, + { version: "1.18.0", run: m17 } // Add new migrations here as they are created ] as { version: string; diff --git a/server/setup/migrationsSqlite.ts b/server/setup/migrationsSqlite.ts index 45a29ec29..c32437aec 100644 --- a/server/setup/migrationsSqlite.ts +++ b/server/setup/migrationsSqlite.ts @@ -40,6 +40,7 @@ import m34 from "./scriptsSqlite/1.15.3"; import m35 from "./scriptsSqlite/1.15.4"; import m36 from "./scriptsSqlite/1.16.0"; import m37 from "./scriptsSqlite/1.17.0"; +import m38 from "./scriptsSqlite/1.18.0"; // THIS CANNOT IMPORT ANYTHING FROM THE SERVER // EXCEPT FOR THE DATABASE AND THE SCHEMA @@ -77,7 +78,8 @@ const migrations = [ { version: "1.15.3", run: m34 }, { version: "1.15.4", run: m35 }, { version: "1.16.0", run: m36 }, - { version: "1.17.0", run: m37 } + { version: "1.17.0", run: m37 }, + { version: "1.18.0", run: m38 } // Add new migrations here as they are created ] as const; diff --git a/server/setup/scriptsPg/1.18.0.ts b/server/setup/scriptsPg/1.18.0.ts new file mode 100644 index 000000000..2f2b3067c --- /dev/null +++ b/server/setup/scriptsPg/1.18.0.ts @@ -0,0 +1,489 @@ +import { db } from "@server/db/pg/driver"; +import { sql } from "drizzle-orm"; + +const version = "1.18.0"; + +export default async function migration() { + console.log(`Running setup script ${version}...`); + + // Query existing targetHealthCheck data with joined siteId and orgId before + // the transaction adds the new columns (which start NULL for existing rows). + // We will delete all rows and reinsert them with targetHealthCheckId = targetId + // so the two IDs form a stable 1:1 mapping. + const healthChecksQuery = await db.execute( + sql`SELECT + thc."targetHealthCheckId", + thc."targetId", + t."siteId", + s."orgId", + thc."hcEnabled", + thc."hcPath", + thc."hcScheme", + thc."hcMode", + thc."hcHostname", + thc."hcPort", + thc."hcInterval", + thc."hcUnhealthyInterval", + thc."hcTimeout", + thc."hcHeaders", + thc."hcFollowRedirects", + thc."hcMethod", + thc."hcStatus", + thc."hcHealth", + thc."hcTlsServerName" + FROM "targetHealthCheck" thc + JOIN "targets" t ON thc."targetId" = t."targetId" + JOIN "sites" s ON t."siteId" = s."siteId"` + ); + const existingHealthChecks = healthChecksQuery.rows as { + targetHealthCheckId: number; + targetId: number; + siteId: number; + orgId: string; + hcEnabled: boolean; + hcPath: string | null; + hcScheme: string | null; + hcMode: string | null; + hcHostname: string | null; + hcPort: number | null; + hcInterval: number | null; + hcUnhealthyInterval: number | null; + hcTimeout: number | null; + hcHeaders: string | null; + hcFollowRedirects: boolean | null; + hcMethod: string | null; + hcStatus: number | null; + hcHealth: string | null; + hcTlsServerName: string | null; + }[]; + + console.log( + `Found ${existingHealthChecks.length} existing targetHealthCheck row(s) to migrate` + ); + + // Query existing siteResources with siteId before it is dropped by the DDL below. + const siteResourcesForNetworkQuery = await db.execute( + sql`SELECT sr."siteResourceId", sr."orgId", sr."siteId" + FROM "siteResources" sr + WHERE sr."siteId" IS NOT NULL` + ); + const existingSiteResourcesForNetwork = siteResourcesForNetworkQuery.rows as { + siteResourceId: number; + orgId: string; + siteId: number; + }[]; + + console.log( + `Found ${existingSiteResourcesForNetwork.length} existing siteResource(s) to migrate to networks` + ); + + try { + await db.execute(sql`BEGIN`); + + await db.execute(sql` + CREATE TABLE "alertEmailActions" ( + "emailActionId" serial PRIMARY KEY NOT NULL, + "alertRuleId" integer NOT NULL, + "enabled" boolean DEFAULT true NOT NULL, + "lastSentAt" bigint + ); + `); + + await db.execute(sql` + CREATE TABLE "alertEmailRecipients" ( + "recipientId" serial PRIMARY KEY NOT NULL, + "emailActionId" integer NOT NULL, + "userId" varchar, + "roleId" integer, + "email" varchar(255) + ); + `); + + await db.execute(sql` + CREATE TABLE "alertHealthChecks" ( + "alertRuleId" integer NOT NULL, + "healthCheckId" integer NOT NULL + ); + `); + + await db.execute(sql` + CREATE TABLE "alertResources" ( + "alertRuleId" integer NOT NULL, + "resourceId" integer NOT NULL + ); + `); + + await db.execute(sql` + CREATE TABLE "alertRules" ( + "alertRuleId" serial PRIMARY KEY NOT NULL, + "orgId" varchar(255) NOT NULL, + "name" varchar(255) NOT NULL, + "eventType" varchar(100) NOT NULL, + "enabled" boolean DEFAULT true NOT NULL, + "cooldownSeconds" integer DEFAULT 300 NOT NULL, + "allSites" boolean DEFAULT false NOT NULL, + "allHealthChecks" boolean DEFAULT false NOT NULL, + "allResources" boolean DEFAULT false NOT NULL, + "lastTriggeredAt" bigint, + "createdAt" bigint NOT NULL, + "updatedAt" bigint NOT NULL + ); + `); + + await db.execute(sql` + CREATE TABLE "alertSites" ( + "alertRuleId" integer NOT NULL, + "siteId" integer NOT NULL + ); + `); + + await db.execute(sql` + CREATE TABLE "alertWebhookActions" ( + "webhookActionId" serial PRIMARY KEY NOT NULL, + "alertRuleId" integer NOT NULL, + "webhookUrl" text NOT NULL, + "config" text, + "enabled" boolean DEFAULT true NOT NULL, + "lastSentAt" bigint + ); + `); + + await db.execute(sql` + CREATE TABLE "networks" ( + "networkId" serial PRIMARY KEY NOT NULL, + "niceId" text, + "name" text, + "scope" varchar DEFAULT 'global' NOT NULL, + "orgId" varchar NOT NULL + ); + `); + + await db.execute(sql` + CREATE TABLE "siteNetworks" ( + "siteId" integer NOT NULL, + "networkId" integer NOT NULL + ); + `); + + await db.execute(sql` + CREATE TABLE "statusHistory" ( + "id" serial PRIMARY KEY NOT NULL, + "entityType" varchar NOT NULL, + "entityId" integer NOT NULL, + "orgId" varchar NOT NULL, + "status" varchar NOT NULL, + "timestamp" integer NOT NULL + ); + `); + + await db.execute(sql` + ALTER TABLE "siteResources" DROP CONSTRAINT "siteResources_siteId_sites_siteId_fk"; + `); + + await db.execute(sql` + ALTER TABLE "targetHealthCheck" ALTER COLUMN "targetId" DROP NOT NULL; + `); + + await db.execute(sql` + ALTER TABLE "subscriptions" ADD COLUMN "expiresAt" bigint; + `); + + await db.execute(sql` + ALTER TABLE "subscriptions" ADD COLUMN "trial" boolean DEFAULT false; + `); + + await db.execute(sql` + ALTER TABLE "requestAuditLog" ADD COLUMN "siteResourceId" integer; + `); + + await db.execute(sql` + ALTER TABLE "siteResources" ADD COLUMN "networkId" integer; + `); + + await db.execute(sql` + ALTER TABLE "siteResources" ADD COLUMN "defaultNetworkId" integer; + `); + + await db.execute(sql` + ALTER TABLE "siteResources" ADD COLUMN "ssl" boolean DEFAULT false NOT NULL; + `); + + await db.execute(sql` + ALTER TABLE "siteResources" ADD COLUMN "scheme" varchar; + `); + + await db.execute(sql` + ALTER TABLE "siteResources" ADD COLUMN "domainId" varchar; + `); + + await db.execute(sql` + ALTER TABLE "siteResources" ADD COLUMN "subdomain" varchar; + `); + + await db.execute(sql` + ALTER TABLE "siteResources" ADD COLUMN "fullDomain" varchar; + `); + + // Add orgId and siteId as nullable first; NOT NULL constraints are applied + // after the data migration below once every row has been populated. + await db.execute(sql` + ALTER TABLE "targetHealthCheck" ADD COLUMN "orgId" varchar; + `); + + await db.execute(sql` + ALTER TABLE "targetHealthCheck" ADD COLUMN "siteId" integer; + `); + + await db.execute(sql` + ALTER TABLE "targetHealthCheck" ADD COLUMN "name" varchar; + `); + + await db.execute(sql` + ALTER TABLE "targetHealthCheck" ADD COLUMN "hcHealthyThreshold" integer DEFAULT 1; + `); + + await db.execute(sql` + ALTER TABLE "targetHealthCheck" ADD COLUMN "hcUnhealthyThreshold" integer DEFAULT 1; + `); + + await db.execute(sql` + ALTER TABLE "alertEmailActions" ADD CONSTRAINT "alertEmailActions_alertRuleId_alertRules_alertRuleId_fk" FOREIGN KEY ("alertRuleId") REFERENCES "public"."alertRules"("alertRuleId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "alertEmailRecipients" ADD CONSTRAINT "alertEmailRecipients_emailActionId_alertEmailActions_emailActionId_fk" FOREIGN KEY ("emailActionId") REFERENCES "public"."alertEmailActions"("emailActionId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "alertEmailRecipients" ADD CONSTRAINT "alertEmailRecipients_userId_user_id_fk" FOREIGN KEY ("userId") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "alertEmailRecipients" ADD CONSTRAINT "alertEmailRecipients_roleId_roles_roleId_fk" FOREIGN KEY ("roleId") REFERENCES "public"."roles"("roleId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "alertHealthChecks" ADD CONSTRAINT "alertHealthChecks_alertRuleId_alertRules_alertRuleId_fk" FOREIGN KEY ("alertRuleId") REFERENCES "public"."alertRules"("alertRuleId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "alertHealthChecks" ADD CONSTRAINT "alertHealthChecks_healthCheckId_targetHealthCheck_targetHealthCheckId_fk" FOREIGN KEY ("healthCheckId") REFERENCES "public"."targetHealthCheck"("targetHealthCheckId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "alertResources" ADD CONSTRAINT "alertResources_alertRuleId_alertRules_alertRuleId_fk" FOREIGN KEY ("alertRuleId") REFERENCES "public"."alertRules"("alertRuleId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "alertResources" ADD CONSTRAINT "alertResources_resourceId_resources_resourceId_fk" FOREIGN KEY ("resourceId") REFERENCES "public"."resources"("resourceId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "alertRules" ADD CONSTRAINT "alertRules_orgId_orgs_orgId_fk" FOREIGN KEY ("orgId") REFERENCES "public"."orgs"("orgId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "alertSites" ADD CONSTRAINT "alertSites_alertRuleId_alertRules_alertRuleId_fk" FOREIGN KEY ("alertRuleId") REFERENCES "public"."alertRules"("alertRuleId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "alertSites" ADD CONSTRAINT "alertSites_siteId_sites_siteId_fk" FOREIGN KEY ("siteId") REFERENCES "public"."sites"("siteId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "alertWebhookActions" ADD CONSTRAINT "alertWebhookActions_alertRuleId_alertRules_alertRuleId_fk" FOREIGN KEY ("alertRuleId") REFERENCES "public"."alertRules"("alertRuleId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "networks" ADD CONSTRAINT "networks_orgId_orgs_orgId_fk" FOREIGN KEY ("orgId") REFERENCES "public"."orgs"("orgId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "siteNetworks" ADD CONSTRAINT "siteNetworks_siteId_sites_siteId_fk" FOREIGN KEY ("siteId") REFERENCES "public"."sites"("siteId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "siteNetworks" ADD CONSTRAINT "siteNetworks_networkId_networks_networkId_fk" FOREIGN KEY ("networkId") REFERENCES "public"."networks"("networkId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "statusHistory" ADD CONSTRAINT "statusHistory_orgId_orgs_orgId_fk" FOREIGN KEY ("orgId") REFERENCES "public"."orgs"("orgId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + CREATE INDEX "idx_statusHistory_entity" ON "statusHistory" USING btree ("entityType","entityId","timestamp"); + `); + + await db.execute(sql` + CREATE INDEX "idx_statusHistory_org_timestamp" ON "statusHistory" USING btree ("orgId","timestamp"); + `); + + await db.execute(sql` + ALTER TABLE "siteResources" ADD CONSTRAINT "siteResources_networkId_networks_networkId_fk" FOREIGN KEY ("networkId") REFERENCES "public"."networks"("networkId") ON DELETE set null ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "siteResources" ADD CONSTRAINT "siteResources_defaultNetworkId_networks_networkId_fk" FOREIGN KEY ("defaultNetworkId") REFERENCES "public"."networks"("networkId") ON DELETE restrict ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "siteResources" ADD CONSTRAINT "siteResources_domainId_domains_domainId_fk" FOREIGN KEY ("domainId") REFERENCES "public"."domains"("domainId") ON DELETE set null ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "targetHealthCheck" ADD CONSTRAINT "targetHealthCheck_orgId_orgs_orgId_fk" FOREIGN KEY ("orgId") REFERENCES "public"."orgs"("orgId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "targetHealthCheck" ADD CONSTRAINT "targetHealthCheck_siteId_sites_siteId_fk" FOREIGN KEY ("siteId") REFERENCES "public"."sites"("siteId") ON DELETE cascade ON UPDATE no action; + `); + + await db.execute(sql` + ALTER TABLE "siteResources" DROP COLUMN "siteId"; + `); + + await db.execute(sql` + ALTER TABLE "siteResources" DROP COLUMN "protocol"; + `); + + await db.execute(sql`COMMIT`); + console.log("Migrated database"); + } catch (e) { + await db.execute(sql`ROLLBACK`); + console.log("Unable to migrate database"); + console.log(e); + throw e; + } + + // Reinsert targetHealthCheck rows with corrected IDs: + // targetHealthCheckId is set to the same integer as targetId (1:1 mapping), + // siteId and orgId are populated from the associated target and site. + // + // Because targetHealthCheckId is a serial (sequence-backed) column, inserting + // explicit values is allowed in PostgreSQL — the sequence is simply bypassed. + // After all inserts we advance the sequence to MAX(targetHealthCheckId) via + // setval() so future auto-inserts never collide with the explicit IDs we used. + if (existingHealthChecks.length > 0) { + try { + // Remove all existing rows first. The alertHealthChecks table is brand + // new in this migration so there are no FK references to worry about. + await db.execute(sql`DELETE FROM "targetHealthCheck"`); + + for (const hc of existingHealthChecks) { + await db.execute(sql` + INSERT INTO "targetHealthCheck" ( + "targetHealthCheckId", + "targetId", + "orgId", + "siteId", + "hcEnabled", + "hcPath", + "hcScheme", + "hcMode", + "hcHostname", + "hcPort", + "hcInterval", + "hcUnhealthyInterval", + "hcTimeout", + "hcHeaders", + "hcFollowRedirects", + "hcMethod", + "hcStatus", + "hcHealth", + "hcTlsServerName" + ) VALUES ( + ${hc.targetId}, + ${hc.targetId}, + ${hc.orgId}, + ${hc.siteId}, + ${hc.hcEnabled}, + ${hc.hcPath}, + ${hc.hcScheme}, + ${hc.hcMode}, + ${hc.hcHostname}, + ${hc.hcPort}, + ${hc.hcInterval}, + ${hc.hcUnhealthyInterval}, + ${hc.hcTimeout}, + ${hc.hcHeaders}, + ${hc.hcFollowRedirects}, + ${hc.hcMethod}, + ${hc.hcStatus}, + ${hc.hcHealth}, + ${hc.hcTlsServerName} + ) + `); + } + + // Now that every row has orgId and siteId populated, enforce NOT NULL. + await db.execute( + sql`ALTER TABLE "targetHealthCheck" ALTER COLUMN "orgId" SET NOT NULL` + ); + await db.execute( + sql`ALTER TABLE "targetHealthCheck" ALTER COLUMN "siteId" SET NOT NULL` + ); + + // Advance the sequence so the next auto-insert picks up after the + // largest ID we explicitly wrote. setval(..., max, true) means the + // next nextval() call will return max + 1. + await db.execute(sql` + SELECT setval( + pg_get_serial_sequence('"targetHealthCheck"', 'targetHealthCheckId'), + (SELECT MAX("targetHealthCheckId") FROM "targetHealthCheck"), + true + ) + `); + + console.log( + `Migrated ${existingHealthChecks.length} targetHealthCheck row(s) with corrected IDs` + ); + } catch (e) { + console.error( + "Error while migrating targetHealthCheck rows:", + e + ); + throw e; + } + } + + // Create a dedicated "resource"-scoped network for each existing siteResource, + // populate siteNetworks with the old siteId, and set networkId / defaultNetworkId + // on the siteResource row. + if (existingSiteResourcesForNetwork.length > 0) { + try { + for (const sr of existingSiteResourcesForNetwork) { + const networkResult = await db.execute(sql` + INSERT INTO "networks" ("scope", "orgId") + VALUES ('resource', ${sr.orgId}) + RETURNING "networkId" + `); + const networkId = ( + networkResult.rows[0] as { networkId: number } + ).networkId; + + await db.execute(sql` + INSERT INTO "siteNetworks" ("siteId", "networkId") + VALUES (${sr.siteId}, ${networkId}) + `); + + await db.execute(sql` + UPDATE "siteResources" + SET "networkId" = ${networkId}, "defaultNetworkId" = ${networkId} + WHERE "siteResourceId" = ${sr.siteResourceId} + `); + } + + console.log( + `Migrated ${existingSiteResourcesForNetwork.length} siteResource(s) to networks` + ); + } catch (e) { + console.error( + "Error while migrating siteResources to networks:", + e + ); + throw e; + } + } + + console.log(`${version} migration complete`); +} diff --git a/server/setup/scriptsSqlite/1.18.0.ts b/server/setup/scriptsSqlite/1.18.0.ts new file mode 100644 index 000000000..c9d2ddc95 --- /dev/null +++ b/server/setup/scriptsSqlite/1.18.0.ts @@ -0,0 +1,452 @@ +import { APP_PATH } from "@server/lib/consts"; +import Database from "better-sqlite3"; +import path from "path"; + +const version = "1.18.0"; + +export default async function migration() { + console.log(`Running setup script ${version}...`); + + const location = path.join(APP_PATH, "db", "db.sqlite"); + const db = new Database(location); + + try { + db.pragma("foreign_keys = OFF"); + + // Query existing targetHealthCheck data with joined siteId and orgId before + // the transaction drops and recreates the table + const existingHealthChecks = db + .prepare( + `SELECT + thc."targetHealthCheckId", + thc."targetId", + t."siteId", + s."orgId", + thc."hcEnabled", + thc."hcPath", + thc."hcScheme", + thc."hcMode", + thc."hcHostname", + thc."hcPort", + thc."hcInterval", + thc."hcUnhealthyInterval", + thc."hcTimeout", + thc."hcHeaders", + thc."hcFollowRedirects", + thc."hcMethod", + thc."hcStatus", + thc."hcHealth", + thc."hcTlsServerName" + FROM 'targetHealthCheck' thc + JOIN 'targets' t ON thc."targetId" = t."targetId" + JOIN 'sites' s ON t."siteId" = s."siteId"` + ) + .all() as { + targetHealthCheckId: number; + targetId: number; + siteId: number; + orgId: string; + hcEnabled: number; + hcPath: string | null; + hcScheme: string | null; + hcMode: string | null; + hcHostname: string | null; + hcPort: number | null; + hcInterval: number | null; + hcUnhealthyInterval: number | null; + hcTimeout: number | null; + hcHeaders: string | null; + hcFollowRedirects: number | null; + hcMethod: string | null; + hcStatus: number | null; + hcHealth: string | null; + hcTlsServerName: string | null; + }[]; + + console.log( + `Found ${existingHealthChecks.length} existing targetHealthCheck row(s) to migrate` + ); + + // Query existing siteResources with siteId before the transaction recreates + // the table without that column. We use this data below to create a dedicated + // network for each resource. + const existingSiteResourcesForNetwork = db + .prepare( + `SELECT sr."siteResourceId", sr."orgId", sr."siteId" + FROM 'siteResources' sr + WHERE sr."siteId" IS NOT NULL` + ) + .all() as { + siteResourceId: number; + orgId: string; + siteId: number; + }[]; + + console.log( + `Found ${existingSiteResourcesForNetwork.length} existing siteResource(s) to migrate to networks` + ); + + db.transaction(() => { + db.prepare( + ` + CREATE TABLE 'alertEmailActions' ( + 'emailActionId' integer PRIMARY KEY AUTOINCREMENT NOT NULL, + 'alertRuleId' integer NOT NULL, + 'enabled' integer DEFAULT true NOT NULL, + 'lastSentAt' integer, + FOREIGN KEY ('alertRuleId') REFERENCES 'alertRules'('alertRuleId') ON UPDATE no action ON DELETE cascade + ); + ` + ).run(); + db.prepare( + ` + CREATE TABLE 'alertEmailRecipients' ( + 'recipientId' integer PRIMARY KEY AUTOINCREMENT NOT NULL, + 'emailActionId' integer NOT NULL, + 'userId' text, + 'roleId' integer, + 'email' text, + FOREIGN KEY ('emailActionId') REFERENCES 'alertEmailActions'('emailActionId') ON UPDATE no action ON DELETE cascade, + FOREIGN KEY ('userId') REFERENCES 'user'('id') ON UPDATE no action ON DELETE cascade, + FOREIGN KEY ('roleId') REFERENCES 'roles'('roleId') ON UPDATE no action ON DELETE cascade + ); + ` + ).run(); + db.prepare( + ` + CREATE TABLE 'alertHealthChecks' ( + 'alertRuleId' integer NOT NULL, + 'healthCheckId' integer NOT NULL, + FOREIGN KEY ('alertRuleId') REFERENCES 'alertRules'('alertRuleId') ON UPDATE no action ON DELETE cascade, + FOREIGN KEY ('healthCheckId') REFERENCES 'targetHealthCheck'('targetHealthCheckId') ON UPDATE no action ON DELETE cascade + ); + ` + ).run(); + db.prepare( + ` + CREATE TABLE 'alertResources' ( + 'alertRuleId' integer NOT NULL, + 'resourceId' integer NOT NULL, + FOREIGN KEY ('alertRuleId') REFERENCES 'alertRules'('alertRuleId') ON UPDATE no action ON DELETE cascade, + FOREIGN KEY ('resourceId') REFERENCES 'resources'('resourceId') ON UPDATE no action ON DELETE cascade + ); + ` + ).run(); + db.prepare( + ` + CREATE TABLE 'alertRules' ( + 'alertRuleId' integer PRIMARY KEY AUTOINCREMENT NOT NULL, + 'orgId' text NOT NULL, + 'name' text NOT NULL, + 'eventType' text NOT NULL, + 'enabled' integer DEFAULT true NOT NULL, + 'cooldownSeconds' integer DEFAULT 300 NOT NULL, + 'allSites' integer DEFAULT false NOT NULL, + 'allHealthChecks' integer DEFAULT false NOT NULL, + 'allResources' integer DEFAULT false NOT NULL, + 'lastTriggeredAt' integer, + 'createdAt' integer NOT NULL, + 'updatedAt' integer NOT NULL, + FOREIGN KEY ('orgId') REFERENCES 'orgs'('orgId') ON UPDATE no action ON DELETE cascade + ); + ` + ).run(); + db.prepare( + ` + CREATE TABLE 'alertSites' ( + 'alertRuleId' integer NOT NULL, + 'siteId' integer NOT NULL, + FOREIGN KEY ('alertRuleId') REFERENCES 'alertRules'('alertRuleId') ON UPDATE no action ON DELETE cascade, + FOREIGN KEY ('siteId') REFERENCES 'sites'('siteId') ON UPDATE no action ON DELETE cascade + ); + ` + ).run(); + db.prepare( + ` + CREATE TABLE 'alertWebhookActions' ( + 'webhookActionId' integer PRIMARY KEY AUTOINCREMENT NOT NULL, + 'alertRuleId' integer NOT NULL, + 'webhookUrl' text NOT NULL, + 'config' text, + 'enabled' integer DEFAULT true NOT NULL, + 'lastSentAt' integer, + FOREIGN KEY ('alertRuleId') REFERENCES 'alertRules'('alertRuleId') ON UPDATE no action ON DELETE cascade + ); + ` + ).run(); + db.prepare( + ` + CREATE TABLE 'networks' ( + 'networkId' integer PRIMARY KEY AUTOINCREMENT NOT NULL, + 'niceId' text, + 'name' text, + 'scope' text DEFAULT 'global' NOT NULL, + 'orgId' text NOT NULL, + FOREIGN KEY ('orgId') REFERENCES 'orgs'('orgId') ON UPDATE no action ON DELETE cascade + ); + ` + ).run(); + db.prepare( + ` + CREATE TABLE 'siteNetworks' ( + 'siteId' integer NOT NULL, + 'networkId' integer NOT NULL, + FOREIGN KEY ('siteId') REFERENCES 'sites'('siteId') ON UPDATE no action ON DELETE cascade, + FOREIGN KEY ('networkId') REFERENCES 'networks'('networkId') ON UPDATE no action ON DELETE cascade + ); + ` + ).run(); + db.prepare( + ` + CREATE TABLE 'statusHistory' ( + 'id' integer PRIMARY KEY AUTOINCREMENT NOT NULL, + 'entityType' text NOT NULL, + 'entityId' integer NOT NULL, + 'orgId' text NOT NULL, + 'status' text NOT NULL, + 'timestamp' integer NOT NULL, + FOREIGN KEY ('orgId') REFERENCES 'orgs'('orgId') ON UPDATE no action ON DELETE cascade + ); + ` + ).run(); + db.prepare( + ` + CREATE INDEX 'idx_statusHistory_entity' ON 'statusHistory' ('entityType','entityId','timestamp'); + ` + ).run(); + db.prepare( + ` + CREATE INDEX 'idx_statusHistory_org_timestamp' ON 'statusHistory' ('orgId','timestamp'); + ` + ).run(); + + db.prepare( + ` + CREATE TABLE '__new_siteResources' ( + 'siteResourceId' integer PRIMARY KEY AUTOINCREMENT NOT NULL, + 'orgId' text NOT NULL, + 'networkId' integer, + 'defaultNetworkId' integer, + 'niceId' text NOT NULL, + 'name' text NOT NULL, + 'ssl' integer DEFAULT false NOT NULL, + 'mode' text NOT NULL, + 'scheme' text, + 'proxyPort' integer, + 'destinationPort' integer, + 'destination' text NOT NULL, + 'enabled' integer DEFAULT true NOT NULL, + 'alias' text, + 'aliasAddress' text, + 'tcpPortRangeString' text DEFAULT '*' NOT NULL, + 'udpPortRangeString' text DEFAULT '*' NOT NULL, + 'disableIcmp' integer DEFAULT false NOT NULL, + 'authDaemonPort' integer DEFAULT 22123, + 'authDaemonMode' text DEFAULT 'site', + 'domainId' text, + 'subdomain' text, + 'fullDomain' text, + FOREIGN KEY ('orgId') REFERENCES 'orgs'('orgId') ON UPDATE no action ON DELETE cascade, + FOREIGN KEY ('networkId') REFERENCES 'networks'('networkId') ON UPDATE no action ON DELETE set null, + FOREIGN KEY ('defaultNetworkId') REFERENCES 'networks'('networkId') ON UPDATE no action ON DELETE restrict, + FOREIGN KEY ('domainId') REFERENCES 'domains'('domainId') ON UPDATE no action ON DELETE set null + ); + ` + ).run(); + db.prepare( + ` + INSERT INTO '__new_siteResources'("siteResourceId", "orgId", "networkId", "defaultNetworkId", "niceId", "name", "ssl", "mode", "scheme", "proxyPort", "destinationPort", "destination", "enabled", "alias", "aliasAddress", "tcpPortRangeString", "udpPortRangeString", "disableIcmp", "authDaemonPort", "authDaemonMode", "domainId", "subdomain", "fullDomain") SELECT "siteResourceId", "orgId", NULL, NULL, "niceId", "name", 0, "mode", NULL, "proxyPort", "destinationPort", "destination", "enabled", "alias", "aliasAddress", "tcpPortRangeString", "udpPortRangeString", "disableIcmp", "authDaemonPort", "authDaemonMode", NULL, NULL, NULL FROM 'siteResources'; + ` + ).run(); + db.prepare( + ` + DROP TABLE 'siteResources'; + ` + ).run(); + db.prepare( + ` + ALTER TABLE '__new_siteResources' RENAME TO 'siteResources'; + ` + ).run(); + db.prepare( + ` + CREATE TABLE '__new_targetHealthCheck' ( + 'targetHealthCheckId' integer PRIMARY KEY AUTOINCREMENT NOT NULL, + 'targetId' integer, + 'orgId' text NOT NULL, + 'siteId' integer NOT NULL, + 'name' text, + 'hcEnabled' integer DEFAULT false NOT NULL, + 'hcPath' text, + 'hcScheme' text, + 'hcMode' text DEFAULT 'http', + 'hcHostname' text, + 'hcPort' integer, + 'hcInterval' integer DEFAULT 30, + 'hcUnhealthyInterval' integer DEFAULT 30, + 'hcTimeout' integer DEFAULT 5, + 'hcHeaders' text, + 'hcFollowRedirects' integer DEFAULT true, + 'hcMethod' text DEFAULT 'GET', + 'hcStatus' integer, + 'hcHealth' text DEFAULT 'unknown', + 'hcTlsServerName' text, + 'hcHealthyThreshold' integer DEFAULT 1, + 'hcUnhealthyThreshold' integer DEFAULT 1, + FOREIGN KEY ('targetId') REFERENCES 'targets'('targetId') ON UPDATE no action ON DELETE cascade, + FOREIGN KEY ('orgId') REFERENCES 'orgs'('orgId') ON UPDATE no action ON DELETE cascade, + FOREIGN KEY ('siteId') REFERENCES 'sites'('siteId') ON UPDATE no action ON DELETE cascade + ); + ` + ).run(); + // INSERT INTO '__new_targetHealthCheck'("targetHealthCheckId", "targetId", "orgId", "siteId", "name", "hcEnabled", "hcPath", "hcScheme", "hcMode", "hcHostname", "hcPort", "hcInterval", "hcUnhealthyInterval", "hcTimeout", "hcHeaders", "hcFollowRedirects", "hcMethod", "hcStatus", "hcHealth", "hcTlsServerName", "hcHealthyThreshold", "hcUnhealthyThreshold") SELECT "targetHealthCheckId", "targetId", "orgId", "siteId", "name", "hcEnabled", "hcPath", "hcScheme", "hcMode", "hcHostname", "hcPort", "hcInterval", "hcUnhealthyInterval", "hcTimeout", "hcHeaders", "hcFollowRedirects", "hcMethod", "hcStatus", "hcHealth", "hcTlsServerName", "hcHealthyThreshold", "hcUnhealthyThreshold" FROM 'targetHealthCheck'; + db.prepare( + ` + DROP TABLE 'targetHealthCheck'; + ` + ).run(); + db.prepare( + ` + ALTER TABLE '__new_targetHealthCheck' RENAME TO 'targetHealthCheck'; + ` + ).run(); + db.prepare( + ` + ALTER TABLE 'subscriptions' ADD 'expiresAt' integer; + ` + ).run(); + db.prepare( + ` + ALTER TABLE 'subscriptions' ADD 'trial' integer DEFAULT false; + ` + ).run(); + db.prepare( + ` + ALTER TABLE 'requestAuditLog' ADD 'siteResourceId' integer; + ` + ).run(); + db.prepare( + ` + ALTER TABLE 'sites' ADD 'networkId' integer REFERENCES networks(networkId); + ` + ).run(); + })(); + + db.pragma("foreign_keys = ON"); + + // Create a dedicated network for each existing siteResource and link the + // old siteId via siteNetworks. Then set networkId and defaultNetworkId on + // the siteResource row so the app can use the new network model. + if (existingSiteResourcesForNetwork.length > 0) { + const insertNetwork = db.prepare( + `INSERT INTO 'networks' ("scope", "orgId") VALUES (?, ?)` + ); + const insertSiteNetwork = db.prepare( + `INSERT INTO 'siteNetworks' ("siteId", "networkId") VALUES (?, ?)` + ); + const updateSiteResource = db.prepare( + `UPDATE 'siteResources' SET "networkId" = ?, "defaultNetworkId" = ? WHERE "siteResourceId" = ?` + ); + + const migrateNetworks = db.transaction(() => { + for (const sr of existingSiteResourcesForNetwork) { + const result = insertNetwork.run("resource", sr.orgId); + const networkId = result.lastInsertRowid as number; + insertSiteNetwork.run(sr.siteId, networkId); + updateSiteResource.run(networkId, networkId, sr.siteResourceId); + } + }); + + migrateNetworks(); + + console.log( + `Migrated ${existingSiteResourcesForNetwork.length} siteResource(s) to networks` + ); + } + + // Re-insert targetHealthCheck rows with corrected IDs: + // targetHealthCheckId is set to the same integer as targetId (1:1 mapping), + // siteId and orgId are populated from the associated target and site. + // + // Because targetHealthCheckId is AUTOINCREMENT, inserting explicit values is + // allowed, but sqlite_sequence must be updated afterwards so future + // auto-increments don't reuse or collide with these IDs. + if (existingHealthChecks.length > 0) { + const insertHealthCheck = db.prepare( + `INSERT INTO 'targetHealthCheck' ( + "targetHealthCheckId", + "targetId", + "orgId", + "siteId", + "hcEnabled", + "hcPath", + "hcScheme", + "hcMode", + "hcHostname", + "hcPort", + "hcInterval", + "hcUnhealthyInterval", + "hcTimeout", + "hcHeaders", + "hcFollowRedirects", + "hcMethod", + "hcStatus", + "hcHealth", + "hcTlsServerName" + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + ); + + const insertAll = db.transaction(() => { + for (const hc of existingHealthChecks) { + insertHealthCheck.run( + hc.targetId, // targetHealthCheckId = targetId (explicit, non-sequential is fine) + hc.targetId, + hc.orgId, + hc.siteId, + hc.hcEnabled, + hc.hcPath, + hc.hcScheme, + hc.hcMode, + hc.hcHostname, + hc.hcPort, + hc.hcInterval, + hc.hcUnhealthyInterval, + hc.hcTimeout, + hc.hcHeaders, + hc.hcFollowRedirects, + hc.hcMethod, + hc.hcStatus, + hc.hcHealth, + hc.hcTlsServerName + ); + } + }); + + insertAll(); + + // Ensure sqlite_sequence reflects the true max so that future + // AUTOINCREMENT inserts never reuse one of the explicitly-set IDs. + // INSERT OR IGNORE handles the case where no auto-insert has happened + // yet and the row doesn't exist in sqlite_sequence. + db.prepare( + `INSERT OR IGNORE INTO sqlite_sequence (name, seq) VALUES ('targetHealthCheck', 0)` + ).run(); + db.prepare( + `UPDATE sqlite_sequence + SET seq = MAX(seq, (SELECT COALESCE(MAX("targetHealthCheckId"), 0) FROM 'targetHealthCheck')) + WHERE name = 'targetHealthCheck'` + ).run(); + + console.log( + `Migrated ${existingHealthChecks.length} targetHealthCheck row(s) with corrected IDs` + ); + } + + console.log(`Migrated database`); + } catch (e) { + console.log("Failed to migrate db:", e); + throw e; + } + + console.log(`${version} migration complete`); +} diff --git a/src/app/[orgId]/layout.tsx b/src/app/[orgId]/layout.tsx index 8dc28001e..fe0077427 100644 --- a/src/app/[orgId]/layout.tsx +++ b/src/app/[orgId]/layout.tsx @@ -21,6 +21,7 @@ import { Layout } from "@app/components/Layout"; import ApplyInternalRedirect from "@app/components/ApplyInternalRedirect"; import SubscriptionViolation from "@app/components/SubscriptionViolation"; + export default async function OrgLayout(props: { children: React.ReactNode; params: Promise<{ orgId: string }>; @@ -110,6 +111,7 @@ export default async function OrgLayout(props: { {props.children} {build === "saas" && } + ); diff --git a/src/app/[orgId]/settings/(private)/billing/page.tsx b/src/app/[orgId]/settings/(private)/billing/page.tsx index 150725e32..8f714336a 100644 --- a/src/app/[orgId]/settings/(private)/billing/page.tsx +++ b/src/app/[orgId]/settings/(private)/billing/page.tsx @@ -219,6 +219,7 @@ export default function BillingPage() { ); const [hasSubscription, setHasSubscription] = useState(false); + const [isTrial, setIsTrial] = useState(false); const [isLoading, setIsLoading] = useState(false); const [currentTier, setCurrentTier] = useState(null); @@ -263,6 +264,7 @@ export default function BillingPage() { setHasSubscription( tierSub.subscription.status === "active" ); + setIsTrial(tierSub.subscription.expiresAt != null); } // Find license subscription @@ -558,7 +560,7 @@ export default function BillingPage() { // Get button label and action for each plan const getPlanAction = (plan: PlanOption) => { if (plan.id === "enterprise") { - if (plan.id === currentPlanId) { + if (plan.id === currentPlanId && !isTrial) { return { label: "Manage Current Plan", action: handleModifySubscription, @@ -597,6 +599,19 @@ export default function BillingPage() { disabled: false }; } + // If this is a trial subscription, show an upgrade button that starts a real checkout + if (isTrial) { + return { + label: "Upgrade", + action: () => { + if (plan.tierType) { + handleStartSubscription(plan.tierType); + } + }, + variant: "default" as const, + disabled: isProblematicState + }; + } return { label: "Manage Current Plan", action: handleModifySubscription, @@ -610,7 +625,8 @@ export default function BillingPage() { ); const planIndex = planOptions.findIndex((p) => p.id === plan.id); - if (planIndex < currentIndex) { + // During a trial, never show a downgrade option — all non-current plans are upgrades + if (!isTrial && planIndex < currentIndex) { return { label: "Downgrade", action: () => { @@ -642,18 +658,23 @@ export default function BillingPage() { label: "Upgrade", action: () => { if (plan.tierType) { - showTierConfirmation( - plan.tierType, - "upgrade", - plan.name, - plan.price + (" " + plan.priceDetail || "") - ); + // During a trial, go straight to checkout instead of the tier-change flow + if (isTrial) { + handleStartSubscription(plan.tierType); + } else { + showTierConfirmation( + plan.tierType, + "upgrade", + plan.name, + plan.price + (" " + plan.priceDetail || "") + ); + } } else { handleModifySubscription(); } }, variant: "outline" as const, - disabled: isProblematicState + disabled: isProblematicState || (isTrial && plan.id == "basic") }; }; diff --git a/src/app/[orgId]/settings/access/roles/page.tsx b/src/app/[orgId]/settings/access/roles/page.tsx index c1ecb2b12..218b035d3 100644 --- a/src/app/[orgId]/settings/access/roles/page.tsx +++ b/src/app/[orgId]/settings/access/roles/page.tsx @@ -16,24 +16,32 @@ export const metadata: Metadata = { type RolesPageProps = { params: Promise<{ orgId: string }>; + searchParams: Promise>; }; export const dynamic = "force-dynamic"; export default async function RolesPage(props: RolesPageProps) { const params = await props.params; + const searchParams = new URLSearchParams(await props.searchParams); let roles: ListRolesResponse["roles"] = []; + let pagination: ListRolesResponse["pagination"] = { + total: 0, + page: 1, + pageSize: 20 + }; let hasInvitations = false; const res = await internal .get< AxiosResponse - >(`/org/${params.orgId}/roles`, await authCookieHeader()) + >(`/org/${params.orgId}/roles?${searchParams.toString()}`, await authCookieHeader()) .catch((e) => {}); if (res && res.status === 200) { roles = res.data.data.roles; + pagination = res.data.data.pagination; } const invitationsRes = await internal @@ -68,7 +76,14 @@ export default async function RolesPage(props: RolesPageProps) { description={t("accessRolesDescription")} /> - + ); diff --git a/src/app/[orgId]/settings/access/users/create/page.tsx b/src/app/[orgId]/settings/access/users/create/page.tsx index 858ac8da8..cec399a32 100644 --- a/src/app/[orgId]/settings/access/users/create/page.tsx +++ b/src/app/[orgId]/settings/access/users/create/page.tsx @@ -50,6 +50,7 @@ import IdpTypeIcon from "@app/components/IdpTypeIcon"; import { usePaidStatus } from "@app/hooks/usePaidStatus"; import { tierMatrix } from "@server/lib/billing/tierMatrix"; import OrgRolesTagField from "@app/components/OrgRolesTagField"; +import CopyToClipboard from "@app/components/CopyToClipboard"; type UserType = "internal" | "oidc"; @@ -467,7 +468,7 @@ export default function Page() {
- {!inviteLink ? ( + {!inviteLink && userOptions.length > 1 ? ( @@ -490,7 +491,7 @@ export default function Page() { genericOidcForm.reset(); } }} - cols={2} + cols={3} /> @@ -670,9 +671,8 @@ export default function Page() { days: expiresInDays })}

-
diff --git a/src/app/[orgId]/settings/access/users/page.tsx b/src/app/[orgId]/settings/access/users/page.tsx index 23c1d69c6..462122a95 100644 --- a/src/app/[orgId]/settings/access/users/page.tsx +++ b/src/app/[orgId]/settings/access/users/page.tsx @@ -1,8 +1,9 @@ import { internal } from "@app/lib/api"; import { authCookieHeader } from "@app/lib/api/cookies"; import { getUserDisplayName } from "@app/lib/getUserDisplayName"; +import type { ListOrgIdpsResponse } from "@server/routers/orgIdp/types"; +import type { ListRolesResponse } from "@server/routers/role/listRoles"; import { ListUsersResponse } from "@server/routers/user"; -import { AxiosResponse } from "axios"; import UsersTable, { UserRow } from "@app/components/UsersTable"; import { GetOrgResponse } from "@server/routers/org"; import { cache } from "react"; @@ -19,36 +20,73 @@ export const metadata: Metadata = { type UsersPageProps = { params: Promise<{ orgId: string }>; + searchParams: Promise>; }; export const dynamic = "force-dynamic"; export default async function UsersPage(props: UsersPageProps) { const params = await props.params; + const searchParams = new URLSearchParams(await props.searchParams); - const getUser = cache(verifySession); - const user = await getUser(); - const t = await getTranslations(); + const user = await verifySession(); let users: ListUsersResponse["users"] = []; + let pagination: ListUsersResponse["pagination"] = { + total: 0, + page: 1, + pageSize: 20 + }; let hasInvitations = false; - const res = await internal - .get< - AxiosResponse - >(`/org/${params.orgId}/users`, await authCookieHeader()) - .catch((e) => {}); + const cookieHeader = await authCookieHeader(); - if (res && res.status === 200) { - users = res.data.data.users; + const [usersRes, idpsRes, rolesRes] = await Promise.all([ + internal + .get( + `/org/${params.orgId}/users?${searchParams.toString()}`, + cookieHeader + ) + .catch(() => {}), + internal + .get(`/org/${params.orgId}/idp?limit=500&offset=0`, cookieHeader) + .catch(() => {}), + internal + .get(`/org/${params.orgId}/roles?pageSize=500&page=1`, cookieHeader) + .catch(() => {}) + ]); + + if (usersRes && usersRes.status === 200) { + const list = usersRes.data.data as ListUsersResponse; + users = list.users; + pagination = list.pagination; } + const t = await getTranslations(); + + const orgIdps = + idpsRes && idpsRes.status === 200 ? (idpsRes.data.data.idps ?? []) : []; + const idpFilterOptions = [ + { value: "internal", label: t("idpNameInternal") }, + ...orgIdps.map((i: ListOrgIdpsResponse["idps"][number]) => ({ + value: String(i.idpId), + label: i.name + })) + ]; + + const orgRoles = + rolesRes && rolesRes.status === 200 + ? (rolesRes.data.data.roles ?? []) + : []; + const roleFilterOptions = orgRoles.map( + (r: ListRolesResponse["roles"][number]) => ({ + value: String(r.roleId), + label: r.name + }) + ); + const invitationsRes = await internal - .get< - AxiosResponse<{ - pagination: { total: number }; - }> - >( + .get( `/org/${params.orgId}/invitations?limit=1&offset=0`, await authCookieHeader() ) @@ -61,9 +99,7 @@ export default async function UsersPage(props: UsersPageProps) { let org: GetOrgResponse | null = null; const getOrg = cache(async () => internal - .get< - AxiosResponse - >(`/org/${params.orgId}`, await authCookieHeader()) + .get(`/org/${params.orgId}`, await authCookieHeader()) .catch((e) => { console.error(e); }) @@ -110,7 +146,16 @@ export default async function UsersPage(props: UsersPageProps) { /> - + diff --git a/src/app/[orgId]/settings/alerting/(list)/health-checks/page.tsx b/src/app/[orgId]/settings/alerting/(list)/health-checks/page.tsx new file mode 100644 index 000000000..5cbb9ea3d --- /dev/null +++ b/src/app/[orgId]/settings/alerting/(list)/health-checks/page.tsx @@ -0,0 +1,202 @@ +import HealthChecksTable from "@app/components/HealthChecksTable"; +import DismissableBanner from "@app/components/DismissableBanner"; +import { internal } from "@app/lib/api"; +import { authCookieHeader } from "@app/lib/api/cookies"; +import { ListHealthChecksResponse } from "@server/routers/healthChecks/types"; +import { GetResourceResponse } from "@server/routers/resource/getResource"; +import { GetSiteResponse } from "@server/routers/site/getSite"; +import type ResponseT from "@server/types/Response"; +import { HeartPulse } from "lucide-react"; +import type { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; + +export const metadata: Metadata = { + title: "Health Checks" +}; + +type AlertingHealthChecksPageProps = { + params: Promise<{ orgId: string }>; + searchParams: Promise>; +}; + +export const dynamic = "force-dynamic"; + +function parsePositiveInt(s: string | undefined): number | undefined { + if (!s) return undefined; + const n = Number(s); + if (!Number.isInteger(n) || n <= 0) return undefined; + return n; +} + +function appendListFilters( + apiSp: URLSearchParams, + searchParams: URLSearchParams +) { + const query = searchParams.get("query"); + if (query) apiSp.set("query", query); + + const hcMode = searchParams.get("hcMode"); + if ( + hcMode === "http" || + hcMode === "tcp" || + hcMode === "snmp" || + hcMode === "ping" + ) { + apiSp.set("hcMode", hcMode); + } + + const hcHealth = searchParams.get("hcHealth"); + if ( + hcHealth === "healthy" || + hcHealth === "unhealthy" || + hcHealth === "unknown" + ) { + apiSp.set("hcHealth", hcHealth); + } + + const hcEnabled = searchParams.get("hcEnabled"); + if (hcEnabled === "true" || hcEnabled === "false") { + apiSp.set("hcEnabled", hcEnabled); + } + + const siteId = parsePositiveInt(searchParams.get("siteId") ?? undefined); + if (siteId) { + apiSp.set("siteId", String(siteId)); + } + + const resourceId = parsePositiveInt( + searchParams.get("resourceId") ?? undefined + ); + if (resourceId) { + apiSp.set("resourceId", String(resourceId)); + } +} + +export default async function AlertingHealthChecksPage( + props: AlertingHealthChecksPageProps +) { + const params = await props.params; + const searchParams = new URLSearchParams(await props.searchParams); + + const page = Math.max( + 1, + parsePositiveInt(searchParams.get("page") ?? undefined) ?? 1 + ); + const pageSize = Math.max( + 1, + parsePositiveInt(searchParams.get("pageSize") ?? undefined) ?? 20 + ); + const pageIndex = page - 1; + + const apiSp = new URLSearchParams(); + apiSp.set("limit", String(pageSize)); + apiSp.set("offset", String(pageIndex * pageSize)); + appendListFilters(apiSp, searchParams); + + let healthChecks: ListHealthChecksResponse["healthChecks"] = []; + let pagination: ListHealthChecksResponse["pagination"] = { + total: 0, + limit: pageSize, + offset: pageIndex * pageSize + }; + + const siteIdParam = parsePositiveInt( + searchParams.get("siteId") ?? undefined + ); + const resourceIdParam = parsePositiveInt( + searchParams.get("resourceId") ?? undefined + ); + + const header = await authCookieHeader(); + + try { + const res = await internal.get( + `/org/${params.orgId}/health-checks?${apiSp.toString()}`, + header + ); + const responseData = (res.data as ResponseT) + .data; + if (responseData) { + healthChecks = responseData.healthChecks; + pagination = responseData.pagination; + } + } catch { + // leave defaults + } + + let initialFilterSite: { + siteId: number; + name: string; + type: string; + } | null = null; + if (siteIdParam) { + try { + const siteRes = await internal.get(`/site/${siteIdParam}`, header); + const s = (siteRes.data as ResponseT).data; + if (s && s.orgId === params.orgId) { + initialFilterSite = { + siteId: s.siteId, + name: s.name, + type: s.type + }; + } + } catch { + // leave null + } + } + + let initialFilterResource: { + name: string; + resourceId: number; + fullDomain: string | null; + niceId: string; + ssl: boolean; + } | null = null; + if (resourceIdParam) { + try { + const resourceRes = await internal.get( + `/resource/${resourceIdParam}`, + header + ); + const r = (resourceRes.data as ResponseT).data; + if (r && r.orgId === params.orgId) { + initialFilterResource = { + name: r.name, + resourceId: r.resourceId, + fullDomain: r.fullDomain, + niceId: r.niceId, + ssl: r.ssl + }; + } + } catch { + // leave null + } + } + + const t = await getTranslations(); + + return ( +
+ + } + description={t("alertingHealthChecksBannerDescription")} + /> + +
+ ); +} diff --git a/src/app/[orgId]/settings/alerting/(list)/layout.tsx b/src/app/[orgId]/settings/alerting/(list)/layout.tsx new file mode 100644 index 000000000..7393e7044 --- /dev/null +++ b/src/app/[orgId]/settings/alerting/(list)/layout.tsx @@ -0,0 +1,38 @@ +import SettingsSectionTitle from "@app/components/SettingsSectionTitle"; +import { HorizontalTabs } from "@app/components/HorizontalTabs"; +import { getTranslations } from "next-intl/server"; + +type AlertingListLayoutProps = { + children: React.ReactNode; + params: Promise<{ orgId: string }>; +}; + +export default async function AlertingListLayout({ + children, + params +}: AlertingListLayoutProps) { + const { orgId } = await params; + const t = await getTranslations(); + + const navItems = [ + { + title: t("alertingTabRules"), + href: `/${orgId}/settings/alerting/rules`, + activePrefix: `/${orgId}/settings/alerting` + }, + { + title: t("alertingTabHealthChecks"), + href: `/${orgId}/settings/alerting/health-checks` + } + ]; + + return ( + <> + + {children} + + ); +} diff --git a/src/app/[orgId]/settings/alerting/(list)/rules/page.tsx b/src/app/[orgId]/settings/alerting/(list)/rules/page.tsx new file mode 100644 index 000000000..ee2a561bf --- /dev/null +++ b/src/app/[orgId]/settings/alerting/(list)/rules/page.tsx @@ -0,0 +1,105 @@ +import AlertingRulesTable from "@app/components/AlertingRulesTable"; +import DismissableBanner from "@app/components/DismissableBanner"; +import { internal } from "@app/lib/api"; +import { authCookieHeader } from "@app/lib/api/cookies"; +import type { ListAlertRulesResponse } from "@server/private/routers/alertRule"; +import { AxiosResponse } from "axios"; +import { BellRing } from "lucide-react"; +import type { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; + +export const metadata: Metadata = { + title: "Alerting" +}; + +type AlertingRulesPageProps = { + params: Promise<{ orgId: string }>; + searchParams: Promise>; +}; + +export const dynamic = "force-dynamic"; + +function parsePositiveInt(s: string | undefined): number | undefined { + if (!s) return undefined; + const n = Number(s); + if (!Number.isInteger(n) || n <= 0) return undefined; + return n; +} + +export default async function AlertingRulesPage(props: AlertingRulesPageProps) { + const params = await props.params; + const searchParams = new URLSearchParams(await props.searchParams); + + const page = Math.max(1, parsePositiveInt(searchParams.get("page") ?? undefined) ?? 1); + const pageSize = Math.max( + 1, + parsePositiveInt(searchParams.get("pageSize") ?? undefined) ?? 20 + ); + const pageIndex = page - 1; + const query = searchParams.get("query") ?? undefined; + const sortBy = searchParams.get("sort_by") ?? undefined; + const order = searchParams.get("order") ?? undefined; + const enabled = searchParams.get("enabled"); + const enabledParam = + enabled === "true" || enabled === "false" ? enabled : undefined; + const siteId = parsePositiveInt(searchParams.get("siteId") ?? undefined); + const resourceId = parsePositiveInt( + searchParams.get("resourceId") ?? undefined + ); + const healthCheckId = parsePositiveInt( + searchParams.get("healthCheckId") ?? undefined + ); + + const apiSp = new URLSearchParams(); + apiSp.set("limit", String(pageSize)); + apiSp.set("offset", String(pageIndex * pageSize)); + if (query) apiSp.set("query", query); + if (siteId != null) apiSp.set("siteId", String(siteId)); + if (resourceId != null) apiSp.set("resourceId", String(resourceId)); + if (healthCheckId != null) + apiSp.set("healthCheckId", String(healthCheckId)); + if (sortBy) { + apiSp.set("sort_by", sortBy); + if (order) apiSp.set("order", order); + } + if (enabledParam) apiSp.set("enabled", enabledParam); + + let alertRules: ListAlertRulesResponse["alertRules"] = []; + let pagination: ListAlertRulesResponse["pagination"] = { + total: 0, + limit: pageSize, + offset: pageIndex * pageSize + }; + try { + const res = await internal.get>( + `/org/${params.orgId}/alert-rules?${apiSp.toString()}`, + await authCookieHeader() + ); + const responseData = res.data.data; + alertRules = responseData.alertRules; + pagination = responseData.pagination; + } catch { + // leave defaults + } + + const t = await getTranslations(); + + return ( +
+ + } + description={t("alertingRulesBannerDescription")} + /> + +
+ ); +} diff --git a/src/app/[orgId]/settings/alerting/[ruleId]/page.tsx b/src/app/[orgId]/settings/alerting/[ruleId]/page.tsx new file mode 100644 index 000000000..427ac7c44 --- /dev/null +++ b/src/app/[orgId]/settings/alerting/[ruleId]/page.tsx @@ -0,0 +1,94 @@ +"use client"; + +import AlertRuleGraphEditor from "@app/components/alert-rule-editor/AlertRuleGraphEditor"; +import HeaderTitle from "@app/components/SettingsSectionTitle"; +import { apiResponseToFormValues } from "@app/lib/alertRuleForm"; +import { createApiClient, formatAxiosError } from "@app/lib/api"; +import { useEnvContext } from "@app/hooks/useEnvContext"; +import { usePaidStatus } from "@app/hooks/usePaidStatus"; +import { toast } from "@app/hooks/useToast"; +import { tierMatrix } from "@server/lib/billing/tierMatrix"; +import { useParams, useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { useEffect, useState } from "react"; +import type { AxiosResponse } from "axios"; +import type { GetAlertRuleResponse } from "@server/private/routers/alertRule"; +import type { AlertRuleFormValues } from "@app/lib/alertRuleForm"; + +export default function EditAlertRulePage() { + const t = useTranslations(); + const params = useParams(); + const router = useRouter(); + const orgId = params.orgId as string; + const ruleIdParam = params.ruleId as string; + const alertRuleId = parseInt(ruleIdParam, 10); + + const api = createApiClient(useEnvContext()); + const { isPaidUser } = usePaidStatus(); + const isPaid = isPaidUser(tierMatrix.alertingRules); + + const [formValues, setFormValues] = useState< + AlertRuleFormValues | null | undefined + >(undefined); + + useEffect(() => { + if (isNaN(alertRuleId)) { + router.replace(`/${orgId}/settings/alerting/rules`); + return; + } + + api.get>( + `/org/${orgId}/alert-rule/${alertRuleId}` + ) + .then((res) => { + const rule = res.data.data; + setFormValues(apiResponseToFormValues(rule)); + }) + .catch((e) => { + toast({ + title: t("error"), + description: formatAxiosError(e), + variant: "destructive" + }); + setFormValues(null); + }); + }, [orgId, alertRuleId]); + + useEffect(() => { + if (formValues === null) { + router.replace(`/${orgId}/settings/alerting/rules`); + } + }, [formValues, orgId, router]); + + if (formValues === undefined) { + return ( + <> + + + ); + } + + if (formValues === null) { + return null; + } + + return ( + <> + + + + ); +} diff --git a/src/app/[orgId]/settings/alerting/create/page.tsx b/src/app/[orgId]/settings/alerting/create/page.tsx new file mode 100644 index 000000000..9f3f20611 --- /dev/null +++ b/src/app/[orgId]/settings/alerting/create/page.tsx @@ -0,0 +1,32 @@ +"use client"; + +import AlertRuleGraphEditor from "@app/components/alert-rule-editor/AlertRuleGraphEditor"; +import HeaderTitle from "@app/components/SettingsSectionTitle"; +import { defaultFormValues } from "@app/lib/alertRuleForm"; +import { usePaidStatus } from "@app/hooks/usePaidStatus"; +import { tierMatrix } from "@server/lib/billing/tierMatrix"; +import { useParams } from "next/navigation"; +import { useTranslations } from "next-intl"; + +export default function NewAlertRulePage() { + const params = useParams(); + const orgId = params.orgId as string; + const t = useTranslations(); + const { isPaidUser } = usePaidStatus(); + const isPaid = isPaidUser(tierMatrix.alertingRules); + + return ( + <> + + + + ); +} diff --git a/src/app/[orgId]/settings/alerting/layout.tsx b/src/app/[orgId]/settings/alerting/layout.tsx new file mode 100644 index 000000000..a541860eb --- /dev/null +++ b/src/app/[orgId]/settings/alerting/layout.tsx @@ -0,0 +1,7 @@ +type AlertingLayoutProps = { + children: React.ReactNode; +}; + +export default function AlertingLayout({ children }: AlertingLayoutProps) { + return <>{children}; +} diff --git a/src/app/[orgId]/settings/alerting/page.tsx b/src/app/[orgId]/settings/alerting/page.tsx new file mode 100644 index 000000000..1768fbced --- /dev/null +++ b/src/app/[orgId]/settings/alerting/page.tsx @@ -0,0 +1,15 @@ +import type { Metadata } from "next"; +import { redirect } from "next/navigation"; + +export const metadata: Metadata = { + title: "Alerting" +}; + +type AlertingIndexPageProps = { + params: Promise<{ orgId: string }>; +}; + +export default async function AlertingIndexPage(props: AlertingIndexPageProps) { + const params = await props.params; + redirect(`/${params.orgId}/settings/alerting/rules`); +} diff --git a/src/app/[orgId]/settings/domains/[domainId]/page.tsx b/src/app/[orgId]/settings/domains/[domainId]/page.tsx index 6d08636d1..9f9878967 100644 --- a/src/app/[orgId]/settings/domains/[domainId]/page.tsx +++ b/src/app/[orgId]/settings/domains/[domainId]/page.tsx @@ -1,16 +1,8 @@ -import SettingsSectionTitle from "@app/components/SettingsSectionTitle"; -import DomainInfoCard from "@app/components/DomainInfoCard"; -import RestartDomainButton from "@app/components/RestartDomainButton"; +import DomainPageClient from "@app/components/DomainPageClient"; import { GetDomainResponse } from "@server/routers/domain/getDomain"; -import { pullEnv } from "@app/lib/pullEnv"; -import { getTranslations } from "next-intl/server"; -import RefreshButton from "@app/components/RefreshButton"; import { internal } from "@app/lib/api"; import { authCookieHeader } from "@app/lib/api/cookies"; import { GetDNSRecordsResponse } from "@server/routers/domain"; -import DNSRecordsTable from "@app/components/DNSRecordTable"; -import DomainCertForm from "@app/components/DomainCertForm"; -import { build } from "@server/build"; import type { Metadata } from "next"; export const metadata: Metadata = { @@ -25,8 +17,6 @@ export default async function DomainSettingsPage({ params }: DomainSettingsPageProps) { const { domainId, orgId } = await params; - const t = await getTranslations(); - const env = pullEnv(); let domain: GetDomainResponse | null = null; try { @@ -39,57 +29,27 @@ export default async function DomainSettingsPage({ return null; } - let dnsRecords; + let dnsRecords: GetDNSRecordsResponse | null = null; try { const response = await internal.get( `/org/${orgId}/domain/${domainId}/dns-records`, await authCookieHeader() ); dnsRecords = response.data.data; - } catch (error) { + } catch { return null; } - if (!domain) { + if (!domain || !dnsRecords) { return null; } return ( - <> -
- - {env.flags.usePangolinDns && domain.failed ? ( - - ) : ( - - )} -
-
- {build != "oss" && env.flags.usePangolinDns ? ( - - ) : null} - - - - {domain.type == "wildcard" && !domain.configManaged && ( - - )} -
- + ); -} +} \ No newline at end of file diff --git a/src/app/[orgId]/settings/health-checks/page.tsx b/src/app/[orgId]/settings/health-checks/page.tsx new file mode 100644 index 000000000..2ee133d91 --- /dev/null +++ b/src/app/[orgId]/settings/health-checks/page.tsx @@ -0,0 +1,18 @@ +import type { Metadata } from "next"; +import { redirect } from "next/navigation"; + +export const metadata: Metadata = { + title: "Health Checks" +}; + +type LegacyHealthChecksPageProps = { + params: Promise<{ orgId: string }>; +}; + +/** @deprecated Use `/settings/alerting/health-checks` */ +export default async function LegacyHealthChecksRedirect( + props: LegacyHealthChecksPageProps +) { + const params = await props.params; + redirect(`/${params.orgId}/settings/alerting/health-checks`); +} diff --git a/src/app/[orgId]/settings/logs/access/page.tsx b/src/app/[orgId]/settings/logs/access/page.tsx index a0f1b5386..826e11c17 100644 --- a/src/app/[orgId]/settings/logs/access/page.tsx +++ b/src/app/[orgId]/settings/logs/access/page.tsx @@ -471,11 +471,7 @@ export default function GeneralPage() { : `/${row.original.orgId}/settings/resources/proxy/${row.original.resourceNiceId}` } > - diff --git a/src/app/[orgId]/settings/logs/connection/page.tsx b/src/app/[orgId]/settings/logs/connection/page.tsx index e15708f8e..0fc8f95b7 100644 --- a/src/app/[orgId]/settings/logs/connection/page.tsx +++ b/src/app/[orgId]/settings/logs/connection/page.tsx @@ -22,7 +22,7 @@ import { useParams, useRouter, useSearchParams } from "next/navigation"; import { useEffect, useState, useTransition } from "react"; function formatBytes(bytes: number | null): string { - if (bytes === null || bytes === undefined) return "—"; + if (bytes === null || bytes === undefined) return "-"; if (bytes === 0) return "0 B"; const units = ["B", "KB", "MB", "GB", "TB"]; const i = Math.floor(Math.log(bytes) / Math.log(1024)); @@ -33,7 +33,7 @@ function formatBytes(bytes: number | null): string { function formatDuration(startedAt: number, endedAt: number | null): string { if (endedAt === null || endedAt === undefined) return "Active"; const durationSec = endedAt - startedAt; - if (durationSec < 0) return "—"; + if (durationSec < 0) return "-"; if (durationSec < 60) return `${durationSec}s`; if (durationSec < 3600) { const m = Math.floor(durationSec / 60); @@ -451,11 +451,7 @@ export default function ConnectionLogsPage() { - @@ -464,7 +460,7 @@ export default function ConnectionLogsPage() { } return ( - {row.original.resourceName ?? "—"} + {row.original.resourceName ?? "-"} ); } @@ -497,11 +493,7 @@ export default function ConnectionLogsPage() { - @@ -634,6 +636,7 @@ export default function GeneralPage() { { value: "105", label: t("validPassword") }, { value: "106", label: t("validEmail") }, { value: "107", label: t("validSSO") }, + { value: "108", label: t("connectedClient") }, { value: "201", label: t("resourceNotFound") }, { value: "202", label: t("resourceBlocked") }, { value: "203", label: t("droppedByRule") }, diff --git a/src/app/[orgId]/settings/logs/streaming/page.tsx b/src/app/[orgId]/settings/logs/streaming/page.tsx index 7e48d7566..022a8eb2e 100644 --- a/src/app/[orgId]/settings/logs/streaming/page.tsx +++ b/src/app/[orgId]/settings/logs/streaming/page.tsx @@ -38,6 +38,8 @@ import { HttpDestinationCredenza, parseHttpConfig } from "@app/components/HttpDestinationCredenza"; +import { S3DestinationCredenza } from "@app/components/S3DestinationCredenza"; +import { DatadogDestinationCredenza } from "@app/components/DatadogDestinationCredenza"; import { useTranslations } from "next-intl"; // ── Re-export Destination so the rest of the file can use it ────────────────── @@ -203,7 +205,6 @@ function DestinationTypePicker({ id: "s3", title: t("streamingS3Title"), description: t("streamingS3Description"), - disabled: true, icon: ( setSelected(type)} cols={1} /> @@ -291,6 +291,7 @@ export default function StreamingDestinationsPage() { const [typePickerOpen, setTypePickerOpen] = useState(false); const [editingDestination, setEditingDestination] = useState(null); + const [pickedType, setPickedType] = useState("http"); const [togglingIds, setTogglingIds] = useState>(new Set()); // Delete state @@ -392,7 +393,8 @@ export default function StreamingDestinationsPage() { setTypePickerOpen(true); }; - const handleTypePicked = (_type: DestinationType) => { + const handleTypePicked = (type: DestinationType) => { + setPickedType(type); setTypePickerOpen(false); setEditingDestination(null); setModalOpen(true); @@ -400,6 +402,7 @@ export default function StreamingDestinationsPage() { const openEdit = (destination: Destination) => { setEditingDestination(destination); + setPickedType((destination.type as DestinationType) ?? "http"); setModalOpen(true); }; @@ -434,7 +437,7 @@ export default function StreamingDestinationsPage() { disabled={!isEnterprise} /> ))} - {/* Add card is always clickable — paywall is enforced inside the picker */} + {/* Add card is always clickable - paywall is enforced inside the picker */} )} @@ -446,13 +449,33 @@ export default function StreamingDestinationsPage() { isPaywalled={!isEnterprise} /> - + {pickedType === "http" && ( + + )} + {pickedType === "s3" && ( + + )} + {pickedType === "datadog" && ( + + )} {deleteTarget && ( ({ + siteId, + siteName: siteResource.siteNames[idx], + siteNiceId: siteResource.siteNiceIds[idx], + online: siteResource.siteOnlines[idx] + })), + mode: siteResource.mode, + scheme: siteResource.scheme, + ssl: siteResource.ssl, + siteNames: siteResource.siteNames, + siteAddresses: siteResource.siteAddresses || null, // protocol: siteResource.protocol, // proxyPort: siteResource.proxyPort, - siteId: siteResource.siteId, + siteIds: siteResource.siteIds, destination: siteResource.destination, - // destinationPort: siteResource.destinationPort, + httpHttpsPort: siteResource.destinationPort ?? null, alias: siteResource.alias || null, aliasAddress: siteResource.aliasAddress || null, - siteNiceId: siteResource.siteNiceId, + siteNiceIds: siteResource.siteNiceIds, niceId: siteResource.niceId, tcpPortRangeString: siteResource.tcpPortRangeString || null, udpPortRangeString: siteResource.udpPortRangeString || null, disableIcmp: siteResource.disableIcmp || false, authDaemonMode: siteResource.authDaemonMode ?? null, - authDaemonPort: siteResource.authDaemonPort ?? null + authDaemonPort: siteResource.authDaemonPort ?? null, + subdomain: siteResource.subdomain ?? null, + domainId: siteResource.domainId ?? null, + fullDomain: siteResource.fullDomain ?? null }; } ); diff --git a/src/app/[orgId]/settings/resources/proxy/[niceId]/general/page.tsx b/src/app/[orgId]/settings/resources/proxy/[niceId]/general/page.tsx index 9589f6a2e..0bbe42878 100644 --- a/src/app/[orgId]/settings/resources/proxy/[niceId]/general/page.tsx +++ b/src/app/[orgId]/settings/resources/proxy/[niceId]/general/page.tsx @@ -13,16 +13,6 @@ import { import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { useResourceContext } from "@app/hooks/useResourceContext"; -import { - Credenza, - CredenzaBody, - CredenzaClose, - CredenzaContent, - CredenzaDescription, - CredenzaFooter, - CredenzaHeader, - CredenzaTitle -} from "@app/components/Credenza"; import DomainPicker from "@app/components/DomainPicker"; import { SettingsContainer, @@ -39,10 +29,9 @@ import { Label } from "@app/components/ui/label"; import { useEnvContext } from "@app/hooks/useEnvContext"; import { toast } from "@app/hooks/useToast"; import { createApiClient, formatAxiosError } from "@app/lib/api"; -import { finalizeSubdomainSanitize } from "@app/lib/subdomain-utils"; import { UpdateResourceResponse } from "@server/routers/resource"; import { AxiosResponse } from "axios"; -import { AlertCircle, Globe } from "lucide-react"; +import { AlertCircle } from "lucide-react"; import { useTranslations } from "next-intl"; import { useParams, useRouter } from "next/navigation"; import { toASCII, toUnicode } from "punycode"; @@ -62,6 +51,7 @@ import { GetResourceResponse } from "@server/routers/resource/getResource"; import type { ResourceContextType } from "@app/contexts/resourceContext"; import { usePaidStatus } from "@app/hooks/usePaidStatus"; import { tierMatrix } from "@server/lib/billing/tierMatrix"; +import UptimeAlertSection from "@app/components/UptimeAlertSection"; type MaintenanceSectionFormProps = { resource: GetResourceResponse; @@ -441,7 +431,6 @@ export default function GeneralForm() { const { resource, updateResource } = useResourceContext(); const router = useRouter(); const t = useTranslations(); - const [editDomainOpen, setEditDomainOpen] = useState(false); const { env } = useEnvContext(); @@ -454,24 +443,13 @@ export default function GeneralForm() { ); const resourceFullDomainName = useMemo(() => { - if (!resource.fullDomain) { - return ""; - } try { const url = new URL(resourceFullDomain); return url.hostname; } catch { return ""; } - }, [resourceFullDomain, resource.fullDomain]); - - const [selectedDomain, setSelectedDomain] = useState<{ - domainId: string; - domainNamespaceId?: string; - subdomain?: string; - fullDomain: string; - baseDomain: string; - } | null>(null); + }, [resourceFullDomain]); const GeneralFormSchema = z .object({ @@ -578,6 +556,13 @@ export default function GeneralForm() { return ( <> + {resource?.resourceId && resource?.orgId && ( + + )} @@ -596,37 +581,6 @@ export default function GeneralForm() { className="space-y-4" id="general-settings-form" > - ( - -
- - - form.setValue( - "enabled", - val - ) - } - /> - -
- -
- )} - /> - - -
- - - {resourceFullDomain} - - + defaultDomainId={ + form.watch( + "domainId" + ) ?? undefined + } + defaultFullDomain={ + resourceFullDomainName || + undefined + } + onDomainChange={(res) => { + if (res === null) { + form.setValue( + "domainId", + undefined + ); + form.setValue( + "subdomain", + undefined + ); + setResourceFullDomain( + `${resource.ssl ? "https" : "http"}://` + ); + return; + } + form.setValue( + "domainId", + res.domainId + ); + form.setValue( + "subdomain", + res.subdomain ?? + undefined + ); + setResourceFullDomain( + `${resource.ssl ? "https" : "http"}://${toUnicode(res.fullDomain)}` + ); + }} + />
)} + + ( + +
+ + + form.setValue( + "enabled", + val + ) + } + /> + +
+ +
+ )} + /> @@ -759,86 +776,6 @@ export default function GeneralForm() { /> )}
- - setEditDomainOpen(setOpen)} - > - - - Edit Domain - - Select a domain for your resource - - - - { - const selected = - res === null - ? null - : { - domainId: res.domainId, - subdomain: res.subdomain, - fullDomain: res.fullDomain, - baseDomain: res.baseDomain, - domainNamespaceId: - res.domainNamespaceId - }; - - setSelectedDomain(selected); - }} - /> - - - - - - - - - ); } diff --git a/src/app/[orgId]/settings/resources/proxy/[niceId]/proxy/page.tsx b/src/app/[orgId]/settings/resources/proxy/[niceId]/proxy/page.tsx index a9128b9d3..03426ef1f 100644 --- a/src/app/[orgId]/settings/resources/proxy/[niceId]/proxy/page.tsx +++ b/src/app/[orgId]/settings/resources/proxy/[niceId]/proxy/page.tsx @@ -1,6 +1,6 @@ "use client"; -import HealthCheckDialog from "@/components/HealthCheckDialog"; +import HealthCheckCredenza from "@/components/HealthCheckCredenza"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { @@ -168,6 +168,30 @@ function ProxyResourceTargetsForm({ const [targets, setTargets] = useState(initialTargets); const [targetsToRemove, setTargetsToRemove] = useState([]); + + const { data: polledTargets } = useQuery({ + ...resourceQueries.resourceTargets({ + resourceId: resource.resourceId + }), + refetchInterval: 10_000 + }); + + useEffect(() => { + if (!polledTargets) return; + setTargets((prev) => + prev.map((t) => { + const fresh = polledTargets.find( + (p) => p.targetId === t.targetId + ); + if (!fresh) return t; + return { + ...t, + hcHealth: fresh.hcHealth, + hcEnabled: t.updated ? t.hcEnabled : fresh.hcEnabled + }; + }) + ); + }, [polledTargets]); const [dockerStates, setDockerStates] = useState>( new Map() ); @@ -317,19 +341,6 @@ function ProxyResourceTargetsForm({ header: () => {t("healthCheck")}, cell: ({ row }) => { const status = row.original.hcHealth || "unknown"; - const isEnabled = row.original.hcEnabled; - - const getStatusColor = (status: string) => { - switch (status) { - case "healthy": - return "green"; - case "unhealthy": - return "red"; - case "unknown": - default: - return "secondary"; - } - }; const getStatusText = (status: string) => { switch (status) { @@ -343,19 +354,7 @@ function ProxyResourceTargetsForm({ } }; - const getStatusIcon = (status: string) => { - switch (status) { - case "healthy": - return ; - case "unhealthy": - return ; - case "unknown": - default: - return null; - } - }; - - return ( + return (
{row.original.siteType === "newt" ? ( + ) : ( - )} @@ -640,10 +642,10 @@ function ProxyResourceTargetsForm({ hcInterval: null, hcTimeout: null, hcHeaders: null, + hcFollowRedirects: null, hcScheme: null, hcHostname: null, hcPort: null, - hcFollowRedirects: null, hcHealth: "unknown", hcStatus: null, hcMode: null, @@ -965,10 +967,10 @@ function ProxyResourceTargetsForm({ {selectedTargetForHealthCheck && ( - - updateTarget(row.original.targetId, - config.path === null && config.pathMatchType === null - ? { ...config, rewritePath: null, rewritePathType: null } + updateTarget( + row.original.targetId, + config.path === null && + config.pathMatchType === null + ? { + ...config, + rewritePath: null, + rewritePathType: null + } : config ) } @@ -804,9 +810,15 @@ export default function Page() { pathMatchType: row.original.pathMatchType }} onChange={(config) => - updateTarget(row.original.targetId, - config.path === null && config.pathMatchType === null - ? { ...config, rewritePath: null, rewritePathType: null } + updateTarget( + row.original.targetId, + config.path === null && + config.pathMatchType === null + ? { + ...config, + rewritePath: null, + rewritePathType: null + } : config ) } @@ -1061,7 +1073,7 @@ export default function Page() { : null ); }} - cols={2} + cols={3} /> )} @@ -1118,28 +1130,30 @@ export default function Page() { - = 1 - } - onDomainChange={(res) => { - if (!res) return; + + = 1 + } + onDomainChange={(res) => { + if (!res) return; - httpForm.setValue( - "subdomain", - res.subdomain - ); - httpForm.setValue( - "domainId", - res.domainId - ); - console.log( - "Domain changed:", - res - ); - }} - /> + httpForm.setValue( + "subdomain", + res.subdomain + ); + httpForm.setValue( + "domainId", + res.domainId + ); + console.log( + "Domain changed:", + res + ); + }} + /> + ) : ( @@ -1155,98 +1169,101 @@ export default function Page() { -
- { - if (e.key === "Enter") { - e.preventDefault(); // block default enter refresh - } - }} - className="space-y-4 grid gap-4 grid-cols-1 md:grid-cols-2 items-start" - id="tcp-udp-settings-form" - > - ( - - - {t("protocol")} - - - - - )} - /> + + + { + if (e.key === "Enter") { + e.preventDefault(); // block default enter refresh + } + }} + className="space-y-4 grid gap-4 grid-cols-1 md:grid-cols-2 items-start" + id="tcp-udp-settings-form" + > + ( + + + {t( + "protocol" + )} + + + + + )} + /> - ( - - - {t( - "resourcePortNumber" - )} - - - - field.onChange( + ( + + + {t( + "resourcePortNumber" + )} + + + - - - - {t( - "resourcePortNumberDescription" - )} - - - )} - /> - - + ) => + field.onChange( + e + .target + .value + ? parseInt( + e + .target + .value + ) + : undefined + ) + } + /> + + + + )} + /> + + +
)} @@ -1460,12 +1477,10 @@ export default function Page() {
{selectedTargetForHealthCheck && ( - + {site?.siteId && site?.orgId && ( + + )} diff --git a/src/app/[orgId]/settings/sites/create/page.tsx b/src/app/[orgId]/settings/sites/create/page.tsx index b7cff202a..ab97197a3 100644 --- a/src/app/[orgId]/settings/sites/create/page.tsx +++ b/src/app/[orgId]/settings/sites/create/page.tsx @@ -425,7 +425,7 @@ export default function Page() { setRemoteExitNodeOptions(exitNodeOptions); if (exitNodeOptions.length === 0) { - // No remote exit nodes available — remove local option and default to newt + // No remote exit nodes available - remove local option and default to newt setTunnelTypes((prev: any) => prev.filter((item: any) => item.id !== "local") ); @@ -434,7 +434,7 @@ export default function Page() { } } catch (error) { console.error("Failed to fetch remote exit nodes:", error); - // If fetch fails, no remote exit nodes available — remove local option and default to newt + // If fetch fails, no remote exit nodes available - remove local option and default to newt setTunnelTypes((prev: any) => prev.filter((item: any) => item.id !== "local") ); diff --git a/src/app/admin/users/AdminUsersTable.tsx b/src/app/admin/users/AdminUsersTable.tsx deleted file mode 100644 index 1c7d1b7fd..000000000 --- a/src/app/admin/users/AdminUsersTable.tsx +++ /dev/null @@ -1,264 +0,0 @@ -"use client"; - -import { UsersDataTable } from "@app/components/AdminUsersDataTable"; -import { Button } from "@app/components/ui/button"; -import { ArrowRight, ArrowUpDown, MoreHorizontal } from "lucide-react"; -import { useRouter } from "next/navigation"; -import { useState } from "react"; -import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog"; -import { toast } from "@app/hooks/useToast"; -import { formatAxiosError } from "@app/lib/api"; -import { createApiClient } from "@app/lib/api"; -import { useEnvContext } from "@app/hooks/useEnvContext"; -import { useTranslations } from "next-intl"; -import { - DropdownMenu, - DropdownMenuItem, - DropdownMenuContent, - DropdownMenuTrigger -} from "@app/components/ui/dropdown-menu"; -import { ExtendedColumnDef } from "@app/components/ui/data-table"; - -export type GlobalUserRow = { - id: string; - name: string | null; - username: string; - email: string | null; - type: string; - idpId: number | null; - idpName: string; - dateCreated: string; - twoFactorEnabled: boolean | null; - twoFactorSetupRequested: boolean | null; -}; - -type Props = { - users: GlobalUserRow[]; -}; - -export default function UsersTable({ users }: Props) { - const router = useRouter(); - const t = useTranslations(); - - const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); - const [selected, setSelected] = useState(null); - const [rows, setRows] = useState(users); - - const api = createApiClient(useEnvContext()); - - const deleteUser = (id: string) => { - api.delete(`/user/${id}`) - .catch((e) => { - console.error(t("userErrorDelete"), e); - toast({ - variant: "destructive", - title: t("userErrorDelete"), - description: formatAxiosError(e, t("userErrorDelete")) - }); - }) - .then(() => { - router.refresh(); - setIsDeleteModalOpen(false); - - const newRows = rows.filter((row) => row.id !== id); - - setRows(newRows); - }); - }; - - const columns: ExtendedColumnDef[] = [ - { - accessorKey: "id", - friendlyName: "ID", - header: ({ column }) => { - return ( - - ); - } - }, - { - accessorKey: "username", - friendlyName: t("username"), - header: ({ column }) => { - return ( - - ); - } - }, - { - accessorKey: "email", - friendlyName: t("email"), - header: ({ column }) => { - return ( - - ); - } - }, - { - accessorKey: "name", - friendlyName: t("name"), - header: ({ column }) => { - return ( - - ); - } - }, - { - accessorKey: "idpName", - friendlyName: t("identityProvider"), - header: ({ column }) => { - return ( - - ); - } - }, - { - accessorKey: "twoFactorEnabled", - friendlyName: t("twoFactor"), - header: ({ column }) => { - return ( - - ); - }, - cell: ({ row }) => { - const userRow = row.original; - - return ( -
- - {userRow.twoFactorEnabled || - userRow.twoFactorSetupRequested ? ( - - {t("enabled")} - - ) : ( - {t("disabled")} - )} - -
- ); - } - }, - { - id: "actions", - header: () => {t("actions")}, - cell: ({ row }) => { - const r = row.original; - return ( - <> -
- - - - - - - { - setSelected(r); - setIsDeleteModalOpen(true); - }} - > - {t("delete")} - - - -
- - ); - } - } - ]; - - return ( - <> - {selected && ( - { - setIsDeleteModalOpen(val); - setSelected(null); - }} - dialog={ -
-

{t("userQuestionRemove")}

- -

{t("userMessageRemove")}

-
- } - buttonText={t("userDeleteConfirm")} - onConfirm={async () => deleteUser(selected!.id)} - string={ - selected.email || selected.name || selected.username - } - title={t("userDeleteServer")} - /> - )} - - - - ); -} diff --git a/src/app/admin/users/page.tsx b/src/app/admin/users/page.tsx index 2a000b34b..0cfaaf3b0 100644 --- a/src/app/admin/users/page.tsx +++ b/src/app/admin/users/page.tsx @@ -1,33 +1,70 @@ import { internal } from "@app/lib/api"; import { authCookieHeader } from "@app/lib/api/cookies"; -import { AxiosResponse } from "axios"; import SettingsSectionTitle from "@app/components/SettingsSectionTitle"; -import { AdminListUsersResponse } from "@server/routers/user/adminListUsers"; +import type { AdminListUsersResponse } from "@server/routers/user/adminListUsers"; +import type { ListIdpsResponse } from "@server/routers/idp/listIdps"; import UsersTable, { GlobalUserRow } from "@app/components/AdminUsersTable"; import { Alert, AlertDescription, AlertTitle } from "@app/components/ui/alert"; import { InfoIcon } from "lucide-react"; import { getTranslations } from "next-intl/server"; -type PageProps = { - params: Promise<{ orgId: string }>; +/** API JSON body shape for `response()` handlers (see `server/lib/response.ts`). */ +type ApiPayload = { + data: T; + success: boolean; + error: boolean; + message: string; + status: number; +}; + +type AdminUsersPageProps = { + searchParams: Promise>; }; export const dynamic = "force-dynamic"; -export default async function UsersPage(props: PageProps) { +export default async function UsersPage(props: AdminUsersPageProps) { + const searchParams = new URLSearchParams(await props.searchParams); + const cookieHeader = await authCookieHeader(); + let rows: AdminListUsersResponse["users"] = []; - try { - const res = await internal.get>( - `/users`, - await authCookieHeader() - ); - rows = res.data.data.users; - } catch (e) { - console.error(e); + let pagination: AdminListUsersResponse["pagination"] = { + total: 0, + page: 1, + pageSize: 20 + }; + + const [usersRes, idpsRes] = await Promise.all([ + internal + .get< + ApiPayload + >(`/users?${searchParams.toString()}`, cookieHeader) + .catch(() => {}), + internal + .get< + ApiPayload + >(`/idp?limit=500&offset=0`, cookieHeader) + .catch(() => {}) + ]); + + if (usersRes && usersRes.status === 200) { + const list = usersRes.data.data; + rows = list.users; + pagination = list.pagination; } const t = await getTranslations(); + const globalIdps = + idpsRes && idpsRes.status === 200 ? (idpsRes.data.data.idps ?? []) : []; + const idpFilterOptions = [ + { value: "internal", label: t("idpNameInternal") }, + ...globalIdps.map((i: ListIdpsResponse["idps"][number]) => ({ + value: String(i.idpId), + label: i.name + })) + ]; + const userRows: GlobalUserRow[] = rows.map((row) => { return { id: row.id, @@ -59,7 +96,15 @@ export default async function UsersPage(props: PageProps) { {t("userAbountDescription")} - + ); } diff --git a/src/app/globals.css b/src/app/globals.css index bbb165c28..aa98b1d49 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -6,7 +6,7 @@ :root { --radius: 0.75rem; - --background: oklch(0.985 0 0); + --background: oklch(1 0 0); --foreground: oklch(0.141 0.005 285.823); --card: oklch(1 0 0); --card-foreground: oklch(0.141 0.005 285.823); @@ -22,30 +22,30 @@ --accent-foreground: oklch(0.21 0.006 285.885); --destructive: oklch(0.577 0.245 27.325); --destructive-foreground: oklch(0.985 0 0); - --border: oklch(0.91 0.004 286.32); - --input: oklch(0.92 0.004 286.32); + --border: oklch(0.88 0.004 286.32); + --input: oklch(0.88 0.004 286.32); --ring: oklch(0.705 0.213 47.604); --chart-1: oklch(0.646 0.222 41.116); --chart-2: oklch(0.6 0.118 184.704); --chart-3: oklch(0.398 0.07 227.392); --chart-4: oklch(0.828 0.189 84.429); --chart-5: oklch(0.769 0.188 70.08); - --sidebar: oklch(0.985 0 0); + --sidebar: #fafafa; --sidebar-foreground: oklch(0.141 0.005 285.823); --sidebar-primary: oklch(0.705 0.213 47.604); --sidebar-primary-foreground: oklch(0.98 0.016 73.684); - --sidebar-accent: oklch(0.967 0.001 286.375); + --sidebar-accent: #eaeaea; --sidebar-accent-foreground: oklch(0.21 0.006 285.885); --sidebar-border: oklch(0.92 0.004 286.32); --sidebar-ring: oklch(0.705 0.213 47.604); } .dark { - --background: oklch(0.19 0.006 285.885); + --background: #0d0d0f; --foreground: oklch(0.985 0 0); - --card: oklch(0.21 0.006 285.885); + --card: #0d0d0f; --card-foreground: oklch(0.985 0 0); - --popover: oklch(0.21 0.006 285.885); + --popover: #0d0d0f; --popover-foreground: oklch(0.985 0 0); --primary: oklch(0.6717 0.1946 41.93); --primary-foreground: oklch(0.98 0.016 73.684); @@ -57,7 +57,7 @@ --accent-foreground: oklch(0.985 0 0); --destructive: oklch(0.5382 0.1949 22.216); --destructive-foreground: oklch(0.985 0 0); - --border: oklch(1 0 0 / 13%); + --border: oklch(1 0 0 / 15%); --input: oklch(1 0 0 / 18%); --ring: oklch(0.646 0.222 41.116); --chart-1: oklch(0.488 0.243 264.376); @@ -65,11 +65,11 @@ --chart-3: oklch(0.769 0.188 70.08); --chart-4: oklch(0.627 0.265 303.9); --chart-5: oklch(0.645 0.246 16.439); - --sidebar: oklch(0.21 0.006 285.885); + --sidebar: #040404; --sidebar-foreground: oklch(0.985 0 0); --sidebar-primary: oklch(0.646 0.222 41.116); --sidebar-primary-foreground: oklch(0.98 0.016 73.684); - --sidebar-accent: oklch(0.274 0.006 286.033); + --sidebar-accent: #131317; --sidebar-accent-foreground: oklch(0.985 0 0); --sidebar-border: oklch(1 0 0 / 10%); --sidebar-ring: oklch(0.646 0.222 41.116); @@ -110,6 +110,15 @@ --color-chart-4: var(--chart-4); --color-chart-5: var(--chart-5); + --color-sidebar: var(--sidebar); + --color-sidebar-foreground: var(--sidebar-foreground); + --color-sidebar-primary: var(--sidebar-primary); + --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); + --color-sidebar-accent: var(--sidebar-accent); + --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); + --color-sidebar-border: var(--sidebar-border); + --color-sidebar-ring: var(--sidebar-ring); + --radius-lg: var(--radius); --radius-md: calc(var(--radius) - 2px); --radius-sm: calc(var(--radius) - 4px); @@ -166,7 +175,9 @@ p { } @keyframes dot-pulse { - 0%, 80%, 100% { + 0%, + 80%, + 100% { opacity: 0.3; transform: scale(0.8); } @@ -189,7 +200,10 @@ p { /* Only apply custom viewport height on mobile */ @media (max-width: 767px) { .h-screen-safe { - height: var(--vh, 100vh); /* Use CSS variable set by ViewportHeightFix on mobile */ + height: var( + --vh, + 100vh + ); /* Use CSS variable set by ViewportHeightFix on mobile */ } } } diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 0db1b49bf..9cf66dd28 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -23,7 +23,7 @@ import { TanstackQueryProvider } from "@app/components/TanstackQueryProvider"; import { TailwindIndicator } from "@app/components/TailwindIndicator"; import { ViewportHeightFix } from "@app/components/ViewportHeightFix"; import StoreInternalRedirect from "@app/components/StoreInternalRedirect"; -import { Inter } from "next/font/google"; +import { Inter, Mona_Sans } from "next/font/google"; export const metadata: Metadata = { title: `Dashboard - ${process.env.BRANDING_APP_NAME || "Pangolin"}`, @@ -36,7 +36,11 @@ const inter = Inter({ subsets: ["latin"] }); -const fontClassName = inter.className; +const monaSans = Mona_Sans({ + subsets: ["latin"] +}); + +const fontClassName = monaSans.className; export default async function RootLayout({ children diff --git a/src/app/navigation.tsx b/src/app/navigation.tsx index ac7a4a10f..24dc02a19 100644 --- a/src/app/navigation.tsx +++ b/src/app/navigation.tsx @@ -2,6 +2,7 @@ import { SidebarNavItem } from "@app/components/SidebarNav"; import { Env } from "@app/lib/types/env"; import { build } from "@server/build"; import { + BellRing, Boxes, Building2, Cable, @@ -212,9 +213,9 @@ export const orgNavSections = ( icon: , items: [ { - title: "sidebarApiKeys", - href: "/{orgId}/settings/api-keys", - icon: + title: "sidebarAlerting", + href: "/{orgId}/settings/alerting", + icon: }, { title: "sidebarProvisioning", @@ -225,6 +226,11 @@ export const orgNavSections = ( title: "sidebarBluePrints", href: "/{orgId}/settings/blueprints", icon: + }, + { + title: "sidebarApiKeys", + href: "/{orgId}/settings/api-keys", + icon: } ] }, diff --git a/src/app/private-maintenance-screen/page.tsx b/src/app/private-maintenance-screen/page.tsx new file mode 100644 index 000000000..21417b6f4 --- /dev/null +++ b/src/app/private-maintenance-screen/page.tsx @@ -0,0 +1,32 @@ +import { Metadata } from "next"; +import { getTranslations } from "next-intl/server"; +import { + Card, + CardContent, + CardHeader, + CardTitle +} from "@app/components/ui/card"; + +export const dynamic = "force-dynamic"; + +export const metadata: Metadata = { + title: "Private Placeholder" +}; + +export default async function MaintenanceScreen() { + const t = await getTranslations(); + + let title = t("privateMaintenanceScreenTitle"); + let message = t("privateMaintenanceScreenMessage"); + + return ( +
+ + + {title} + + {message} + +
+ ); +} diff --git a/src/components/AdminUsersDataTable.tsx b/src/components/AdminUsersDataTable.tsx deleted file mode 100644 index afa473e86..000000000 --- a/src/components/AdminUsersDataTable.tsx +++ /dev/null @@ -1,37 +0,0 @@ -"use client"; - -import { ColumnDef } from "@tanstack/react-table"; -import { DataTable } from "@app/components/ui/data-table"; -import { useTranslations } from "next-intl"; - -interface DataTableProps { - columns: ColumnDef[]; - data: TData[]; - onRefresh?: () => void; - isRefreshing?: boolean; -} - -export function UsersDataTable({ - columns, - data, - onRefresh, - isRefreshing -}: DataTableProps) { - const t = useTranslations(); - - return ( - - ); -} diff --git a/src/components/AdminUsersTable.tsx b/src/components/AdminUsersTable.tsx index 09797a2e2..eabb6b468 100644 --- a/src/components/AdminUsersTable.tsx +++ b/src/components/AdminUsersTable.tsx @@ -1,19 +1,31 @@ "use client"; -import { ColumnDef } from "@tanstack/react-table"; -import { ExtendedColumnDef } from "@app/components/ui/data-table"; -import { UsersDataTable } from "@app/components/AdminUsersDataTable"; -import { Button } from "@app/components/ui/button"; -import { ArrowRight, ArrowUpDown, MoreHorizontal } from "lucide-react"; -import { useRouter } from "next/navigation"; -import { useState, useEffect } from "react"; import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog"; -import { toast } from "@app/hooks/useToast"; -import { formatAxiosError } from "@app/lib/api"; -import { createApiClient } from "@app/lib/api"; -import { getUserDisplayName } from "@app/lib/getUserDisplayName"; +import { ColumnFilterButton } from "@app/components/ColumnFilterButton"; +import { Button } from "@app/components/ui/button"; +import { + ControlledDataTable, + type ExtendedColumnDef +} from "@app/components/ui/controlled-data-table"; import { useEnvContext } from "@app/hooks/useEnvContext"; +import { useNavigationContext } from "@app/hooks/useNavigationContext"; +import { toast } from "@app/hooks/useToast"; +import { createApiClient, formatAxiosError } from "@app/lib/api"; +import { getUserDisplayName } from "@app/lib/getUserDisplayName"; +import { getNextSortOrder, getSortDirection } from "@app/lib/sortColumn"; +import { type PaginationState } from "@tanstack/react-table"; +import { + ArrowDown01Icon, + ArrowRight, + ArrowUp10Icon, + ChevronsUpDownIcon, + MoreHorizontal +} from "lucide-react"; import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import { useState, useTransition } from "react"; +import { useDebouncedCallback } from "use-debounce"; +import z from "zod"; import { DropdownMenu, DropdownMenuItem, @@ -31,7 +43,6 @@ import { CredenzaClose } from "@app/components/Credenza"; import CopyToClipboard from "@app/components/CopyToClipboard"; -import { AxiosResponse } from "axios"; export type GlobalUserRow = { id: string; @@ -44,10 +55,16 @@ export type GlobalUserRow = { dateCreated: string; twoFactorEnabled: boolean | null; twoFactorSetupRequested: boolean | null; + serverAdmin?: boolean; }; +type FilterOption = { value: string; label: string }; + type Props = { users: GlobalUserRow[]; + pagination: PaginationState; + rowCount: number; + idpFilterOptions: FilterOption[]; }; type AdminGeneratePasswordResetCodeResponse = { @@ -56,74 +73,103 @@ type AdminGeneratePasswordResetCodeResponse = { url: string; }; -export default function UsersTable({ users }: Props) { +export default function UsersTable({ + users, + pagination, + rowCount, + idpFilterOptions +}: Props) { const router = useRouter(); const t = useTranslations(); + const api = createApiClient(useEnvContext()); const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); const [selected, setSelected] = useState(null); - const [rows, setRows] = useState(users); - - const api = createApiClient(useEnvContext()); - - const [isRefreshing, setIsRefreshing] = useState(false); const [isPasswordResetCodeDialogOpen, setIsPasswordResetCodeDialogOpen] = useState(false); const [passwordResetCodeData, setPasswordResetCodeData] = useState(null); const [isGeneratingCode, setIsGeneratingCode] = useState(false); - // Update local state when props change (e.g., after refresh) - useEffect(() => { - setRows(users); - }, [users]); + const [isRefreshing, startTransition] = useTransition(); + const { + navigate: filter, + isNavigating: isFiltering, + searchParams, + pathname + } = useNavigationContext(); + + const idpIdParamSchema = z + .union([z.literal("internal"), z.string().regex(/^\d+$/)]) + .optional() + .catch(undefined); + + const twoFactorFilterSchema = z + .enum(["true", "false"]) + .optional() + .catch(undefined); + + function handleFilterChange( + column: string, + value: string | undefined | null + ) { + const sp = new URLSearchParams(searchParams); + sp.delete(column); + sp.delete("page"); + + if (value) { + sp.set(column, value); + } + startTransition(() => router.push(`${pathname}?${sp.toString()}`)); + } const refreshData = async () => { - console.log("Data refreshed"); - setIsRefreshing(true); - try { - await new Promise((resolve) => setTimeout(resolve, 200)); - router.refresh(); - } catch (error) { - toast({ - title: t("error"), - description: t("refreshError"), - variant: "destructive" - }); - } finally { - setIsRefreshing(false); - } + startTransition(async () => { + try { + await new Promise((resolve) => setTimeout(resolve, 200)); + router.refresh(); + } catch (error) { + toast({ + title: t("error"), + description: t("refreshError"), + variant: "destructive" + }); + } + }); }; const deleteUser = (id: string) => { - api.delete(`/user/${id}`) - .catch((e) => { - console.error(t("userErrorDelete"), e); - toast({ - variant: "destructive", - title: t("userErrorDelete"), - description: formatAxiosError(e, t("userErrorDelete")) + startTransition(() => { + void api + .delete(`/user/${id}`) + .catch((e) => { + console.error(t("userErrorDelete"), e); + toast({ + variant: "destructive", + title: t("userErrorDelete"), + description: formatAxiosError(e, t("userErrorDelete")) + }); + }) + .then(() => { + router.refresh(); + setIsDeleteModalOpen(false); + setSelected(null); }); - }) - .then(() => { - router.refresh(); - setIsDeleteModalOpen(false); - - const newRows = rows.filter((row) => row.id !== id); - - setRows(newRows); - }); + }); }; const generatePasswordResetCode = async (userId: string) => { setIsGeneratingCode(true); try { - const res = await api.post< - AxiosResponse - >(`/user/${userId}/generate-password-reset-code`); + const res = await api.post( + `/user/${userId}/generate-password-reset-code` + ); - if (res.data?.data) { - setPasswordResetCodeData(res.data.data); + const envelope = res.data as { + data?: AdminGeneratePasswordResetCodeResponse; + }; + if (envelope?.data) { + setPasswordResetCodeData(envelope.data); setIsPasswordResetCodeDialogOpen(true); } } catch (e) { @@ -138,37 +184,55 @@ export default function UsersTable({ users }: Props) { } }; + function toggleSort(column: string) { + const newSearch = getNextSortOrder(column, searchParams); + filter({ + searchParams: newSearch + }); + } + + const handlePaginationChange = (newPage: PaginationState) => { + searchParams.set("page", (newPage.pageIndex + 1).toString()); + searchParams.set("pageSize", newPage.pageSize.toString()); + filter({ + searchParams + }); + }; + + const handleSearchChange = useDebouncedCallback((query: string) => { + searchParams.set("query", query); + searchParams.delete("page"); + filter({ + searchParams + }); + }, 300); + const columns: ExtendedColumnDef[] = [ { accessorKey: "id", friendlyName: "ID", - header: ({ column }) => { - return ( - - ); - } + header: () => ID }, { accessorKey: "username", enableHiding: false, friendlyName: t("username"), - header: ({ column }) => { + header: () => { + const sortOrder = getSortDirection("username", searchParams); + const Icon = + sortOrder === "asc" + ? ArrowDown01Icon + : sortOrder === "desc" + ? ArrowUp10Icon + : ChevronsUpDownIcon; return ( ); } @@ -176,16 +240,22 @@ export default function UsersTable({ users }: Props) { { accessorKey: "email", friendlyName: t("email"), - header: ({ column }) => { + header: () => { + const sortOrder = getSortDirection("email", searchParams); + const Icon = + sortOrder === "asc" + ? ArrowDown01Icon + : sortOrder === "desc" + ? ArrowUp10Icon + : ChevronsUpDownIcon; return ( ); } @@ -193,16 +263,22 @@ export default function UsersTable({ users }: Props) { { accessorKey: "name", friendlyName: t("name"), - header: ({ column }) => { + header: () => { + const sortOrder = getSortDirection("name", searchParams); + const Icon = + sortOrder === "asc" + ? ArrowDown01Icon + : sortOrder === "desc" + ? ArrowUp10Icon + : ChevronsUpDownIcon; return ( ); } @@ -210,39 +286,45 @@ export default function UsersTable({ users }: Props) { { accessorKey: "idpName", friendlyName: t("identityProvider"), - header: ({ column }) => { - return ( - - ); - } + header: () => ( + + handleFilterChange("idp_id", value) + } + searchPlaceholder={t("searchPlaceholder")} + emptyMessage={t("emptySearchOptions")} + label={t("identityProvider")} + className="p-3" + /> + ) }, { accessorKey: "twoFactorEnabled", friendlyName: t("twoFactor"), - header: ({ column }) => { - return ( - - ); - }, + header: () => ( + + handleFilterChange("two_factor", value) + } + searchPlaceholder={t("searchPlaceholder")} + emptyMessage={t("emptySearchOptions")} + label={t("twoFactor")} + className="p-3" + /> + ), cell: ({ row }) => { const userRow = row.original; - return (
@@ -277,8 +359,11 @@ export default function UsersTable({ users }: Props) { {r.type === "internal" && ( { - generatePasswordResetCode(r.id); + void generatePasswordResetCode( + r.id + ); }} > {t("generatePasswordResetCode")} @@ -350,11 +435,21 @@ export default function UsersTable({ users }: Props) { /> )} - ) => string +) { + if (alertRuleAllSitesSelected(rule.eventType, rule.siteIds)) { + return t("alertingSummaryAllSites"); + } + if ( + rule.eventType === "site_online" || + rule.eventType === "site_offline" || + rule.eventType === "site_toggle" + ) { + return t("alertingSummarySites", { count: rule.siteIds.length }); + } + if (alertRuleAllResourcesSelected(rule.eventType, rule.resourceIds)) { + return t("alertingSummaryAllResources"); + } + if (rule.eventType.startsWith("resource_")) { + return t("alertingSummaryResources", { + count: rule.resourceIds.length + }); + } + if (alertRuleAllHealthChecksSelected(rule.eventType, rule.healthCheckIds)) { + return t("alertingSummaryAllHealthChecks"); + } + return t("alertingSummaryHealthChecks", { + count: rule.healthCheckIds.length + }); +} + +function triggerLabel(rule: AlertRuleRow, t: (k: string) => string) { + switch (rule.eventType) { + case "site_online": + return t("alertingTriggerSiteOnline"); + case "site_offline": + return t("alertingTriggerSiteOffline"); + case "site_toggle": + return t("alertingTriggerSiteToggle"); + case "health_check_healthy": + return t("alertingTriggerHcHealthy"); + case "health_check_unhealthy": + return t("alertingTriggerHcUnhealthy"); + case "health_check_toggle": + return t("alertingTriggerHcToggle"); + case "resource_healthy": + return t("alertingTriggerResourceHealthy"); + case "resource_unhealthy": + return t("alertingTriggerResourceUnhealthy"); + case "resource_toggle": + return t("alertingTriggerResourceToggle"); + default: + return rule.eventType; + } +} + +export default function AlertingRulesTable({ + orgId, + alertRules, + rowCount +}: AlertingRulesTableProps) { + const router = useRouter(); + const t = useTranslations(); + const api = createApiClient(useEnvContext()); + const [isRefreshing, startRefresh] = useTransition(); + const { isPaidUser } = usePaidStatus(); + const isPaid = isPaidUser(tierMatrix.alertingRules); + + const { + navigate: filter, + isNavigating: isFiltering, + searchParams + } = useNavigationContext(); + + const [deleteOpen, setDeleteOpen] = useState(false); + const [selected, setSelected] = useState(null); + const [togglingId, setTogglingId] = useState(null); + + const page = Math.max(1, Number(searchParams.get("page") ?? 1)); + const pageSize = Math.max(1, Number(searchParams.get("pageSize") ?? 20)); + const pageIndex = page - 1; + const query = searchParams.get("query") ?? undefined; + const sortBy = searchParams.get("sort_by") ?? undefined; + const order = searchParams.get("order") ?? undefined; + const enabledForQuery = alertRulesEnabledQuerySchema.parse( + searchParams.get("enabled") ?? undefined + ); + + const enabledFilterOptions = useMemo( + () => [ + { value: "true", label: t("enabled") }, + { value: "false", label: t("disabled") } + ], + [t] + ); + + const rows = alertRules; + const total = rowCount; + const pageCount = Math.max(1, Math.ceil(total / pageSize)); + + function refreshList() { + startRefresh(() => { + router.refresh(); + }); + } + + const paginationState: DataTablePaginationState = { + pageIndex, + pageSize, + pageCount + }; + + const handlePaginationChange = (newState: PaginationState) => { + searchParams.set("page", (newState.pageIndex + 1).toString()); + searchParams.set("pageSize", newState.pageSize.toString()); + filter({ searchParams }); + }; + + const handleSearchChange = useDebouncedCallback((value: string) => { + if (value) { + searchParams.set("query", value); + } else { + searchParams.delete("query"); + } + searchParams.delete("page"); + filter({ searchParams }); + }, 300); + + function toggleSort(column: string) { + filter({ + searchParams: getNextSortOrder(column, searchParams) + }); + } + + function handleEnabledFilter(value: string | undefined | null) { + const sp = new URLSearchParams(searchParams); + sp.delete("enabled"); + sp.delete("page"); + if (value) { + sp.set("enabled", value); + } + filter({ searchParams: sp }); + } + + const setEnabled = async (rule: AlertRuleRow, enabled: boolean) => { + setTogglingId(rule.alertRuleId); + try { + await api.post(`/org/${orgId}/alert-rule/${rule.alertRuleId}`, { + enabled + }); + refreshList(); + } catch (e) { + toast({ + title: t("error"), + description: formatAxiosError(e), + variant: "destructive" + }); + } finally { + setTogglingId(null); + } + }; + + const confirmDelete = async () => { + if (!selected) return; + try { + await api.delete( + `/org/${orgId}/alert-rule/${selected.alertRuleId}` + ); + refreshList(); + toast({ title: t("alertingRuleDeleted") }); + } catch (e) { + toast({ + title: t("error"), + description: formatAxiosError(e), + variant: "destructive" + }); + } finally { + setDeleteOpen(false); + setSelected(null); + } + }; + + const columns: ExtendedColumnDef[] = [ + { + accessorKey: "name", + enableHiding: false, + friendlyName: t("name"), + header: () => { + const nameOrder = getSortDirection("name", searchParams); + const Icon = + nameOrder === "asc" + ? ArrowDown01Icon + : nameOrder === "desc" + ? ArrowUp10Icon + : ChevronsUpDownIcon; + return ( + + ); + }, + cell: ({ row }) => {row.original.name} + }, + { + id: "source", + friendlyName: t("alertingColumnSource"), + header: () => ( + {t("alertingColumnSource")} + ), + cell: ({ row }) => {sourceSummary(row.original, t)} + }, + { + id: "trigger", + friendlyName: t("alertingColumnTrigger"), + header: () => ( + {t("alertingColumnTrigger")} + ), + cell: ({ row }) => {triggerLabel(row.original, t)} + }, + { + accessorKey: "lastTriggeredAt", + friendlyName: t("lastTriggeredAt"), + header: () => { + const triggerOrder = getSortDirection( + "last_triggered_at", + searchParams + ); + const Icon = + triggerOrder === "asc" + ? ArrowDown01Icon + : triggerOrder === "desc" + ? ArrowUp10Icon + : ChevronsUpDownIcon; + return ( + + ); + }, + cell: ({ row }) => ( + + {row.original.lastTriggeredAt + ? moment(row.original.lastTriggeredAt).format("lll") + : "-"} + + ) + }, + { + accessorKey: "enabled", + friendlyName: t("alertingColumnEnabled"), + header: () => ( + + ), + cell: ({ row }) => { + const r = row.original; + return ( + setEnabled(r, v)} + /> + ); + } + }, + { + id: "rowActions", + enableHiding: false, + header: () => , + cell: ({ row }) => { + const r = row.original; + return ( +
+ + + + + + { + setSelected(r); + setDeleteOpen(true); + }} + > + + {t("delete")} + + + + + +
+ ); + } + } + ]; + + return ( + <> + {selected && ( + { + setDeleteOpen(val); + if (!val) setSelected(null); + }} + dialog={ +
+

{t("alertingDeleteQuestion")}

+
+ } + buttonText={t("delete")} + onConfirm={confirmDelete} + string={selected.name} + title={t("alertingDeleteRule")} + /> + )} + + + { + router.push(`/${orgId}/settings/alerting/create`); + }} + onRefresh={refreshList} + isRefreshing={isRefreshing || isFiltering} + addButtonText={t("alertingAddRule")} + enableColumnVisibility + stickyLeftColumn="name" + stickyRightColumn="rowActions" + pagination={paginationState} + onPaginationChange={handlePaginationChange} + /> + + ); +} diff --git a/src/components/BrandingLogo.tsx b/src/components/BrandingLogo.tsx index f6152f150..aa5112409 100644 --- a/src/components/BrandingLogo.tsx +++ b/src/components/BrandingLogo.tsx @@ -48,6 +48,7 @@ export default function BrandingLogo(props: BrandingLogoProps) { // we use `img` tag here because the `logoPath` could be any URL // and next.js `Image` component only accepts a restricted number of domains const Component = props.logoPath ? "img" : Image; + const isNextImage = Component === Image; return ( path && ( @@ -56,6 +57,11 @@ export default function BrandingLogo(props: BrandingLogoProps) { alt="Logo" width={props.width} height={props.height} + style={ + isNextImage + ? { width: "auto", height: "auto" } + : undefined + } /> ) ); diff --git a/src/components/ClientInfoCard.tsx b/src/components/ClientInfoCard.tsx index ece2309e2..7f55a46cd 100644 --- a/src/components/ClientInfoCard.tsx +++ b/src/components/ClientInfoCard.tsx @@ -49,7 +49,7 @@ export default function SiteInfoCard({}: ClientInfoCardProps) {
) : (
-
+
{t("offline")}
)} diff --git a/src/components/ClientResourcesTable.tsx b/src/components/ClientResourcesTable.tsx index 5066f273d..36f8caa78 100644 --- a/src/components/ClientResourcesTable.tsx +++ b/src/components/ClientResourcesTable.tsx @@ -21,6 +21,7 @@ import { ArrowUp10Icon, ArrowUpDown, ArrowUpRight, + ChevronDown, ChevronsUpDownIcon, MoreHorizontal } from "lucide-react"; @@ -38,21 +39,32 @@ import { ControlledDataTable } from "./ui/controlled-data-table"; import { useNavigationContext } from "@app/hooks/useNavigationContext"; import { useDebouncedCallback } from "use-debounce"; import { ColumnFilterButton } from "./ColumnFilterButton"; +import { cn } from "@app/lib/cn"; + +export type InternalResourceSiteRow = { + siteId: number; + siteName: string; + siteNiceId: string; + online: boolean; +}; export type InternalResourceRow = { id: number; name: string; orgId: string; - siteName: string; - siteAddress: string | null; + sites: InternalResourceSiteRow[]; + siteNames: string[]; + siteAddresses: (string | null)[]; + siteIds: number[]; + siteNiceIds: string[]; // mode: "host" | "cidr" | "port"; - mode: "host" | "cidr"; + mode: "host" | "cidr" | "http"; + scheme: "http" | "https" | null; + ssl: boolean; // protocol: string | null; // proxyPort: number | null; - siteId: number; - siteNiceId: string; destination: string; - // destinationPort: number | null; + httpHttpsPort: number | null; alias: string | null; aliasAddress: string | null; niceId: string; @@ -61,8 +73,147 @@ export type InternalResourceRow = { disableIcmp: boolean; authDaemonMode?: "site" | "remote" | null; authDaemonPort?: number | null; + subdomain?: string | null; + domainId?: string | null; + fullDomain?: string | null; }; +function resolveHttpHttpsDisplayPort( + mode: "http", + httpHttpsPort: number | null +): number { + if (httpHttpsPort != null) { + return httpHttpsPort; + } + return 80; +} + +function formatDestinationDisplay(row: InternalResourceRow): string { + const { mode, destination, httpHttpsPort, scheme } = row; + if (mode !== "http") { + return destination; + } + const port = resolveHttpHttpsDisplayPort(mode, httpHttpsPort); + const downstreamScheme = scheme ?? "http"; + const hostPart = + destination.includes(":") && !destination.startsWith("[") + ? `[${destination}]` + : destination; + return `${downstreamScheme}://${hostPart}:${port}`; +} + +function isSafeUrlForLink(href: string): boolean { + try { + void new URL(href); + return true; + } catch { + return false; + } +} + +type AggregateSitesStatus = "allOnline" | "partial" | "allOffline"; + +function aggregateSitesStatus( + resourceSites: InternalResourceSiteRow[] +): AggregateSitesStatus { + if (resourceSites.length === 0) { + return "allOffline"; + } + const onlineCount = resourceSites.filter((rs) => rs.online).length; + if (onlineCount === resourceSites.length) return "allOnline"; + if (onlineCount > 0) return "partial"; + return "allOffline"; +} + +function aggregateStatusDotClass(status: AggregateSitesStatus): string { + switch (status) { + case "allOnline": + return "bg-green-500"; + case "partial": + return "bg-yellow-500"; + case "allOffline": + default: + return "bg-neutral-500"; + } +} + +function ClientResourceSitesStatusCell({ + orgId, + resourceSites +}: { + orgId: string; + resourceSites: InternalResourceSiteRow[]; +}) { + const t = useTranslations(); + + if (resourceSites.length === 0) { + return -; + } + + const aggregate = aggregateSitesStatus(resourceSites); + const countLabel = t("multiSitesSelectorSitesCount", { + count: resourceSites.length + }); + + return ( + + + + + + {resourceSites.map((site) => { + const isOnline = site.online; + return ( + + +
+
+ + {site.siteName} + +
+ + {isOnline ? t("online") : t("offline")} + + + + ); + })} + + + ); +} + type ClientResourcesTableProps = { internalResources: InternalResourceRow[]; orgId: string; @@ -97,8 +248,6 @@ export default function ClientResourcesTable({ useState(); const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false); - const { data: sites = [] } = useQuery(orgQueries.sites({ orgId })); - const [isRefreshing, startTransition] = useTransition(); const refreshData = () => { @@ -136,6 +285,60 @@ export default function ClientResourcesTable({ } }; + function SiteCell({ resourceRow }: { resourceRow: InternalResourceRow }) { + const { siteNames, siteNiceIds, orgId } = resourceRow; + + if (!siteNames || siteNames.length === 0) { + return -; + } + + if (siteNames.length === 1) { + return ( + + + + ); + } + + return ( + + + + + + {siteNames.map((siteName, idx) => ( + + + {siteName} + + + + ))} + + + ); + } + const internalColumns: ExtendedColumnDef[] = [ { accessorKey: "name", @@ -185,20 +388,17 @@ export default function ClientResourcesTable({ } }, { - accessorKey: "siteName", - friendlyName: t("site"), - header: () => {t("site")}, + id: "sites", + accessorFn: (row) => row.sites.map((s) => s.siteName).join(", "), + friendlyName: t("sites"), + header: () => {t("sites")}, cell: ({ row }) => { const resourceRow = row.original; return ( - - - + ); } }, @@ -215,6 +415,10 @@ export default function ClientResourcesTable({ { value: "cidr", label: t("editInternalResourceDialogModeCidr") + }, + { + value: "http", + label: t("editInternalResourceDialogModeHttp") } ]} selectedValue={searchParams.get("mode") ?? undefined} @@ -227,10 +431,14 @@ export default function ClientResourcesTable({ ), cell: ({ row }) => { const resourceRow = row.original; - const modeLabels: Record<"host" | "cidr" | "port", string> = { + const modeLabels: Record< + "host" | "cidr" | "port" | "http", + string + > = { host: t("editInternalResourceDialogModeHost"), cidr: t("editInternalResourceDialogModeCidr"), - port: t("editInternalResourceDialogModePort") + port: t("editInternalResourceDialogModePort"), + http: t("editInternalResourceDialogModeHttp") }; return {modeLabels[resourceRow.mode]}; } @@ -243,11 +451,12 @@ export default function ClientResourcesTable({ ), cell: ({ row }) => { const resourceRow = row.original; + const display = formatDestinationDisplay(resourceRow); return ( ); } @@ -260,15 +469,26 @@ export default function ClientResourcesTable({ ), cell: ({ row }) => { const resourceRow = row.original; - return resourceRow.mode === "host" && resourceRow.alias ? ( - - ) : ( - - - ); + if (resourceRow.mode === "host" && resourceRow.alias) { + return ( + + ); + } + if (resourceRow.mode === "http") { + const url = `${resourceRow.ssl ? "https" : "http"}://${resourceRow.fullDomain}`; + return ( + + ); + } + return -; } }, { @@ -399,7 +619,7 @@ export default function ClientResourcesTable({ onConfirm={async () => deleteInternalResource( selectedInternalResource!.id, - selectedInternalResource!.siteId + selectedInternalResource!.siteIds[0] ) } string={selectedInternalResource.name} @@ -435,7 +655,6 @@ export default function ClientResourcesTable({ setOpen={setIsEditDialogOpen} resource={editingResource} orgId={orgId} - sites={sites} onSuccess={() => { // Delay refresh to allow modal to close smoothly setTimeout(() => { @@ -450,7 +669,6 @@ export default function ClientResourcesTable({ open={isCreateDialogOpen} setOpen={setIsCreateDialogOpen} orgId={orgId} - sites={sites} onSuccess={() => { // Delay refresh to allow modal to close smoothly setTimeout(() => { diff --git a/src/components/ColumnMultiFilterButton.tsx b/src/components/ColumnMultiFilterButton.tsx new file mode 100644 index 000000000..ee386461d --- /dev/null +++ b/src/components/ColumnMultiFilterButton.tsx @@ -0,0 +1,146 @@ +"use client"; + +import { useMemo, useState } from "react"; +import { useTranslations } from "next-intl"; +import { Button } from "@app/components/ui/button"; +import { + Popover, + PopoverContent, + PopoverTrigger +} from "@app/components/ui/popover"; +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList +} from "@app/components/ui/command"; +import { CheckIcon, Funnel } from "lucide-react"; +import { cn } from "@app/lib/cn"; +import { Badge } from "./ui/badge"; + +type FilterOption = { + value: string; + label: string; +}; + +type ColumnMultiFilterButtonProps = { + options: FilterOption[]; + selectedValues: string[]; + onSelectedValuesChange: (values: string[]) => void; + searchPlaceholder?: string; + emptyMessage?: string; + className?: string; + label: string; +}; + +export function ColumnMultiFilterButton({ + options, + selectedValues, + onSelectedValuesChange, + searchPlaceholder = "Search...", + emptyMessage = "No options found", + className, + label +}: ColumnMultiFilterButtonProps) { + const [open, setOpen] = useState(false); + const t = useTranslations(); + + const selectedSet = useMemo( + () => new Set(selectedValues), + [selectedValues] + ); + + const summary = useMemo(() => { + if (selectedValues.length === 0) { + return null; + } + if (selectedValues.length === 1) { + return ( + options.find((o) => o.value === selectedValues[0])?.label ?? + selectedValues[0] + ); + } + return t("accessUsersRoleFilterCount", { + count: selectedValues.length + }); + }, [selectedValues, options, t]); + + function toggle(value: string) { + const next = selectedSet.has(value) + ? selectedValues.filter((v) => v !== value) + : [...selectedValues, value]; + onSelectedValuesChange(next); + } + + return ( + + + + + + + + + {emptyMessage} + + {selectedValues.length > 0 && ( + { + onSelectedValuesChange([]); + setOpen(false); + }} + className="text-muted-foreground" + > + {t("accessUsersRoleFilterClear")} + + )} + {options.map((option) => ( + { + toggle(option.value); + }} + > + + {option.label} + + ))} + + + + + + ); +} diff --git a/src/components/ContactSalesBanner.tsx b/src/components/ContactSalesBanner.tsx new file mode 100644 index 000000000..e5cb87d83 --- /dev/null +++ b/src/components/ContactSalesBanner.tsx @@ -0,0 +1,42 @@ +"use client"; + +import { KeyRound, ExternalLink } from "lucide-react"; +import Link from "next/link"; +import { useTranslations } from "next-intl"; + +export function ContactSalesBanner() { + const t = useTranslations(); + + return ( +
+
+
+ + + {t("contactSalesEnable")}{" "} + + {t("contactSalesBookDemo")} + + + {" " + t("contactSalesOr") + " "} + + {t("contactSalesContactUs")} + + + . + +
+
+
+ ); +} \ No newline at end of file diff --git a/src/components/CreateInternalResourceDialog.tsx b/src/components/CreateInternalResourceDialog.tsx index d5ca61acc..4d2bc0916 100644 --- a/src/components/CreateInternalResourceDialog.tsx +++ b/src/components/CreateInternalResourceDialog.tsx @@ -14,7 +14,6 @@ import { Button } from "@app/components/ui/button"; import { useEnvContext } from "@app/hooks/useEnvContext"; import { toast } from "@app/hooks/useToast"; import { createApiClient, formatAxiosError } from "@app/lib/api"; -import { ListSitesResponse } from "@server/routers/site"; import { AxiosResponse } from "axios"; import { useTranslations } from "next-intl"; import { useState } from "react"; @@ -25,13 +24,10 @@ import { type InternalResourceFormValues } from "./InternalResourceForm"; -type Site = ListSitesResponse["sites"][0]; - type CreateInternalResourceDialogProps = { open: boolean; setOpen: (val: boolean) => void; orgId: string; - sites: Site[]; onSuccess?: () => void; }; @@ -39,18 +35,21 @@ export default function CreateInternalResourceDialog({ open, setOpen, orgId, - sites, onSuccess }: CreateInternalResourceDialogProps) { const t = useTranslations(); const api = createApiClient(useEnvContext()); const [isSubmitting, setIsSubmitting] = useState(false); + const [isHttpModeDisabled, setIsHttpModeDisabled] = useState(false); async function handleSubmit(values: InternalResourceFormValues) { setIsSubmitting(true); try { let data = { ...values }; - if (data.mode === "host" && isHostname(data.destination)) { + if ( + (data.mode === "host" || data.mode === "http") && + isHostname(data.destination) + ) { const currentAlias = data.alias?.trim() || ""; if (!currentAlias) { let aliasValue = data.destination; @@ -65,25 +64,56 @@ export default function CreateInternalResourceDialog({ `/org/${orgId}/site-resource`, { name: data.name, - siteId: data.siteId, + siteIds: data.siteIds, mode: data.mode, destination: data.destination, enabled: true, - alias: data.alias && typeof data.alias === "string" && data.alias.trim() ? data.alias : undefined, - tcpPortRangeString: data.tcpPortRangeString, - udpPortRangeString: data.udpPortRangeString, - disableIcmp: data.disableIcmp ?? false, - ...(data.authDaemonMode != null && { authDaemonMode: data.authDaemonMode }), - ...(data.authDaemonMode === "remote" && data.authDaemonPort != null && { authDaemonPort: data.authDaemonPort }), - roleIds: data.roles ? data.roles.map((r) => parseInt(r.id)) : [], + ...(data.mode === "http" && { + scheme: data.scheme, + ssl: data.ssl ?? false, + destinationPort: data.httpHttpsPort ?? undefined, + domainId: data.httpConfigDomainId + ? data.httpConfigDomainId + : undefined, + subdomain: data.httpConfigSubdomain + ? data.httpConfigSubdomain + : undefined + }), + ...(data.mode === "host" && { + alias: + data.alias && + typeof data.alias === "string" && + data.alias.trim() + ? data.alias + : undefined, + ...(data.authDaemonMode != null && { + authDaemonMode: data.authDaemonMode + }), + ...(data.authDaemonMode === "remote" && + data.authDaemonPort != null && { + authDaemonPort: data.authDaemonPort + }) + }), + ...((data.mode === "host" || data.mode == "cidr") && { + tcpPortRangeString: data.tcpPortRangeString, + udpPortRangeString: data.udpPortRangeString, + disableIcmp: data.disableIcmp ?? false + }), + roleIds: data.roles + ? data.roles.map((r) => parseInt(r.id)) + : [], userIds: data.users ? data.users.map((u) => u.id) : [], - clientIds: data.clients ? data.clients.map((c) => parseInt(c.id)) : [] + clientIds: data.clients + ? data.clients.map((c) => parseInt(c.id)) + : [] } ); toast({ title: t("createInternalResourceDialogSuccess"), - description: t("createInternalResourceDialogInternalResourceCreatedSuccessfully"), + description: t( + "createInternalResourceDialogInternalResourceCreatedSuccessfully" + ), variant: "default" }); setOpen(false); @@ -93,7 +123,9 @@ export default function CreateInternalResourceDialog({ title: t("createInternalResourceDialogError"), description: formatAxiosError( error, - t("createInternalResourceDialogFailedToCreateInternalResource") + t( + "createInternalResourceDialogFailedToCreateInternalResource" + ) ), variant: "destructive" }); @@ -106,31 +138,39 @@ export default function CreateInternalResourceDialog({ - {t("createInternalResourceDialogCreateClientResource")} + + {t("createInternalResourceDialogCreateClientResource")} + - {t("createInternalResourceDialogCreateClientResourceDescription")} + {t( + "createInternalResourceDialogCreateClientResourceDescription" + )} - + + + + + ); +} diff --git a/src/components/DomainPageClient.tsx b/src/components/DomainPageClient.tsx new file mode 100644 index 000000000..31527c5b8 --- /dev/null +++ b/src/components/DomainPageClient.tsx @@ -0,0 +1,93 @@ +"use client"; + +import { useQuery } from "@tanstack/react-query"; +import { domainQueries } from "@app/lib/queries"; +import { GetDomainResponse } from "@server/routers/domain/getDomain"; +import { GetDNSRecordsResponse } from "@server/routers/domain"; +import DomainInfoCard from "@app/components/DomainInfoCard"; +import DNSRecordsTable from "@app/components/DNSRecordTable"; +import RestartDomainButton from "@app/components/RestartDomainButton"; +import RefreshButton from "@app/components/RefreshButton"; +import SettingsSectionTitle from "@app/components/SettingsSectionTitle"; +import DomainCertForm from "@app/components/DomainCertForm"; +import { build } from "@server/build"; +import { useEnvContext } from "@app/hooks/useEnvContext"; +import { useTranslations } from "next-intl"; + +interface DomainPageClientProps { + initialDomain: GetDomainResponse; + initialDnsRecords: GetDNSRecordsResponse; + orgId: string; + domainId: string; +} + +export default function DomainPageClient({ + initialDomain, + initialDnsRecords, + orgId, + domainId +}: DomainPageClientProps) { + const t = useTranslations(); + const { env } = useEnvContext(); + + const { data: domain, refetch: refetchDomain } = useQuery({ + ...domainQueries.getDomain({ orgId, domainId }), + initialData: initialDomain + }); + + const { data: dnsRecords, refetch: refetchDnsRecords } = useQuery({ + ...domainQueries.getDNSRecords({ orgId, domainId }), + initialData: initialDnsRecords + }); + + const refetchAll = () => { + refetchDomain(); + refetchDnsRecords(); + }; + + return ( + <> +
+ + {env.flags.usePangolinDns && domain.failed ? ( + + ) : ( + + )} +
+
+ {build !== "oss" && env.flags.usePangolinDns ? ( + + ) : null} + + ({ + ...r, + id: String(r.id) + }))} + type={domain.type} + /> + + {domain.type === "wildcard" && !domain.configManaged && ( + + )} +
+ + ); +} \ No newline at end of file diff --git a/src/components/DomainPicker.tsx b/src/components/DomainPicker.tsx index ac8493d6e..7a90dfa67 100644 --- a/src/components/DomainPicker.tsx +++ b/src/components/DomainPicker.tsx @@ -175,15 +175,18 @@ export default function DomainPicker({ domainId: firstOrExistingDomain.domainId }; + const base = firstOrExistingDomain.baseDomain; + const sub = + firstOrExistingDomain.type !== "cname" + ? defaultSubdomain?.trim() || undefined + : undefined; + onDomainChange?.({ domainId: firstOrExistingDomain.domainId, type: "organization", - subdomain: - firstOrExistingDomain.type !== "cname" - ? defaultSubdomain || undefined - : undefined, - fullDomain: firstOrExistingDomain.baseDomain, - baseDomain: firstOrExistingDomain.baseDomain + subdomain: sub, + fullDomain: sub ? `${sub}.${base}` : base, + baseDomain: base }); } } diff --git a/src/components/DomainsTable.tsx b/src/components/DomainsTable.tsx index f5cb1ae74..2c3abeb1a 100644 --- a/src/components/DomainsTable.tsx +++ b/src/components/DomainsTable.tsx @@ -10,13 +10,12 @@ import { MoreHorizontal, RefreshCw } from "lucide-react"; -import { useState } from "react"; +import { useMemo, useState } from "react"; import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog"; import { formatAxiosError } from "@app/lib/api"; import { createApiClient } from "@app/lib/api"; import { useEnvContext } from "@app/hooks/useEnvContext"; import { Badge } from "@app/components/ui/badge"; -import { useRouter } from "next/navigation"; import { useTranslations } from "next-intl"; import CreateDomainForm from "@app/components/CreateDomainForm"; import { useToast } from "@app/hooks/useToast"; @@ -34,6 +33,10 @@ import { TooltipTrigger } from "./ui/tooltip"; import Link from "next/link"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { orgQueries } from "@app/lib/queries"; +import { toUnicode } from "punycode"; +import { durationToMs } from "@app/lib/durationToMs"; export type DomainRow = { domainId: string; @@ -59,32 +62,32 @@ export default function DomainsTable({ domains, orgId }: Props) { const [selectedDomain, setSelectedDomain] = useState( null ); - const [isRefreshing, setIsRefreshing] = useState(false); const [restartingDomains, setRestartingDomains] = useState>( new Set() ); const env = useEnvContext(); const api = createApiClient(env); - const router = useRouter(); const t = useTranslations(); const { toast } = useToast(); const { org } = useOrgContext(); + const queryClient = useQueryClient(); - const refreshData = async () => { - setIsRefreshing(true); - try { - await new Promise((resolve) => setTimeout(resolve, 200)); - router.refresh(); - } catch (error) { - toast({ - title: t("error"), - description: t("refreshError"), - variant: "destructive" - }); - } finally { - setIsRefreshing(false); - } - }; + const { data: rawDomains, isRefetching, refetch } = useQuery({ + ...orgQueries.domains({ orgId }), + initialData: domains as any, + refetchInterval: durationToMs(10, "seconds") + }); + + const tableData = useMemo( + () => + (rawDomains ?? []).map((d) => ({ + ...d, + baseDomain: toUnicode(d.baseDomain), + type: d.type ?? "", + errorMessage: d.errorMessage ?? null + } as DomainRow)), + [rawDomains] + ); const deleteDomain = async (domainId: string) => { try { @@ -94,7 +97,7 @@ export default function DomainsTable({ domains, orgId }: Props) { description: t("domainDeletedDescription") }); setIsDeleteModalOpen(false); - refreshData(); + refetch(); } catch (e) { toast({ title: t("error"), @@ -114,7 +117,7 @@ export default function DomainsTable({ domains, orgId }: Props) { fallback: "Domain verification restarted successfully" }) }); - refreshData(); + refetch(); } catch (e) { toast({ title: t("error"), @@ -361,16 +364,16 @@ export default function DomainsTable({ domains, orgId }: Props) { open={isCreateModalOpen} setOpen={setIsCreateModalOpen} onCreated={(domain) => { - refreshData(); + refetch(); }} /> setIsCreateModalOpen(true)} - onRefresh={refreshData} - isRefreshing={isRefreshing} + onRefresh={refetch} + isRefreshing={isRefetching} /> ); diff --git a/src/components/EditInternalResourceDialog.tsx b/src/components/EditInternalResourceDialog.tsx index 690ad405d..859981f7d 100644 --- a/src/components/EditInternalResourceDialog.tsx +++ b/src/components/EditInternalResourceDialog.tsx @@ -15,7 +15,6 @@ import { useEnvContext } from "@app/hooks/useEnvContext"; import { toast } from "@app/hooks/useToast"; import { createApiClient, formatAxiosError } from "@app/lib/api"; import { resourceQueries } from "@app/lib/queries"; -import { ListSitesResponse } from "@server/routers/site"; import { useQueryClient } from "@tanstack/react-query"; import { useTranslations } from "next-intl"; import { useState, useTransition } from "react"; @@ -27,14 +26,11 @@ import { isHostname } from "./InternalResourceForm"; -type Site = ListSitesResponse["sites"][0]; - type EditInternalResourceDialogProps = { open: boolean; setOpen: (val: boolean) => void; resource: InternalResourceData; orgId: string; - sites: Site[]; onSuccess?: () => void; }; @@ -43,18 +39,21 @@ export default function EditInternalResourceDialog({ setOpen, resource, orgId, - sites, onSuccess }: EditInternalResourceDialogProps) { const t = useTranslations(); const api = createApiClient(useEnvContext()); const queryClient = useQueryClient(); const [isSubmitting, startTransition] = useTransition(); + const [isHttpModeDisabled, setIsHttpModeDisabled] = useState(false); async function handleSubmit(values: InternalResourceFormValues) { try { let data = { ...values }; - if (data.mode === "host" && isHostname(data.destination)) { + if ( + (data.mode === "host" || data.mode === "http") && + isHostname(data.destination) + ) { const currentAlias = data.alias?.trim() || ""; if (!currentAlias) { let aliasValue = data.destination; @@ -67,24 +66,39 @@ export default function EditInternalResourceDialog({ await api.post(`/site-resource/${resource.id}`, { name: data.name, - siteId: data.siteId, + siteIds: data.siteIds, mode: data.mode, niceId: data.niceId, destination: data.destination, - alias: - data.alias && - typeof data.alias === "string" && - data.alias.trim() - ? data.alias - : null, - tcpPortRangeString: data.tcpPortRangeString, - udpPortRangeString: data.udpPortRangeString, - disableIcmp: data.disableIcmp ?? false, - ...(data.authDaemonMode != null && { - authDaemonMode: data.authDaemonMode + ...(data.mode === "http" && { + scheme: data.scheme, + ssl: data.ssl ?? false, + destinationPort: data.httpHttpsPort ?? null, + domainId: data.httpConfigDomainId + ? data.httpConfigDomainId + : undefined, + subdomain: data.httpConfigSubdomain + ? data.httpConfigSubdomain + : undefined }), - ...(data.authDaemonMode === "remote" && { - authDaemonPort: data.authDaemonPort || null + ...(data.mode === "host" && { + alias: + data.alias && + typeof data.alias === "string" && + data.alias.trim() + ? data.alias + : null, + ...(data.authDaemonMode != null && { + authDaemonMode: data.authDaemonMode + }), + ...(data.authDaemonMode === "remote" && { + authDaemonPort: data.authDaemonPort || null + }) + }), + ...((data.mode === "host" || data.mode === "cidr") && { + tcpPortRangeString: data.tcpPortRangeString, + udpPortRangeString: data.udpPortRangeString, + disableIcmp: data.disableIcmp ?? false }), roleIds: (data.roles || []).map((r) => parseInt(r.id)), userIds: (data.users || []).map((u) => u.id), @@ -156,13 +170,13 @@ export default function EditInternalResourceDialog({ variant="edit" open={open} resource={resource} - sites={sites} orgId={orgId} siteResourceId={resource.id} formId="edit-internal-resource-form" onSubmit={(values) => startTransition(() => handleSubmit(values)) } + onSubmitDisabledChange={setIsHttpModeDisabled} /> @@ -178,7 +192,7 @@ export default function EditInternalResourceDialog({
) : (
-
+
{t("offline")}
)} diff --git a/src/components/ExitNodesTable.tsx b/src/components/ExitNodesTable.tsx index 5c39f409e..67d819a47 100644 --- a/src/components/ExitNodesTable.tsx +++ b/src/components/ExitNodesTable.tsx @@ -146,7 +146,7 @@ export default function ExitNodesTable({ } else { return ( -
+
{t("offline")}
); diff --git a/src/components/HealthCheckCredenza.tsx b/src/components/HealthCheckCredenza.tsx new file mode 100644 index 000000000..671a16e7d --- /dev/null +++ b/src/components/HealthCheckCredenza.tsx @@ -0,0 +1,1386 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { z } from "zod"; +import { useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { + Form, + FormControl, + FormDescription, + FormField, + FormItem, + FormLabel, + FormMessage +} from "@/components/ui/form"; +import { Input } from "@/components/ui/input"; +import { Switch } from "@/components/ui/switch"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue +} from "@/components/ui/select"; +import { StrategySelect } from "@app/components/StrategySelect"; +import { HeadersInput } from "@app/components/HeadersInput"; +import { HorizontalTabs } from "@app/components/HorizontalTabs"; +import { + Credenza, + CredenzaBody, + CredenzaClose, + CredenzaContent, + CredenzaDescription, + CredenzaFooter, + CredenzaHeader, + CredenzaTitle +} from "@/components/Credenza"; +import { toast } from "@app/hooks/useToast"; +import { createApiClient, formatAxiosError } from "@app/lib/api"; +import { useEnvContext } from "@app/hooks/useEnvContext"; +import { useTranslations } from "next-intl"; +import { ContactSalesBanner } from "@app/components/ContactSalesBanner"; +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; +import { SitesSelector } from "@app/components/site-selector"; +import type { Selectedsite } from "@app/components/site-selector"; +import { CaretSortIcon } from "@radix-ui/react-icons"; +import { cn } from "@app/lib/cn"; + +export type HealthCheckConfig = { + hcEnabled: boolean; + hcPath: string; + hcMethod: string; + hcInterval: number; + hcTimeout: number; + hcStatus: number | null; + hcHeaders?: { name: string; value: string }[] | null; + hcScheme?: string; + hcHostname: string; + hcPort: number; + hcFollowRedirects: boolean; + hcMode: string; + hcUnhealthyInterval: number; + hcTlsServerName: string; + hcHealthyThreshold: number; + hcUnhealthyThreshold: number; +}; + +export type HealthCheckRow = { + targetHealthCheckId: number; + name: string; + hcEnabled: boolean; + hcHealth: "unknown" | "healthy" | "unhealthy"; + hcMode: string | null; + hcHostname: string | null; + hcPort: number | null; + hcPath: string | null; + hcScheme: string | null; + hcMethod: string | null; + hcInterval: number | null; + hcUnhealthyInterval: number | null; + hcTimeout: number | null; + hcHeaders: string | null; + hcFollowRedirects: boolean | null; + hcStatus: number | null; + hcTlsServerName: string | null; + hcHealthyThreshold: number | null; + hcUnhealthyThreshold: number | null; + resourceId: number | null; + resourceName: string | null; + resourceNiceId: string | null; + siteId: number | null; + siteName: string | null; + siteNiceId: string | null; +}; + +export type HealthCheckCredenzaProps = + | { + mode: "autoSave"; + open: boolean; + setOpen: (v: boolean) => void; + orgId?: string; + targetAddress: string; + targetMethod?: string; + initialConfig?: Partial; + onChanges: (config: HealthCheckConfig) => Promise; + } + | { + mode: "submit"; + open: boolean; + setOpen: (v: boolean) => void; + orgId: string; + initialValues?: HealthCheckRow | null; + onSaved: () => void; + }; + +const DEFAULT_VALUES = { + name: "", + hcEnabled: true, + hcMode: "http", + hcScheme: "https", + hcMethod: "GET", + hcHostname: "", + hcPort: "", + hcPath: "/", + hcInterval: 30, + hcUnhealthyInterval: 30, + hcTimeout: 5, + hcHealthyThreshold: 1, + hcUnhealthyThreshold: 1, + hcFollowRedirects: true, + hcTlsServerName: "", + hcStatus: null as number | null, + hcHeaders: [] as { name: string; value: string }[] +}; + +export function HealthCheckCredenza(props: HealthCheckCredenzaProps) { + const { mode, open, setOpen, orgId } = props; + + const t = useTranslations(); + const api = createApiClient(useEnvContext()); + const [loading, setLoading] = useState(false); + const [selectedSite, setSelectedSite] = useState(null); + + const healthCheckSchema = z + .object({ + ...(mode === "submit" + ? { + name: z + .string() + .min(1, { message: t("standaloneHcNameLabel") }) + } + : {}), + hcEnabled: z.boolean(), + hcPath: z.string().optional(), + hcMethod: z.string().optional(), + hcInterval: z + .int() + .positive() + .min(5, { message: t("healthCheckIntervalMin") }), + hcTimeout: z + .int() + .positive() + .min(1, { message: t("healthCheckTimeoutMin") }), + hcStatus: z.int().positive().min(100).optional().nullable(), + hcHeaders: z + .array(z.object({ name: z.string(), value: z.string() })) + .nullable() + .optional(), + hcScheme: z.string().optional(), + hcHostname: z.string(), + hcPort: z + .string() + .min(1, { message: t("healthCheckPortInvalid") }) + .refine( + (val) => { + const port = parseInt(val); + return port > 0 && port <= 65535; + }, + { message: t("healthCheckPortInvalid") } + ), + hcFollowRedirects: z.boolean(), + hcMode: z.string(), + hcUnhealthyInterval: z.int().positive().min(5), + hcTlsServerName: z.string(), + hcHealthyThreshold: z + .int() + .positive() + .min(1, { message: t("healthCheckHealthyThresholdMin") }), + hcUnhealthyThreshold: z + .int() + .positive() + .min(1, { message: t("healthCheckUnhealthyThresholdMin") }) + }) + .superRefine((data, ctx) => { + if (data.hcMode !== "tcp") { + if (!data.hcPath || data.hcPath.length < 1) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t("healthCheckPathRequired"), + path: ["hcPath"] + }); + } + if (!data.hcMethod || data.hcMethod.length < 1) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t("healthCheckMethodRequired"), + path: ["hcMethod"] + }); + } + } + }); + + type FormValues = z.infer; + + const form = useForm({ + resolver: zodResolver(healthCheckSchema), + defaultValues: mode === "submit" ? DEFAULT_VALUES : {} + }); + + const watchedEnabled = form.watch("hcEnabled"); + const watchedMode = form.watch("hcMode"); + + useEffect(() => { + if (!open) return; + + if (mode === "autoSave") { + const { initialConfig, targetMethod } = props; + + const getDefaultScheme = () => { + if (initialConfig?.hcScheme) return initialConfig.hcScheme; + if (targetMethod === "https") return "https"; + return "http"; + }; + + form.reset({ + hcEnabled: initialConfig?.hcEnabled, + hcPath: initialConfig?.hcPath, + hcMethod: initialConfig?.hcMethod, + hcInterval: initialConfig?.hcInterval, + hcTimeout: initialConfig?.hcTimeout, + hcStatus: initialConfig?.hcStatus, + hcHeaders: initialConfig?.hcHeaders, + hcScheme: getDefaultScheme(), + hcHostname: initialConfig?.hcHostname, + hcPort: initialConfig?.hcPort + ? initialConfig.hcPort.toString() + : "", + hcFollowRedirects: initialConfig?.hcFollowRedirects, + hcMode: initialConfig?.hcMode ?? "http", + hcUnhealthyInterval: initialConfig?.hcUnhealthyInterval, + hcTlsServerName: initialConfig?.hcTlsServerName ?? "", + hcHealthyThreshold: initialConfig?.hcHealthyThreshold ?? 1, + hcUnhealthyThreshold: initialConfig?.hcUnhealthyThreshold ?? 1 + }); + } else { + const { initialValues } = props; + + if (initialValues) { + let parsedHeaders: { name: string; value: string }[] = []; + if (initialValues.hcHeaders) { + try { + parsedHeaders = JSON.parse(initialValues.hcHeaders); + } catch { + parsedHeaders = []; + } + } + + form.reset({ + name: initialValues.name, + hcEnabled: initialValues.hcEnabled, + hcMode: initialValues.hcMode ?? "http", + hcScheme: initialValues.hcScheme ?? "https", + hcMethod: initialValues.hcMethod ?? "GET", + hcHostname: initialValues.hcHostname ?? "", + hcPort: initialValues.hcPort + ? initialValues.hcPort.toString() + : "", + hcPath: initialValues.hcPath ?? "/", + hcInterval: initialValues.hcInterval ?? 30, + hcUnhealthyInterval: + initialValues.hcUnhealthyInterval ?? 30, + hcTimeout: initialValues.hcTimeout ?? 5, + hcHealthyThreshold: initialValues.hcHealthyThreshold ?? 1, + hcUnhealthyThreshold: + initialValues.hcUnhealthyThreshold ?? 1, + hcFollowRedirects: initialValues.hcFollowRedirects ?? true, + hcTlsServerName: initialValues.hcTlsServerName ?? "", + hcStatus: initialValues.hcStatus ?? null, + hcHeaders: parsedHeaders + }); + if (initialValues.siteId && initialValues.siteName) { + setSelectedSite({ siteId: initialValues.siteId, name: initialValues.siteName, type: "" }); + } else { + setSelectedSite(null); + } + } else { + form.reset(DEFAULT_VALUES); + setSelectedSite(null); + } + } + }, [open]); + + const handleFieldChange = async (fieldName: string, value: any) => { + if (mode !== "autoSave") return; + try { + const currentValues = form.getValues(); + const updatedValues = { ...currentValues, [fieldName]: value }; + + const configToSend: HealthCheckConfig = { + ...updatedValues, + hcPath: updatedValues.hcPath ?? "", + hcMethod: updatedValues.hcMethod ?? "", + hcPort: parseInt(updatedValues.hcPort), + hcStatus: updatedValues.hcStatus || null, + hcHealthyThreshold: updatedValues.hcHealthyThreshold, + hcUnhealthyThreshold: updatedValues.hcUnhealthyThreshold + }; + + await props.onChanges(configToSend); + } catch (error) { + toast({ + title: t("healthCheckError"), + description: t("healthCheckErrorDescription"), + variant: "destructive" + }); + } + }; + + const handleChange = ( + fieldName: string, + value: any, + fieldOnChange: (v: any) => void + ) => { + fieldOnChange(value); + if (mode === "autoSave") { + handleFieldChange(fieldName, value); + } + }; + + const onSubmit = async (values: FormValues) => { + if (mode !== "submit") return; + const { initialValues, onSaved } = props; + + setLoading(true); + try { + const payload = { + name: (values as any).name, + siteId: selectedSite?.siteId, + hcEnabled: values.hcEnabled, + hcMode: values.hcMode, + hcScheme: values.hcScheme, + hcMethod: values.hcMethod, + hcHostname: values.hcHostname, + hcPort: parseInt(values.hcPort), + hcPath: values.hcPath ?? "", + hcInterval: values.hcInterval, + hcUnhealthyInterval: values.hcUnhealthyInterval, + hcTimeout: values.hcTimeout, + hcHealthyThreshold: values.hcHealthyThreshold, + hcUnhealthyThreshold: values.hcUnhealthyThreshold, + hcFollowRedirects: values.hcFollowRedirects, + hcTlsServerName: values.hcTlsServerName, + hcStatus: values.hcStatus || null, + hcHeaders: + values.hcHeaders && values.hcHeaders.length > 0 + ? JSON.stringify(values.hcHeaders) + : null + }; + + if (initialValues) { + await api.post( + `/org/${orgId}/health-check/${initialValues.targetHealthCheckId}`, + payload + ); + } else { + await api.put(`/org/${orgId}/health-check`, payload); + } + + toast({ title: t("standaloneHcSaved") }); + onSaved(); + setOpen(false); + } catch (e) { + toast({ + title: t("error"), + description: formatAxiosError(e), + variant: "destructive" + }); + } finally { + setLoading(false); + } + }; + + const isEditing = mode === "submit" && !!(props as any).initialValues; + + const title = + mode === "autoSave" + ? t("configureHealthCheck") + : isEditing + ? t("standaloneHcEditTitle") + : t("standaloneHcCreateTitle"); + + const description = + mode === "autoSave" + ? t("configureHealthCheckDescription", { + target: (props as any).targetAddress + }) + : t("standaloneHcDescription"); + + const showFields = mode === "submit" || watchedEnabled; + const isSnmpOrIcmp = watchedMode === "snmp" || watchedMode === "icmp"; + const isTcp = watchedMode === "tcp"; + + return ( + + + + {title} + {description} + + +
+ + {/* Name (submit mode only) */} + {mode === "submit" && ( + ( + + + {t("standaloneHcNameLabel")} + + + + + + + )} + /> + )} + + {/* Site picker (submit mode only) */} + {mode === "submit" && ( +
+ + {t("site")} + + + + + + { + setSelectedSite(site); + }} + /> + + + +
+ )} + +
+ + {/* ── Strategy tab ──────────────────────── */} +
+ {/* Enable toggle (autoSave mode only) */} + {mode === "autoSave" && ( + ( + +
+ + {t( + "enableHealthChecks" + )} + +
+ + + handleChange( + "hcEnabled", + value, + field.onChange + ) + } + /> + +
+ )} + /> + )} + + {/* Strategy picker */} + {showFields && ( + ( + + + + handleChange( + "hcMode", + value, + field.onChange + ) + } + /> + + + + )} + /> + )} +
+ + {/* ── Connection tab ────────────────────── */} +
+ {!showFields && ( +

+ {t("enableHealthChecks")} +

+ )} + + {/* Contact-sales banner for SNMP / ICMP */} + {showFields && isSnmpOrIcmp && ( + + )} + + {showFields && !isSnmpOrIcmp && ( + <> + {/* Scheme / Hostname / Port */} + {isTcp ? ( +
+ ( + + + {t( + "healthHostname" + )} + + + + handleChange( + "hcHostname", + e + .target + .value, + () => + field.onChange( + e + ) + ) + } + /> + + + + )} + /> + ( + + + {t( + "healthPort" + )} + + + + handleChange( + "hcPort", + e + .target + .value, + field.onChange + ) + } + /> + + + + )} + /> +
+ ) : ( +
+ ( + + + {t( + "healthScheme" + )} + + + + + )} + /> + ( + + + {t( + "healthHostname" + )} + + + + handleChange( + "hcHostname", + e + .target + .value, + () => + field.onChange( + e + ) + ) + } + /> + + + + )} + /> + ( + + + {t( + "healthPort" + )} + + + + handleChange( + "hcPort", + e + .target + .value, + field.onChange + ) + } + /> + + + + )} + /> +
+ )} + + {/* Method / Path / Timeout (HTTP) */} + {!isTcp && ( +
+ ( + + + {t( + "httpMethod" + )} + + + + + )} + /> + ( + + + {t( + "healthCheckPath" + )} + + + + handleChange( + "hcPath", + e + .target + .value, + () => + field.onChange( + e + ) + ) + } + /> + + + + )} + /> + ( + + + {t( + "timeoutSeconds" + )} + + + + handleChange( + "hcTimeout", + parseInt( + e + .target + .value + ), + field.onChange + ) + } + /> + + + + )} + /> +
+ )} + + {/* Timeout for TCP */} + {isTcp && ( + ( + + + {t( + "timeoutSeconds" + )} + + + + handleChange( + "hcTimeout", + parseInt( + e + .target + .value + ), + field.onChange + ) + } + /> + + + + )} + /> + )} + + )} +
+ + {/* ── Advanced tab ──────────────────────── */} +
+ {!showFields && ( +

+ {t("enableHealthChecks")} +

+ )} + + {/* Contact-sales banner for SNMP / ICMP */} + {showFields && isSnmpOrIcmp && ( + + )} + + {showFields && !isSnmpOrIcmp && ( + <> + {/* Healthy interval + threshold */} +
+ ( + + + {t( + "healthyIntervalSeconds" + )} + + + + handleChange( + "hcInterval", + parseInt( + e + .target + .value + ), + field.onChange + ) + } + /> + + + + )} + /> + ( + + + {t( + "healthyThreshold" + )} + + + + handleChange( + "hcHealthyThreshold", + parseInt( + e + .target + .value + ), + field.onChange + ) + } + /> + + + + )} + /> +
+ + {/* Unhealthy interval + threshold */} +
+ ( + + + {t( + "unhealthyIntervalSeconds" + )} + + + + handleChange( + "hcUnhealthyInterval", + parseInt( + e + .target + .value + ), + field.onChange + ) + } + /> + + + + )} + /> + ( + + + {t( + "unhealthyThreshold" + )} + + + + handleChange( + "hcUnhealthyThreshold", + parseInt( + e + .target + .value + ), + field.onChange + ) + } + /> + + + + )} + /> +
+ + {/* HTTP-only advanced fields */} + {!isTcp && ( + <> + {/* Expected status + TLS server name */} +
+ ( + + + {t( + "expectedResponseCodes" + )} + + + { + const val = + e + .target + .value; + const value = + val + ? parseInt( + val + ) + : null; + handleChange( + "hcStatus", + value, + field.onChange + ); + }} + /> + + + + )} + /> + ( + + + {t( + "tlsServerName" + )} + + + + handleChange( + "hcTlsServerName", + e + .target + .value, + () => + field.onChange( + e + ) + ) + } + /> + + + + )} + /> +
+ + {/* Follow redirects */} + ( + + + {t( + "followRedirects" + )} + + + + handleChange( + "hcFollowRedirects", + value, + field.onChange + ) + } + /> + + + )} + /> + + {/* Custom headers */} + ( + + + {t( + "customHeaders" + )} + + + + handleChange( + "hcHeaders", + value, + field.onChange + ) + } + rows={ + 4 + } + /> + + + {t( + "customHeadersDescription" + )} + + + + )} + /> + + )} + + )} +
+
+
+ + +
+ + {mode === "autoSave" ? ( + + ) : ( + <> + + + + + + )} + +
+
+ ); +} + +export default HealthCheckCredenza; diff --git a/src/components/HealthCheckDialog.tsx b/src/components/HealthCheckDialog.tsx deleted file mode 100644 index c95908025..000000000 --- a/src/components/HealthCheckDialog.tsx +++ /dev/null @@ -1,635 +0,0 @@ -"use client"; - -import { useEffect } from "react"; -import { Button } from "@/components/ui/button"; -import { Input } from "@/components/ui/input"; -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue -} from "@/components/ui/select"; -import { Switch } from "@/components/ui/switch"; -import { HeadersInput } from "@app/components/HeadersInput"; -import { z } from "zod"; -import { useForm } from "react-hook-form"; -import { zodResolver } from "@hookform/resolvers/zod"; -import { - Form, - FormControl, - FormDescription, - FormField, - FormItem, - FormLabel, - FormMessage -} from "@/components/ui/form"; -import { - Credenza, - CredenzaBody, - CredenzaClose, - CredenzaContent, - CredenzaDescription, - CredenzaFooter, - CredenzaHeader, - CredenzaTitle -} from "@/components/Credenza"; -import { toast } from "@/hooks/useToast"; -import { useTranslations } from "next-intl"; - -type HealthCheckConfig = { - hcEnabled: boolean; - hcPath: string; - hcMethod: string; - hcInterval: number; - hcTimeout: number; - hcStatus: number | null; - hcHeaders?: { name: string; value: string }[] | null; - hcScheme?: string; - hcHostname: string; - hcPort: number; - hcFollowRedirects: boolean; - hcMode: string; - hcUnhealthyInterval: number; - hcTlsServerName: string; -}; - -type HealthCheckDialogProps = { - open: boolean; - setOpen: (val: boolean) => void; - targetId: number; - targetAddress: string; - targetMethod?: string; - initialConfig?: Partial; - onChanges: (config: HealthCheckConfig) => Promise; -}; - -export default function HealthCheckDialog({ - open, - setOpen, - targetId, - targetAddress, - targetMethod, - initialConfig, - onChanges -}: HealthCheckDialogProps) { - const t = useTranslations(); - - const healthCheckSchema = z.object({ - hcEnabled: z.boolean(), - hcPath: z.string().min(1, { message: t("healthCheckPathRequired") }), - hcMethod: z - .string() - .min(1, { message: t("healthCheckMethodRequired") }), - hcInterval: z - .int() - .positive() - .min(5, { message: t("healthCheckIntervalMin") }), - hcTimeout: z - .int() - .positive() - .min(1, { message: t("healthCheckTimeoutMin") }), - hcStatus: z.int().positive().min(100).optional().nullable(), - hcHeaders: z - .array(z.object({ name: z.string(), value: z.string() })) - .nullable() - .optional(), - hcScheme: z.string().optional(), - hcHostname: z.string(), - hcPort: z - .string() - .min(1, { message: t("healthCheckPortInvalid") }) - .refine( - (val) => { - const port = parseInt(val); - return port > 0 && port <= 65535; - }, - { - message: t("healthCheckPortInvalid") - } - ), - hcFollowRedirects: z.boolean(), - hcMode: z.string(), - hcUnhealthyInterval: z.int().positive().min(5), - hcTlsServerName: z.string() - }); - - const form = useForm>({ - resolver: zodResolver(healthCheckSchema), - defaultValues: {} - }); - - useEffect(() => { - if (!open) return; - - // Determine default scheme from target method - const getDefaultScheme = () => { - if (initialConfig?.hcScheme) { - return initialConfig.hcScheme; - } - // Default to target method if it's http or https, otherwise default to http - if (targetMethod === "https") { - return "https"; - } - return "http"; - }; - - form.reset({ - hcEnabled: initialConfig?.hcEnabled, - hcPath: initialConfig?.hcPath, - hcMethod: initialConfig?.hcMethod, - hcInterval: initialConfig?.hcInterval, - hcTimeout: initialConfig?.hcTimeout, - hcStatus: initialConfig?.hcStatus, - hcHeaders: initialConfig?.hcHeaders, - hcScheme: getDefaultScheme(), - hcHostname: initialConfig?.hcHostname, - hcPort: initialConfig?.hcPort - ? initialConfig.hcPort.toString() - : "", - hcFollowRedirects: initialConfig?.hcFollowRedirects, - hcMode: initialConfig?.hcMode, - hcUnhealthyInterval: initialConfig?.hcUnhealthyInterval, - hcTlsServerName: initialConfig?.hcTlsServerName ?? "" - }); - }, [open]); - - const watchedEnabled = form.watch("hcEnabled"); - - const handleFieldChange = async (fieldName: string, value: any) => { - try { - const currentValues = form.getValues(); - const updatedValues = { ...currentValues, [fieldName]: value }; - - // Convert hcPort from string to number before passing to parent - const configToSend: HealthCheckConfig = { - ...updatedValues, - hcPort: parseInt(updatedValues.hcPort), - hcStatus: updatedValues.hcStatus || null - }; - - await onChanges(configToSend); - } catch (error) { - toast({ - title: t("healthCheckError"), - description: t("healthCheckErrorDescription"), - variant: "destructive" - }); - } - }; - - return ( - - - - {t("configureHealthCheck")} - - {t("configureHealthCheckDescription", { - target: targetAddress - })} - - - -
- - {/* Enable Health Checks */} - ( - -
- - {t("enableHealthChecks")} - - - {t( - "enableHealthChecksDescription" - )} - -
- - { - field.onChange(value); - handleFieldChange( - "hcEnabled", - value - ); - }} - /> - -
- )} - /> - - {watchedEnabled && ( -
-
- ( - - - {t("healthScheme")} - - - - - )} - /> - ( - - - {t("healthHostname")} - - - { - field.onChange( - e - ); - handleFieldChange( - "hcHostname", - e.target - .value - ); - }} - /> - - - - )} - /> - ( - - - {t("healthPort")} - - - { - const value = - e.target - .value; - field.onChange( - value - ); - handleFieldChange( - "hcPort", - value - ); - }} - /> - - - - )} - /> - ( - - - {t("healthCheckPath")} - - - { - field.onChange( - e - ); - handleFieldChange( - "hcPath", - e.target - .value - ); - }} - /> - - - - )} - /> -
- - {/* HTTP Method */} - ( - - - {t("httpMethod")} - - - - - )} - /> - - {/* Check Interval, Timeout, and Retry Attempts */} -
- ( - - - {t( - "healthyIntervalSeconds" - )} - - - { - const value = - parseInt( - e.target - .value - ); - field.onChange( - value - ); - handleFieldChange( - "hcInterval", - value - ); - }} - /> - - - - )} - /> - - ( - - - {t( - "unhealthyIntervalSeconds" - )} - - - { - const value = - parseInt( - e.target - .value - ); - field.onChange( - value - ); - handleFieldChange( - "hcUnhealthyInterval", - value - ); - }} - /> - - - - )} - /> - - ( - - - {t("timeoutSeconds")} - - - { - const value = - parseInt( - e.target - .value - ); - field.onChange( - value - ); - handleFieldChange( - "hcTimeout", - value - ); - }} - /> - - - - )} - /> -
- - {/* Expected Response Codes */} - ( - - - {t("expectedResponseCodes")} - - - { - const value = - parseInt( - e.target - .value - ); - field.onChange( - value - ); - handleFieldChange( - "hcStatus", - value - ); - }} - /> - - - {t( - "expectedResponseCodesDescription" - )} - - - - )} - /> - - {/*TLS Server Name (SNI)*/} - ( - - - {t("tlsServerName")} - - - { - field.onChange(e); - handleFieldChange( - "hcTlsServerName", - e.target.value - ); - }} - /> - - - {t( - "tlsServerNameDescription" - )} - - - - )} - /> - - {/* Custom Headers */} - ( - - - {t("customHeaders")} - - - { - field.onChange( - value - ); - handleFieldChange( - "hcHeaders", - value - ); - }} - rows={4} - /> - - - {t( - "customHeadersDescription" - )} - - - - )} - /> -
- )} - - -
- - - -
-
- ); -} diff --git a/src/components/HealthCheckFormFields.tsx b/src/components/HealthCheckFormFields.tsx new file mode 100644 index 000000000..6f5d528db --- /dev/null +++ b/src/components/HealthCheckFormFields.tsx @@ -0,0 +1,768 @@ +"use client"; + +import { UseFormReturn } from "react-hook-form"; +import { useTranslations } from "next-intl"; +import { Input } from "@/components/ui/input"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue +} from "@/components/ui/select"; +import { StrategySelect } from "@app/components/StrategySelect"; +import { Switch } from "@/components/ui/switch"; +import { HeadersInput } from "@app/components/HeadersInput"; +import { + FormControl, + FormDescription, + FormField, + FormItem, + FormLabel, + FormMessage +} from "@/components/ui/form"; +import { ExternalLink, KeyRound } from "lucide-react"; +import Link from "next/link"; + +type HealthCheckFormFieldsProps = { + form: UseFormReturn; + onFieldChange?: (fieldName: string, value: any) => void; + showNameField?: boolean; + hideEnabledField?: boolean; + watchedEnabled?: boolean; + watchedMode?: string; +}; + +export function HealthCheckFormFields({ + form, + onFieldChange, + showNameField, + hideEnabledField, + watchedEnabled, + watchedMode +}: HealthCheckFormFieldsProps) { + const t = useTranslations(); + + const showFields = hideEnabledField || watchedEnabled; + + const handleChange = ( + fieldName: string, + value: any, + fieldOnChange: (v: any) => void + ) => { + fieldOnChange(value); + if (onFieldChange) { + onFieldChange(fieldName, value); + } + }; + + return ( + <> + {/* Name */} + {showNameField && ( + ( + + {t("standaloneHcNameLabel")} + + + + + + )} + /> + )} + + {/* Enable Health Checks */} + {!hideEnabledField && ( + ( + +
+ {t("enableHealthChecks")} +
+ + + handleChange( + "hcEnabled", + value, + field.onChange + ) + } + /> + +
+ )} + /> + )} + + {showFields && ( +
+ {/* Strategy */} + ( + + + + handleChange( + "hcMode", + value, + field.onChange + ) + } + /> + + + + )} + /> + + {/* Inline contact-sales banner for SNMP / ICMP */} + {(watchedMode === "snmp" || watchedMode === "icmp") && ( +
+
+
+ + + Contact sales to enable this feature.{" "} + + Book a demo + + + {" or "} + + contact us + + + . + +
+
+
+ )} + + {/* Connection fields + all remaining config — hidden for SNMP / ICMP */} + {watchedMode !== "snmp" && watchedMode !== "icmp" && ( + <> + {/* Connection fields */} + {watchedMode === "tcp" ? ( +
+ ( + + + {t("healthHostname")} + + + + handleChange( + "hcHostname", + e.target.value, + (v) => + field.onChange( + e + ) + ) + } + /> + + + + )} + /> + ( + + + {t("healthPort")} + + + { + const value = + e.target.value; + handleChange( + "hcPort", + value, + field.onChange + ); + }} + /> + + + + )} + /> +
+ ) : ( +
+ ( + + + {t("healthScheme")} + + + + + )} + /> + ( + + + {t("healthHostname")} + + + + handleChange( + "hcHostname", + e.target.value, + (v) => + field.onChange( + e + ) + ) + } + /> + + + + )} + /> + ( + + + {t("healthPort")} + + + { + const value = + e.target.value; + handleChange( + "hcPort", + value, + field.onChange + ); + }} + /> + + + + )} + /> +
+ )} + + {/* HTTP Method + Path + Timeout (shown when not TCP) */} + {watchedMode !== "tcp" && ( +
+ ( + + + {t("httpMethod")} + + + + + )} + /> + ( + + + {t("healthCheckPath")} + + + + handleChange( + "hcPath", + e.target.value, + (v) => + field.onChange( + e + ) + ) + } + /> + + + + )} + /> + ( + + + {t("timeoutSeconds")} + + + { + const value = + parseInt( + e.target + .value + ); + handleChange( + "hcTimeout", + value, + field.onChange + ); + }} + /> + + + + )} + /> +
+ )} + + {/* TCP timeout (shown only for TCP) */} + {watchedMode === "tcp" && ( + ( + + + {t("timeoutSeconds")} + + + { + const value = parseInt( + e.target.value + ); + handleChange( + "hcTimeout", + value, + field.onChange + ); + }} + /> + + + + )} + /> + )} + + {/* Healthy interval + healthy threshold */} +
+ ( + + + {t("healthyIntervalSeconds")} + + + { + const value = parseInt( + e.target.value + ); + handleChange( + "hcInterval", + value, + field.onChange + ); + }} + /> + + + + )} + /> + ( + + + {t("healthyThreshold")} + + + { + const value = parseInt( + e.target.value + ); + handleChange( + "hcHealthyThreshold", + value, + field.onChange + ); + }} + /> + + + + )} + /> +
+ + {/* Unhealthy interval + unhealthy threshold */} +
+ ( + + + {t("unhealthyIntervalSeconds")} + + + { + const value = parseInt( + e.target.value + ); + handleChange( + "hcUnhealthyInterval", + value, + field.onChange + ); + }} + /> + + + + )} + /> + ( + + + {t("unhealthyThreshold")} + + + { + const value = parseInt( + e.target.value + ); + handleChange( + "hcUnhealthyThreshold", + value, + field.onChange + ); + }} + /> + + + + )} + /> +
+ + {/* HTTP-only fields */} + {watchedMode !== "tcp" && ( + <> + {/* Expected Response Codes + TLS Server Name */} +
+ ( + + + {t( + "expectedResponseCodes" + )} + + + { + const val = + e.target + .value; + const value = + val + ? parseInt( + val + ) + : null; + handleChange( + "hcStatus", + value, + field.onChange + ); + }} + /> + + + + )} + /> + ( + + + {t("tlsServerName")} + + + + handleChange( + "hcTlsServerName", + e.target + .value, + (v) => + field.onChange( + e + ) + ) + } + /> + + + + )} + /> +
+ + {/* Follow Redirects inline toggle */} + ( + + + {t("followRedirects")} + + + + handleChange( + "hcFollowRedirects", + value, + field.onChange + ) + } + /> + + + )} + /> + + {/* Custom Headers */} + ( + + + {t("customHeaders")} + + + + handleChange( + "hcHeaders", + value, + field.onChange + ) + } + rows={4} + /> + + + {t( + "customHeadersDescription" + )} + + + + )} + /> + + )} + + )} +
+ )} + + ); +} diff --git a/src/components/HealthChecksTable.tsx b/src/components/HealthChecksTable.tsx new file mode 100644 index 000000000..404ade547 --- /dev/null +++ b/src/components/HealthChecksTable.tsx @@ -0,0 +1,710 @@ +"use client"; + +import UptimeMiniBar from "@app/components/UptimeMiniBar"; + +import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog"; +import HealthCheckCredenza, { + HealthCheckRow +} from "@app/components/HealthCheckCredenza"; +import { ColumnFilterButton } from "@app/components/ColumnFilterButton"; +import { Badge } from "@app/components/ui/badge"; +import { Button } from "@app/components/ui/button"; +import { + ControlledDataTable, + type ExtendedColumnDef +} from "@app/components/ui/controlled-data-table"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger +} from "@app/components/ui/dropdown-menu"; +import { + Popover, + PopoverContent, + PopoverTrigger +} from "@app/components/ui/popover"; +import { Switch } from "@app/components/ui/switch"; +import { toast } from "@app/hooks/useToast"; +import { useEnvContext } from "@app/hooks/useEnvContext"; +import { createApiClient, formatAxiosError } from "@app/lib/api"; +import { Selectedsite, SitesSelector } from "@app/components/site-selector"; +import { + ResourceSelector, + SelectedResource +} from "@app/components/resource-selector"; +import { + ArrowUpDown, + ArrowUpRight, + Funnel, + MoreHorizontal +} from "lucide-react"; +import { useTranslations } from "next-intl"; +import { useState, useTransition, useEffect, useMemo } from "react"; +import type { PaginationState } from "@tanstack/react-table"; +import { useNavigationContext } from "@app/hooks/useNavigationContext"; +import { useDebouncedCallback } from "use-debounce"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert"; +import { usePaidStatus } from "@app/hooks/usePaidStatus"; +import { tierMatrix } from "@server/lib/billing/tierMatrix"; +import { cn } from "@app/lib/cn"; + +type StandaloneHealthChecksTableProps = { + orgId: string; + healthChecks: HealthCheckRow[]; + rowCount: number; + pagination: PaginationState; + initialFilterSite?: Selectedsite | null; + initialFilterResource?: SelectedResource | null; +}; + +function formatTarget(row: HealthCheckRow): string { + if (!row.hcHostname) return "-"; + if (row.hcMode === "tcp") { + if (!row.hcPort) return row.hcHostname; + return `${row.hcHostname}:${row.hcPort}`; + } + if (row.hcMode === "snmp" || row.hcMode === "ping") { + if (row.hcPort) { + return `${row.hcHostname}:${row.hcPort}`; + } + return row.hcHostname; + } + // HTTP / default + const scheme = row.hcScheme ?? "http"; + const host = row.hcHostname; + const port = row.hcPort ? `:${row.hcPort}` : ""; + const path = row.hcPath ?? "/"; + return `${scheme}://${host}${port}${path}`; +} + +export default function HealthChecksTable({ + orgId, + healthChecks, + rowCount, + pagination, + initialFilterSite = null, + initialFilterResource = null +}: StandaloneHealthChecksTableProps) { + const router = useRouter(); + const t = useTranslations(); + const api = createApiClient(useEnvContext()); + const [isRefreshing, startRefresh] = useTransition(); + const { isPaidUser } = usePaidStatus(); + const isPaid = isPaidUser(tierMatrix.standaloneHealthChecks); + + const [credenzaOpen, setCredenzaOpen] = useState(false); + const { + navigate: filter, + isNavigating: isFiltering, + searchParams + } = useNavigationContext(); + + const [deleteOpen, setDeleteOpen] = useState(false); + const [selected, setSelected] = useState(null); + const [togglingId, setTogglingId] = useState(null); + const [siteFilterOpen, setSiteFilterOpen] = useState(false); + const [resourceFilterOpen, setResourceFilterOpen] = useState(false); + + const pageSize = pagination.pageSize; + const query = searchParams.get("query") ?? undefined; + + const siteIdQ = searchParams.get("siteId"); + const siteIdNum = siteIdQ ? parseInt(siteIdQ, 10) : NaN; + const selectedSite: Selectedsite | null = useMemo(() => { + if (!siteIdQ || !Number.isInteger(siteIdNum) || siteIdNum <= 0) { + return null; + } + if (initialFilterSite && initialFilterSite.siteId === siteIdNum) { + return initialFilterSite; + } + return { + siteId: siteIdNum, + name: t("standaloneHcFilterSiteIdFallback", { id: siteIdNum }), + type: "newt" + }; + }, [initialFilterSite, siteIdQ, siteIdNum, t]); + + const resourceIdQ = searchParams.get("resourceId"); + const resourceIdNum = resourceIdQ ? parseInt(resourceIdQ, 10) : NaN; + const selectedResource: SelectedResource | null = useMemo(() => { + if ( + !resourceIdQ || + !Number.isInteger(resourceIdNum) || + resourceIdNum <= 0 + ) { + return null; + } + if ( + initialFilterResource && + initialFilterResource.resourceId === resourceIdNum + ) { + return initialFilterResource; + } + return { + name: t("standaloneHcFilterResourceIdFallback", { + id: resourceIdNum + }), + resourceId: resourceIdNum, + fullDomain: null, + niceId: "", + ssl: false + }; + }, [initialFilterResource, resourceIdQ, resourceIdNum, t]); + + const rows = healthChecks; + + function refreshList() { + startRefresh(() => { + router.refresh(); + }); + } + + useEffect(() => { + const interval = setInterval(() => { + router.refresh(); + }, 10_000); + return () => clearInterval(interval); + }, [router]); + + const handlePaginationChange = (newState: PaginationState) => { + searchParams.set("page", (newState.pageIndex + 1).toString()); + searchParams.set("pageSize", newState.pageSize.toString()); + filter({ searchParams }); + }; + + const handleSearchChange = useDebouncedCallback((value: string) => { + if (value) { + searchParams.set("query", value); + } else { + searchParams.delete("query"); + } + searchParams.delete("page"); + filter({ searchParams }); + }, 300); + + function handleFilterChange( + column: string, + value: string | undefined | null + ) { + const sp = new URLSearchParams(searchParams); + sp.delete(column); + sp.delete("page"); + if (value) { + sp.set(column, value); + } + filter({ searchParams: sp }); + } + + const clearSiteFilter = () => { + handleFilterChange("siteId", undefined); + setSiteFilterOpen(false); + }; + + const clearResourceFilter = () => { + handleFilterChange("resourceId", undefined); + setResourceFilterOpen(false); + }; + + const onPickSite = (site: Selectedsite) => { + handleFilterChange("siteId", String(site.siteId)); + setSiteFilterOpen(false); + }; + + const onPickResource = (resource: SelectedResource) => { + handleFilterChange("resourceId", String(resource.resourceId)); + setResourceFilterOpen(false); + }; + + const handleToggleEnabled = async ( + row: HealthCheckRow, + enabled: boolean + ) => { + setTogglingId(row.targetHealthCheckId); + try { + await api.post( + `/org/${orgId}/health-check/${row.targetHealthCheckId}`, + { hcEnabled: enabled } + ); + refreshList(); + } catch (e) { + toast({ + title: t("error"), + description: formatAxiosError(e), + variant: "destructive" + }); + } finally { + setTogglingId(null); + } + }; + + const handleDelete = async () => { + if (!selected) return; + try { + await api.delete( + `/org/${orgId}/health-check/${selected.targetHealthCheckId}` + ); + refreshList(); + toast({ title: t("standaloneHcDeleted") }); + } catch (e) { + toast({ + title: t("error"), + description: formatAxiosError(e), + variant: "destructive" + }); + } finally { + setDeleteOpen(false); + setSelected(null); + } + }; + + const modeParam = searchParams.get("hcMode"); + const selectedHcMode = + modeParam === "http" || + modeParam === "tcp" || + modeParam === "snmp" || + modeParam === "ping" + ? modeParam + : undefined; + const healthParam = searchParams.get("hcHealth"); + const selectedHcHealth = + healthParam === "healthy" || + healthParam === "unhealthy" || + healthParam === "unknown" + ? healthParam + : undefined; + const enabledParam = searchParams.get("hcEnabled"); + const selectedHcEnabled = + enabledParam === "true" || enabledParam === "false" + ? enabledParam + : undefined; + + const columns: ExtendedColumnDef[] = [ + { + accessorKey: "name", + enableHiding: false, + friendlyName: t("name"), + header: ({ column }) => ( + + ), + cell: ({ row }) => ( + {row.original.name ? row.original.name : "-"} + ) + }, + { + id: "mode", + friendlyName: t("standaloneHcColumnMode"), + header: () => ( + + handleFilterChange("hcMode", value) + } + searchPlaceholder={t("searchPlaceholder")} + emptyMessage={t("emptySearchOptions")} + label={t("standaloneHcColumnMode")} + className="p-3" + /> + ), + cell: ({ row }) => ( + {row.original.hcMode?.toUpperCase() ?? "-"} + ) + }, + { + id: "target", + friendlyName: t("standaloneHcColumnTarget"), + header: () => ( + {t("standaloneHcColumnTarget")} + ), + cell: ({ row }) => {formatTarget(row.original)} + }, + { + id: "resource", + friendlyName: t("resource"), + header: () => ( + + + + + +
+ +
+ +
+
+ ), + cell: ({ row }) => { + const r = row.original; + if (!r.resourceId || !r.resourceName || !r.resourceNiceId) { + return -; + } + return ( + + + + ); + } + }, + { + id: "site", + friendlyName: t("site"), + header: () => ( + + + + + +
+ +
+ +
+
+ ), + cell: ({ row }) => { + const r = row.original; + if (!r.siteId || !r.siteName || !r.siteNiceId) { + return -; + } + return ( + + + + ); + } + }, + { + id: "health", + friendlyName: t("standaloneHcColumnHealth"), + header: () => ( + + handleFilterChange("hcHealth", value) + } + searchPlaceholder={t("searchPlaceholder")} + emptyMessage={t("emptySearchOptions")} + label={t("standaloneHcColumnHealth")} + className="p-3" + /> + ), + cell: ({ row }) => { + const health = row.original.hcHealth; + if (health === "healthy") { + return ( + +
+ {t("standaloneHcHealthStateHealthy")} + + ); + } else if (health === "unhealthy") { + return ( + +
+ {t("standaloneHcHealthStateUnhealthy")} + + ); + } else { + return ( + +
+ {t("standaloneHcHealthStateUnknown")} + + ); + } + } + }, + { + id: "uptime", + friendlyName: t("uptime30d"), + header: () => {t("uptime30d")}, + cell: ({ row }) => { + return ( + + ); + } + }, + { + accessorKey: "hcEnabled", + friendlyName: t("alertingColumnEnabled"), + header: () => ( + + handleFilterChange("hcEnabled", value) + } + searchPlaceholder={t("searchPlaceholder")} + emptyMessage={t("emptySearchOptions")} + label={t("alertingColumnEnabled")} + className="p-3" + /> + ), + cell: ({ row }) => { + const r = row.original; + return ( + handleToggleEnabled(r, v)} + /> + ); + } + }, + { + id: "rowActions", + enableHiding: false, + header: () => , + cell: ({ row }) => { + const r = row.original; + return ( +
+ + + + + + { + setSelected(r); + setDeleteOpen(true); + }} + > + + {t("delete")} + + + + + {r.resourceId && r.resourceName && r.resourceNiceId ? ( + + + + ) : ( + + )} +
+ ); + } + } + ]; + + return ( + <> + {selected && deleteOpen && ( + { + setDeleteOpen(val); + if (!val) setSelected(null); + }} + dialog={ +
+

{t("standaloneHcDeleteQuestion")}

+
+ } + buttonText={t("delete")} + onConfirm={handleDelete} + string={selected.name} + title={t("standaloneHcDeleteTitle")} + /> + )} + + { + setCredenzaOpen(val); + if (!val) setSelected(null); + }} + orgId={orgId} + initialValues={selected} + onSaved={refreshList} + /> + + + + { + setSelected(null); + setCredenzaOpen(true); + }} + addButtonDisabled={!isPaid} + onRefresh={refreshList} + isRefreshing={isRefreshing || isFiltering} + addButtonText={t("standaloneHcAddButton")} + enableColumnVisibility + stickyLeftColumn="name" + stickyRightColumn="rowActions" + pagination={pagination} + onPaginationChange={handlePaginationChange} + rowCount={rowCount} + /> + + ); +} diff --git a/src/components/HorizontalTabs.tsx b/src/components/HorizontalTabs.tsx index 717a3c120..bffaadeba 100644 --- a/src/components/HorizontalTabs.tsx +++ b/src/components/HorizontalTabs.tsx @@ -11,6 +11,8 @@ import { useTranslations } from "next-intl"; export type TabItem = { title: string; href: string; + /** When set, active tab detection uses this path instead of `href` (link target unchanged). */ + activePrefix?: string; icon?: React.ReactNode; showProfessional?: boolean; exact?: boolean; @@ -115,18 +117,33 @@ export function HorizontalTabs({ } // Server-side mode: original behavior with routing + const activeIndex: number | null = (() => { + if (pathname.includes("create")) return null; + let best: number | null = null; + let bestLen = -1; + for (let i = 0; i < items.length; i++) { + const item = items[i]; + const matchBase = hydrateHref(item.activePrefix ?? item.href); + const matched = item.exact + ? pathname === matchBase + : pathname === matchBase || + pathname.startsWith(`${matchBase}/`); + if (matched && matchBase.length > bestLen) { + bestLen = matchBase.length; + best = i; + } + } + return best; + })(); + return (
- {items.map((item) => { + {items.map((item, index) => { const hydratedHref = hydrateHref(item.href); - const isActive = - (item.exact - ? pathname === hydratedHref - : pathname.startsWith(hydratedHref)) && - !pathname.includes("create"); + const isActive = activeIndex === index; const isProfessional = item.showProfessional && !isUnlocked(); @@ -135,7 +152,7 @@ export function HorizontalTabs({ return ( // --- Types --- -type Site = ListSitesResponse["sites"][0]; +export type InternalResourceMode = "host" | "cidr" | "http"; export type InternalResourceData = { id: number; name: string; orgId: string; - siteName: string; - mode: "host" | "cidr"; - siteId: number; + siteNames: string[]; + mode: InternalResourceMode; + siteIds: number[]; niceId: string; destination: string; alias?: string | null; @@ -135,14 +144,30 @@ export type InternalResourceData = { disableIcmp?: boolean; authDaemonMode?: "site" | "remote" | null; authDaemonPort?: number | null; + httpHttpsPort?: number | null; + scheme?: "http" | "https" | null; + ssl?: boolean; + subdomain?: string | null; + domainId?: string | null; + fullDomain?: string | null; }; const tagSchema = z.object({ id: z.string(), text: z.string() }); +function buildSelectedSitesForResource( + resource: InternalResourceData, +): Selectedsite[] { + return resource.siteIds.map((siteId, idx) => ({ + name: resource.siteNames[idx] ?? "", + siteId, + type: "newt" as const + })); +} + export type InternalResourceFormValues = { name: string; - siteId: number; - mode: "host" | "cidr"; + siteIds: number[]; + mode: InternalResourceMode; destination: string; alias?: string | null; niceId?: string; @@ -151,6 +176,12 @@ export type InternalResourceFormValues = { disableIcmp?: boolean; authDaemonMode?: "site" | "remote" | null; authDaemonPort?: number | null; + httpHttpsPort?: number | null; + scheme?: "http" | "https"; + ssl?: boolean; + httpConfigSubdomain?: string | null; + httpConfigDomainId?: string | null; + httpConfigFullDomain?: string | null; roles?: z.infer[]; users?: z.infer[]; clients?: z.infer[]; @@ -160,28 +191,29 @@ type InternalResourceFormProps = { variant: "create" | "edit"; resource?: InternalResourceData; open?: boolean; - sites: Site[]; orgId: string; siteResourceId?: number; formId: string; onSubmit: (values: InternalResourceFormValues) => void | Promise; + onSubmitDisabledChange?: (disabled: boolean) => void; }; export function InternalResourceForm({ variant, resource, open, - sites, orgId, siteResourceId, formId, - onSubmit + onSubmit, + onSubmitDisabledChange }: InternalResourceFormProps) { const t = useTranslations(); const { env } = useEnvContext(); const { isPaidUser } = usePaidStatus(); const disableEnterpriseFeatures = env.flags.disableEnterpriseFeatures; const sshSectionDisabled = !isPaidUser(tierMatrix.sshPam); + const httpSectionDisabled = !isPaidUser(tierMatrix.httpPrivateResources); const nameRequiredKey = variant === "create" @@ -211,6 +243,22 @@ export function InternalResourceForm({ variant === "create" ? "createInternalResourceDialogModeCidr" : "editInternalResourceDialogModeCidr"; + const modeHttpKey = + variant === "create" + ? "createInternalResourceDialogModeHttp" + : "editInternalResourceDialogModeHttp"; + const schemeLabelKey = + variant === "create" + ? "createInternalResourceDialogScheme" + : "editInternalResourceDialogScheme"; + const enableSslLabelKey = + variant === "create" + ? "createInternalResourceDialogEnableSsl" + : "editInternalResourceDialogEnableSsl"; + const enableSslDescriptionKey = + variant === "create" + ? "createInternalResourceDialogEnableSslDescription" + : "editInternalResourceDialogEnableSslDescription"; const destinationLabelKey = variant === "create" ? "createInternalResourceDialogDestination" @@ -223,50 +271,95 @@ export function InternalResourceForm({ variant === "create" ? "createInternalResourceDialogAlias" : "editInternalResourceDialogAlias"; + const httpHttpsPortLabelKey = + variant === "create" + ? "createInternalResourceDialogModePort" + : "editInternalResourceDialogModePort"; + const httpConfigurationTitleKey = + variant === "create" + ? "createInternalResourceDialogHttpConfiguration" + : "editInternalResourceDialogHttpConfiguration"; + const httpConfigurationDescriptionKey = + variant === "create" + ? "createInternalResourceDialogHttpConfigurationDescription" + : "editInternalResourceDialogHttpConfigurationDescription"; - const formSchema = z.object({ - name: z.string().min(1, t(nameRequiredKey)).max(255, t(nameMaxKey)), - siteId: z - .number() - .int() - .positive(siteRequiredKey ? t(siteRequiredKey) : undefined), - mode: z.enum(["host", "cidr"]), - destination: z - .string() - .min( - 1, - destinationRequiredKey - ? { message: t(destinationRequiredKey) } - : undefined - ), - alias: z.string().nullish(), - niceId: z - .string() - .min(1) - .max(255) - .regex(/^[a-zA-Z0-9-]+$/) - .optional(), - tcpPortRangeString: createPortRangeStringSchema(t), - udpPortRangeString: createPortRangeStringSchema(t), - disableIcmp: z.boolean().optional(), - authDaemonMode: z.enum(["site", "remote"]).optional().nullable(), - authDaemonPort: z.number().int().positive().optional().nullable(), - roles: z.array(tagSchema).optional(), - users: z.array(tagSchema).optional(), - clients: z - .array( - z.object({ - clientId: z.number(), - name: z.string() - }) - ) - .optional() - }); + const siteIdsSchema = siteRequiredKey + ? z.array(z.number().int().positive()).min(1, t(siteRequiredKey)) + : z.array(z.number().int().positive()).min(1); + + const formSchema = z + .object({ + name: z.string().min(1, t(nameRequiredKey)).max(255, t(nameMaxKey)), + siteIds: siteIdsSchema, + mode: z.enum(["host", "cidr", "http"]), + destination: z + .string() + .min( + 1, + destinationRequiredKey + ? { message: t(destinationRequiredKey) } + : undefined + ), + alias: z.string().nullish(), + httpHttpsPort: z + .number() + .int() + .min(1) + .max(65535) + .optional() + .nullable(), + scheme: z.enum(["http", "https"]).optional(), + ssl: z.boolean().optional(), + httpConfigSubdomain: z.string().nullish(), + httpConfigDomainId: z.string().nullish(), + httpConfigFullDomain: z.string().nullish(), + niceId: z + .string() + .min(1) + .max(255) + .regex(/^[a-zA-Z0-9-]+$/) + .optional(), + tcpPortRangeString: createPortRangeStringSchema(t), + udpPortRangeString: createPortRangeStringSchema(t), + disableIcmp: z.boolean().optional(), + authDaemonMode: z.enum(["site", "remote"]).optional().nullable(), + authDaemonPort: z.number().int().positive().optional().nullable(), + roles: z.array(tagSchema).optional(), + users: z.array(tagSchema).optional(), + clients: z + .array( + z.object({ + clientId: z.number(), + name: z.string() + }) + ) + .optional() + }) + .superRefine((data, ctx) => { + if (data.mode !== "http") return; + if (!data.scheme) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t("internalResourceDownstreamSchemeRequired"), + path: ["scheme"] + }); + } + if ( + data.httpHttpsPort == null || + !Number.isFinite(data.httpHttpsPort) || + data.httpHttpsPort < 1 + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t("internalResourceHttpPortRequired"), + path: ["httpHttpsPort"] + }); + } + }); type FormData = z.infer; - const availableSites = sites.filter((s) => s.type === "newt"); - const rolesQuery = useQuery(orgQueries.roles({ orgId })); const usersQuery = useQuery(orgQueries.users({ orgId })); const clientsQuery = useQuery(orgQueries.machineClients({ orgId })); @@ -385,7 +478,7 @@ export function InternalResourceForm({ variant === "edit" && resource ? { name: resource.name, - siteId: resource.siteId, + siteIds: resource.siteIds, mode: resource.mode ?? "host", destination: resource.destination ?? "", alias: resource.alias ?? null, @@ -394,6 +487,12 @@ export function InternalResourceForm({ disableIcmp: resource.disableIcmp ?? false, authDaemonMode: resource.authDaemonMode ?? "site", authDaemonPort: resource.authDaemonPort ?? null, + httpHttpsPort: resource.httpHttpsPort ?? null, + scheme: resource.scheme ?? "http", + ssl: resource.ssl ?? false, + httpConfigSubdomain: resource.subdomain ?? null, + httpConfigDomainId: resource.domainId ?? null, + httpConfigFullDomain: resource.fullDomain ?? null, niceId: resource.niceId, roles: [], users: [], @@ -401,10 +500,16 @@ export function InternalResourceForm({ } : { name: "", - siteId: availableSites[0]?.siteId ?? 0, + siteIds: [], mode: "host", destination: "", alias: null, + httpHttpsPort: null, + scheme: "http", + ssl: true, + httpConfigSubdomain: null, + httpConfigDomainId: null, + httpConfigFullDomain: null, tcpPortRangeString: "*", udpPortRangeString: "*", disableIcmp: false, @@ -415,8 +520,10 @@ export function InternalResourceForm({ clients: [] }; - const [selectedSite, setSelectedSite] = useState( - availableSites[0] + const [selectedSites, setSelectedSites] = useState(() => + variant === "edit" && resource + ? buildSelectedSitesForResource(resource) + : [] ); const form = useForm({ @@ -425,6 +532,10 @@ export function InternalResourceForm({ }); const mode = form.watch("mode"); + const httpConfigSubdomain = form.watch("httpConfigSubdomain"); + const httpConfigDomainId = form.watch("httpConfigDomainId"); + const httpConfigFullDomain = form.watch("httpConfigFullDomain"); + const isHttpMode = mode === "http"; const authDaemonMode = form.watch("authDaemonMode") ?? "site"; const hasInitialized = useRef(false); const previousResourceId = useRef(null); @@ -444,10 +555,16 @@ export function InternalResourceForm({ if (variant === "create" && open) { form.reset({ name: "", - siteId: availableSites[0]?.siteId ?? 0, + siteIds: [], mode: "host", destination: "", alias: null, + httpHttpsPort: null, + scheme: "http", + ssl: true, + httpConfigSubdomain: null, + httpConfigDomainId: null, + httpConfigFullDomain: null, tcpPortRangeString: "*", udpPortRangeString: "*", disableIcmp: false, @@ -457,12 +574,13 @@ export function InternalResourceForm({ users: [], clients: [] }); + setSelectedSites([]); setTcpPortMode("all"); setUdpPortMode("all"); setTcpCustomPorts(""); setUdpCustomPorts(""); } - }, [variant, open]); + }, [variant, open, form]); // Reset when edit dialog opens / resource changes useEffect(() => { @@ -471,10 +589,16 @@ export function InternalResourceForm({ if (resourceChanged) { form.reset({ name: resource.name, - siteId: resource.siteId, + siteIds: resource.siteIds, mode: resource.mode ?? "host", destination: resource.destination ?? "", alias: resource.alias ?? null, + httpHttpsPort: resource.httpHttpsPort ?? null, + scheme: resource.scheme ?? "http", + ssl: resource.ssl ?? false, + httpConfigSubdomain: resource.subdomain ?? null, + httpConfigDomainId: resource.domainId ?? null, + httpConfigFullDomain: resource.fullDomain ?? null, tcpPortRangeString: resource.tcpPortRangeString ?? "*", udpPortRangeString: resource.udpPortRangeString ?? "*", disableIcmp: resource.disableIcmp ?? false, @@ -484,6 +608,9 @@ export function InternalResourceForm({ users: [], clients: [] }); + setSelectedSites( + buildSelectedSitesForResource(resource) + ); setTcpPortMode( getPortModeFromString(resource.tcpPortRangeString) ); @@ -537,12 +664,18 @@ export function InternalResourceForm({ form ]); + useEffect(() => { + onSubmitDisabledChange?.(isHttpMode && httpSectionDisabled); + }, [isHttpMode, httpSectionDisabled, onSubmitDisabledChange]); + return (
{ + const siteIds = values.siteIds; onSubmit({ ...values, + siteIds, clients: (values.clients ?? []).map((c) => ({ id: c.clientId.toString(), text: c.name @@ -581,51 +714,6 @@ export function InternalResourceForm({ )} /> )} - ( - - {t("site")} - - - - - - - - { - setSelectedSite(site); - field.onChange(site.siteId); - }} - /> - - - - - )} - />
-
-
+
+
( - + - {t(modeLabelKey)} + {t("sites")} - + + + + + + + + { + setSelectedSites( + sites + ); + field.onChange( + sites.map( + (s) => + s.siteId + ) + ); + }} + /> + + )} />
+
+ { + const modeOptions: OptionSelectOption[] = + [ + { + value: "host", + label: t(modeHostKey) + }, + { + value: "cidr", + label: t(modeCidrKey) + }, + { + value: "http", + label: t(modeHttpKey) + } + ]; + return ( + + + {t(modeLabelKey)} + + + options={modeOptions} + value={field.value} + onChange={ + field.onChange + } + cols={3} + /> + + + ); + }} + /> +
+
+
+ {mode === "http" && ( +
+ ( + + + {t(schemeLabelKey)} + + + + + )} + /> +
+ )}
- + )} />
- {mode !== "cidr" && ( -
+ {mode === "host" && ( +
)} + {mode === "http" && ( +
+ ( + + + {t( + httpHttpsPortLabelKey + )} + + + { + const raw = + e.target + .value; + if ( + raw === "" + ) { + field.onChange( + null + ); + return; + } + const n = + Number(raw); + field.onChange( + Number.isFinite( + n + ) + ? n + : null + ); + }} + /> + + + + )} + /> +
+ )}
-
-
- -
- {t( - "editInternalResourceDialogPortRestrictionsDescription" + {isHttpMode && ( + + )} + + {isHttpMode ? ( +
+
+ +
+ {t(httpConfigurationDescriptionKey)} +
+
+
+ { + if (res === null) { + form.setValue( + "httpConfigSubdomain", + null + ); + form.setValue( + "httpConfigDomainId", + null + ); + form.setValue( + "httpConfigFullDomain", + null + ); + return; + } + form.setValue( + "httpConfigSubdomain", + res.subdomain ?? null + ); + form.setValue( + "httpConfigDomainId", + res.domainId + ); + form.setValue( + "httpConfigFullDomain", + res.fullDomain + ); + }} + /> +
+ ( + + + + + )} -
+ />
-
-
- - {t("editInternalResourceDialogTcp")} - -
-
- ( - -
- - {tcpPortMode === - "custom" ? ( - - - setTcpCustomPorts( - e.target - .value - ) - } - /> - - ) : ( - - )} -
- -
+ ) : ( +
+
+ +
+ {t( + "editInternalResourceDialogPortRestrictionsDescription" )} - /> -
-
-
-
- - {t("editInternalResourceDialogUdp")} - +
- ( - -
- - {udpPortMode === - "custom" ? ( - - - setUdpCustomPorts( - e.target - .value - ) - } - /> - - ) : ( - - )} -
- -
- )} - /> -
-
-
-
- - {t("editInternalResourceDialogIcmp")} - -
-
- ( - -
- - + + {t("editInternalResourceDialogTcp")} + +
+
+ ( + +
+ + {tcpPortMode === + "custom" ? ( + + + setTcpCustomPorts( + e + .target + .value + ) + } + /> + + ) : ( + + )} +
+ +
+ )} + /> +
+
+
+
+ + {t("editInternalResourceDialogUdp")} + +
+
+ ( + +
+ + {udpPortMode === + "custom" ? ( + + + setUdpCustomPorts( + e + .target + .value + ) + } + /> + + ) : ( + + )} +
+ +
+ )} + /> +
+
+
+
+ + {t( + "editInternalResourceDialogIcmp" + )} + +
+
+ ( + +
+ + + field.onChange( + !checked + ) + } + /> + + + {field.value + ? t("blocked") + : t("allowed")} + +
+ +
+ )} + /> +
-
+ )}
@@ -1066,7 +1432,7 @@ export function InternalResourceForm({ ] ) } - enableAutocomplete={true} + enableAutocomplete autocompleteOptions={ allRoles } @@ -1176,7 +1542,7 @@ export function InternalResourceForm({ ) )} - + {t( "accessClientSelect" )} @@ -1213,8 +1579,8 @@ export function InternalResourceForm({ )}
- {/* SSH Access tab */} - {!disableEnterpriseFeatures && mode !== "cidr" && ( + {/* SSH Access tab (host mode only) */} + {!disableEnterpriseFeatures && mode === "host" && (
diff --git a/src/components/LayoutHeader.tsx b/src/components/LayoutHeader.tsx index bef016853..29850f115 100644 --- a/src/components/LayoutHeader.tsx +++ b/src/components/LayoutHeader.tsx @@ -49,7 +49,7 @@ export function LayoutHeader({ showTopBar }: LayoutHeaderProps) { return (
-
+
diff --git a/src/components/LayoutMobileMenu.tsx b/src/components/LayoutMobileMenu.tsx index 854cad6db..13efdd564 100644 --- a/src/components/LayoutMobileMenu.tsx +++ b/src/components/LayoutMobileMenu.tsx @@ -101,7 +101,6 @@ export function LayoutMobileMenu({ "serverAdmin" )} -
)} diff --git a/src/components/LayoutSidebar.tsx b/src/components/LayoutSidebar.tsx index 27d8c2cd8..19a095419 100644 --- a/src/components/LayoutSidebar.tsx +++ b/src/components/LayoutSidebar.tsx @@ -13,6 +13,7 @@ import { import { useEnvContext } from "@app/hooks/useEnvContext"; import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext"; import { useUserContext } from "@app/hooks/useUserContext"; +import { useSubscriptionStatusContext } from "@app/hooks/useSubscriptionStatusContext"; import { cn } from "@app/lib/cn"; import { approvalQueries } from "@app/lib/queries"; import { build } from "@server/build"; @@ -31,6 +32,10 @@ const ProductUpdates = dynamic(() => import("./ProductUpdates"), { ssr: false }); +const ShowTrialCard = dynamic(() => import("./ShowTrialCard"), { + ssr: false +}); + interface LayoutSidebarProps { orgId?: string; orgs?: ListUserOrgsResponse["orgs"]; @@ -55,6 +60,7 @@ export function LayoutSidebar({ const { user } = useUserContext(); const { isUnlocked, licenseStatus } = useLicenseStatusContext(); const { env } = useEnvContext(); + const subscriptionContext = useSubscriptionStatusContext(); const t = useTranslations(); // Fetch pending approval count if we have an orgId and it's not an admin page @@ -122,10 +128,15 @@ export function LayoutSidebar({ const canShowProductUpdates = user.serverAdmin || Boolean(currentOrg?.isOwner || currentOrg?.isAdmin); + const showTrial = + build === "saas" && + Boolean(orgId) && + subscriptionContext?.isTrial + return (
@@ -154,7 +165,7 @@ export function LayoutSidebar({ {t("serverAdmin")} - )} @@ -191,7 +201,7 @@ export function LayoutSidebar({ />
{/* Fade gradient at bottom to indicate scrollable content */} -
+
{isSidebarCollapsed && ( @@ -206,7 +216,7 @@ export function LayoutSidebar({ setHasManualToggle(true); setSidebarStateCookie(false); }} - className="rounded-md p-2 text-muted-foreground hover:text-foreground hover:bg-secondary/80 dark:hover:bg-secondary/50 transition-colors" + className="rounded-md p-2 text-muted-foreground hover:text-foreground hover:bg-sidebar-accent/80 dark:hover:bg-sidebar-accent/50 transition-colors" aria-label={t("sidebarExpand")} > @@ -220,13 +230,24 @@ export function LayoutSidebar({
)} -
+
{canShowProductUpdates ? (
) :
} + {showTrial && ( +
+ +
+ )} + {build === "enterprise" && (
)} + {!isSidebarCollapsed && (
{loadFooterLinks() ? ( diff --git a/src/components/LicenseKeysDataTable.tsx b/src/components/LicenseKeysDataTable.tsx index 1e39c9225..a3e6f3ce5 100644 --- a/src/components/LicenseKeysDataTable.tsx +++ b/src/components/LicenseKeysDataTable.tsx @@ -1,6 +1,5 @@ "use client"; -import { ColumnDef } from "@tanstack/react-table"; import { ExtendedColumnDef } from "@app/components/ui/data-table"; import { DataTable } from "@app/components/ui/data-table"; import { Button } from "@app/components/ui/button"; diff --git a/src/components/LocaleSwitcherSelect.tsx b/src/components/LocaleSwitcherSelect.tsx index e647f7dd1..b6f65aa7c 100644 --- a/src/components/LocaleSwitcherSelect.tsx +++ b/src/components/LocaleSwitcherSelect.tsx @@ -36,7 +36,7 @@ export default function LocaleSwitcherSelect({ }); // Persist locale to the database (fire-and-forget) api.post("/user/locale", { locale }).catch(() => { - // Silently ignore errors — cookie is already set as fallback + // Silently ignore errors - cookie is already set as fallback }); } @@ -53,7 +53,7 @@ export default function LocaleSwitcherSelect({ )} aria-label={label} > - + {selected?.label ?? label} diff --git a/src/components/LogDataTable.tsx b/src/components/LogDataTable.tsx index 3a53a859f..14e87ff75 100644 --- a/src/components/LogDataTable.tsx +++ b/src/components/LogDataTable.tsx @@ -405,7 +405,11 @@ export function LogDataTable({ onClick={() => !disabled && onExport() } - disabled={isExporting || disabled || isExportDisabled} + disabled={ + isExporting || + disabled || + isExportDisabled + } > {isExporting ? ( diff --git a/src/components/MachineClientsTable.tsx b/src/components/MachineClientsTable.tsx index 9c1da5b4d..4ef22c83d 100644 --- a/src/components/MachineClientsTable.tsx +++ b/src/components/MachineClientsTable.tsx @@ -293,7 +293,7 @@ export default function MachineClientsTable({ } else { return ( -
+
{t("disconnected")}
); diff --git a/src/components/OrgIdpDataTable.tsx b/src/components/OrgIdpDataTable.tsx index 7e3f7ab65..fe15b6cc9 100644 --- a/src/components/OrgIdpDataTable.tsx +++ b/src/components/OrgIdpDataTable.tsx @@ -12,13 +12,15 @@ interface DataTableProps { data: TData[]; onAdd?: () => void; addActions?: DataTableAddAction[]; + addButtonDisabled?: boolean; } export function IdpDataTable({ columns, data, onAdd, - addActions + addActions, + addButtonDisabled }: DataTableProps) { const t = useTranslations(); @@ -33,6 +35,7 @@ export function IdpDataTable({ addButtonText={t("idpAdd")} onAdd={onAdd} addActions={addActions} + addButtonDisabled={addButtonDisabled} enableColumnVisibility={true} stickyRightColumn="actions" /> diff --git a/src/components/OrgIdpTable.tsx b/src/components/OrgIdpTable.tsx index 0e3a83dc2..bdbaafa27 100644 --- a/src/components/OrgIdpTable.tsx +++ b/src/components/OrgIdpTable.tsx @@ -52,6 +52,7 @@ import type { ListUserAdminOrgIdpsResponse } from "@server/routers/orgIdp/types" import { cn } from "@app/lib/cn"; import { usePaidStatus } from "@app/hooks/usePaidStatus"; import { tierMatrix } from "@server/lib/billing/tierMatrix"; +import { isIdpGlobalModeBannerVisible } from "@app/components/IdpGlobalModeBanner"; export type IdpRow = { idpId: number; @@ -85,13 +86,15 @@ export default function IdpTable({ idps, orgId }: Props) { const [importSubmitting, setImportSubmitting] = useState(false); const [debouncedImportSearch] = useDebounce(importSearchQuery, 150); - const api = createApiClient(useEnvContext()); + const envContext = useEnvContext(); + const api = createApiClient(envContext); const { user } = useUserContext(); const { isPaidUser } = usePaidStatus(); const router = useRouter(); const t = useTranslations(); const canImportOrgOidcIdp = isPaidUser(tierMatrix.orgOidc); + const addIdpDisabled = isIdpGlobalModeBannerVisible(envContext.env); const { data: adminIdpsRaw = [] } = useQuery({ queryKey: ["admin-org-idps", user.userId], @@ -184,23 +187,6 @@ export default function IdpTable({ idps, orgId }: Props) { }; const columns: ExtendedColumnDef[] = [ - { - accessorKey: "idpId", - friendlyName: "ID", - header: ({ column }) => { - return ( - - ); - } - }, { accessorKey: "name", friendlyName: t("name"), @@ -427,6 +413,7 @@ export default function IdpTable({ idps, orgId }: Props) { {isCollapsed ? ( @@ -172,7 +172,7 @@ export function OrgSelector({ ); @@ -387,6 +419,7 @@ export default function PendingSitesTable({ cell: ({ row }) => { const siteRow = row.original; const isApproving = approvingIds.has(siteRow.id); + const isRejecting = rejectingIds.has(siteRow.id); return (
@@ -409,7 +442,18 @@ export default function PendingSitesTable({ + ); } @@ -148,6 +170,30 @@ export default function UsersTable({ roles }: RolesTableProps) { } ]; + function toggleSort(column: string) { + const newSearch = getNextSortOrder(column, searchParams); + + filter({ + searchParams: newSearch + }); + } + + const handlePaginationChange = (newPage: PaginationState) => { + searchParams.set("page", (newPage.pageIndex + 1).toString()); + searchParams.set("pageSize", newPage.pageSize.toString()); + filter({ + searchParams + }); + }; + + const handleSearchChange = useDebouncedCallback((query: string) => { + searchParams.set("query", query); + searchParams.delete("page"); + filter({ + searchParams + }); + }, 300); + return ( <> {editingRole && ( @@ -191,10 +237,18 @@ export default function UsersTable({ roles }: RolesTableProps) { /> )} - { + rows={roles} + tableId="roles-table" + searchQuery={searchParams.get("query")?.toString()} + onSearch={handleSearchChange} + onPaginationChange={handlePaginationChange} + searchPlaceholder={t("accessRolesSearch")} + addButtonText={t("accessRolesAdd")} + rowCount={rowCount} + pagination={pagination} + onAdd={() => { setIsCreateModalOpen(true); }} onRefresh={() => startTransition(refreshData)} diff --git a/src/components/S3DestinationCredenza.tsx b/src/components/S3DestinationCredenza.tsx new file mode 100644 index 000000000..7702e7932 --- /dev/null +++ b/src/components/S3DestinationCredenza.tsx @@ -0,0 +1,63 @@ +"use client"; + + +import { + Credenza, + CredenzaBody, + CredenzaClose, + CredenzaContent, + CredenzaDescription, + CredenzaFooter, + CredenzaHeader, + CredenzaTitle +} from "@app/components/Credenza"; +import { Button } from "@app/components/ui/button"; +import { ContactSalesBanner } from "@app/components/ContactSalesBanner"; +import { useTranslations } from "next-intl"; + +export interface S3DestinationCredenzaProps { + open: boolean; + onOpenChange: (open: boolean) => void; + editing: any; + orgId: string; + onSaved: () => void; +} + +export function S3DestinationCredenza({ + open, + onOpenChange, + editing, + orgId, + onSaved, +}: S3DestinationCredenzaProps) { + const t = useTranslations(); + + return ( + + + + + {editing + ? t("S3DestEditTitle") + : t("S3DestAddTitle")} + + + {editing + ? t("S3DestEditDescription") + : t("S3DestAddDescription")} + + + + + + + + + + + + + + + ); +} diff --git a/src/components/ShareLinksTable.tsx b/src/components/ShareLinksTable.tsx index efac77df3..333cee03f 100644 --- a/src/components/ShareLinksTable.tsx +++ b/src/components/ShareLinksTable.tsx @@ -144,9 +144,9 @@ export default function ShareLinksTable({ - ); diff --git a/src/components/ShowTrialCard.tsx b/src/components/ShowTrialCard.tsx new file mode 100644 index 000000000..1cc8e79f1 --- /dev/null +++ b/src/components/ShowTrialCard.tsx @@ -0,0 +1,98 @@ +"use client"; + +import { cn } from "@app/lib/cn"; +import { useSubscriptionStatusContext } from "@app/hooks/useSubscriptionStatusContext"; +import { useParams } from "next/navigation"; +import Link from "next/link"; +import { ClockIcon, ArrowRight } from "lucide-react"; +import { ProgressBackwards } from "@app/components/ui/progress-backwards"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger +} from "@app/components/ui/tooltip"; +import { useTranslations } from "next-intl"; + +const TRIAL_DURATION_DAYS = 14; + +export default function ShowTrialCard({ + isCollapsed +}: { + isCollapsed?: boolean; +}) { + const context = useSubscriptionStatusContext(); + const params = useParams(); + const orgId = params?.orgId as string | undefined; + const t = useTranslations(); + + const trialExpiresAt = context?.trialExpiresAt ?? null; + + if (trialExpiresAt == null) return null; + + const now = Date.now(); + const remainingMs = trialExpiresAt - now; + const remainingDays = Math.max(0, Math.ceil(remainingMs / (1000 * 60 * 60 * 24))); + const totalMs = TRIAL_DURATION_DAYS * 24 * 60 * 60 * 1000; + const progressPct = Math.min(100, Math.max(0, ((now - (trialExpiresAt - totalMs)) / totalMs) * 100)); + // Inverted: full bar at start, drains to empty as trial ends + const displayPct = 100 - progressPct; + + const billingHref = orgId ? `/${orgId}/settings/billing` : "/"; + + if (isCollapsed) { + return ( + + + + + + + + +

+ {remainingDays === 0 + ? t("trialExpired") + : t("trialDaysLeftShort", { days: remainingDays })} +

+
+
+
+ ); + } + + return ( + +
+ +

+ {remainingDays === 0 + ? t("trialExpired") + : t("trialActive")} +

+
+
+ + + {remainingDays === 0 + ? t("trialHasEnded") + : t("trialDaysRemaining", { count: remainingDays })} + +
+ {t("trialGoToBilling")} + +
+
+ + ); +} diff --git a/src/components/SidebarNav.tsx b/src/components/SidebarNav.tsx index 5769bf5cf..dd673dace 100644 --- a/src/components/SidebarNav.tsx +++ b/src/components/SidebarNav.tsx @@ -121,8 +121,8 @@ function CollapsibleNavItem({ "flex items-center w-full rounded-md transition-colors", "px-3 py-1.5", isActive - ? "bg-secondary font-medium" - : "text-muted-foreground hover:bg-secondary/80 dark:hover:bg-secondary/50 hover:text-foreground", + ? "bg-sidebar-accent font-medium" + : "text-muted-foreground hover:bg-sidebar-accent/80 dark:hover:bg-sidebar-accent/50 hover:text-foreground", isDisabled && "cursor-not-allowed opacity-60" )} disabled={isDisabled} @@ -256,8 +256,8 @@ function CollapsedNavItemWithPopover({ className={cn( "flex items-center rounded-md transition-colors px-2 py-2 justify-center w-full", isActive || isChildActive - ? "bg-secondary font-medium" - : "text-muted-foreground hover:bg-secondary/80 dark:hover:bg-secondary/50 hover:text-foreground", + ? "bg-sidebar-accent font-medium" + : "text-muted-foreground hover:bg-sidebar-accent/80 dark:hover:bg-sidebar-accent/50 hover:text-foreground", isDisabled && "cursor-not-allowed opacity-60" )} @@ -308,8 +308,8 @@ function CollapsedNavItemWithPopover({ className={cn( "flex items-center rounded-md transition-colors px-3 py-1.5 text-sm", childIsActive - ? "bg-secondary font-medium" - : "text-muted-foreground hover:bg-secondary/50 hover:text-foreground", + ? "bg-sidebar-accent font-medium" + : "text-muted-foreground hover:bg-sidebar-accent/50 hover:text-foreground", childIsDisabled && "cursor-not-allowed opacity-60" )} @@ -450,8 +450,8 @@ export function SidebarNav({ "flex items-center rounded-md transition-colors relative", isCollapsed ? "px-2 py-2 justify-center" : "px-3 py-1.5", isActive - ? "bg-secondary font-medium" - : "text-muted-foreground hover:bg-secondary/80 dark:hover:bg-secondary/50 hover:text-foreground", + ? "bg-sidebar-accent font-medium" + : "text-muted-foreground hover:bg-sidebar-accent/80 dark:hover:bg-sidebar-accent/50 hover:text-foreground", isDisabled && "cursor-not-allowed opacity-60" )} onClick={(e) => { diff --git a/src/components/SiteInfoCard.tsx b/src/components/SiteInfoCard.tsx index c0a9b36b1..56492ff54 100644 --- a/src/components/SiteInfoCard.tsx +++ b/src/components/SiteInfoCard.tsx @@ -33,7 +33,7 @@ export default function SiteInfoCard({}: SiteInfoCardProps) { return ( - + {t("identifier")} {site.niceId} @@ -52,7 +52,7 @@ export default function SiteInfoCard({}: SiteInfoCardProps) {
) : (
-
+
{t("offline")}
)} @@ -68,6 +68,18 @@ export default function SiteInfoCard({}: SiteInfoCardProps) { {getConnectionTypeString(site.type)} + {site.endpoint && ( + + + {t("publicIpEndpoint")} + + + {site.endpoint.includes(":") + ? site.endpoint.substring(0, site.endpoint.lastIndexOf(":")) + : site.endpoint} + + + )} diff --git a/src/components/SitesTable.tsx b/src/components/SitesTable.tsx index 6cca706a6..ffec95283 100644 --- a/src/components/SitesTable.tsx +++ b/src/components/SitesTable.tsx @@ -1,6 +1,7 @@ "use client"; import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog"; +import UptimeMiniBar from "@app/components/UptimeMiniBar"; import { Badge } from "@app/components/ui/badge"; import { Button } from "@app/components/ui/button"; @@ -29,7 +30,7 @@ import { import { useTranslations } from "next-intl"; import Link from "next/link"; import { usePathname, useRouter } from "next/navigation"; -import { useState, useTransition } from "react"; +import { useState, useTransition, useEffect } from "react"; import { useDebouncedCallback } from "use-debounce"; import z from "zod"; import { ColumnFilterButton } from "./ColumnFilterButton"; @@ -84,6 +85,13 @@ export default function SitesTable({ const api = createApiClient(useEnvContext()); const t = useTranslations(); + useEffect(() => { + const interval = setInterval(() => { + router.refresh(); + }, 10_000); + return () => clearInterval(interval); + }, []); + const booleanSearchFilterSchema = z .enum(["true", "false"]) .optional() @@ -212,7 +220,7 @@ export default function SitesTable({ } else { return ( -
+
{t("offline")}
); @@ -222,6 +230,17 @@ export default function SitesTable({ } } }, + { + id: "uptime", + friendlyName: "Uptime", + header: () => {t("uptime30d")}, + cell: ({ row }) => { + const originalRow = row.original; + return ( + + ); + } + }, { accessorKey: "mbIn", friendlyName: t("dataIn"), @@ -363,9 +382,9 @@ export default function SitesTable({ - ); diff --git a/src/components/UptimeAlertSection.tsx b/src/components/UptimeAlertSection.tsx new file mode 100644 index 000000000..a964d2614 --- /dev/null +++ b/src/components/UptimeAlertSection.tsx @@ -0,0 +1,329 @@ +"use client"; + +import { useState, useMemo } from "react"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import Link from "next/link"; +import { BellPlus, BellRing } from "lucide-react"; +import { + SettingsSection, + SettingsSectionHeader, + SettingsSectionTitle, + SettingsSectionDescription, + SettingsSectionBody +} from "@app/components/Settings"; +import UptimeBar from "@app/components/UptimeBar"; +import { Button } from "@app/components/ui/button"; +import { + Credenza, + CredenzaBody, + CredenzaClose, + CredenzaContent, + CredenzaDescription, + CredenzaFooter, + CredenzaHeader, + CredenzaTitle +} from "@app/components/Credenza"; +import { Input } from "@app/components/ui/input"; +import { Label } from "@app/components/ui/label"; +import { TagInput, type Tag } from "@app/components/tags/tag-input"; +import { getUserDisplayName } from "@app/lib/getUserDisplayName"; +import { createApiClient, formatAxiosError } from "@app/lib/api"; +import { useEnvContext } from "@app/hooks/useEnvContext"; +import { toast } from "@app/hooks/useToast"; +import { orgQueries } from "@app/lib/queries"; +import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert"; +import { usePaidStatus } from "@app/hooks/usePaidStatus"; +import { tierMatrix } from "@server/lib/billing/tierMatrix"; + +interface UptimeAlertSectionProps { + orgId: string; + siteId?: number; + startingName?: string; + resourceId?: number; + days?: number; +} + +export default function UptimeAlertSection({ + orgId, + siteId, + startingName, + resourceId, + days = 90 +}: UptimeAlertSectionProps) { + const api = createApiClient(useEnvContext()); + const queryClient = useQueryClient(); + const { isPaidUser } = usePaidStatus(); + const isPaid = isPaidUser(tierMatrix.alertingRules); + + const [open, setOpen] = useState(false); + const [name, setName] = useState( + `${siteId ? "Site" : "Resource"} ${startingName} Alert` + ); + const [userTags, setUserTags] = useState([]); + const [roleTags, setRoleTags] = useState([]); + const [emailTags, setEmailTags] = useState([]); + const [activeUserTagIndex, setActiveUserTagIndex] = useState( + null + ); + const [activeRoleTagIndex, setActiveRoleTagIndex] = useState( + null + ); + const [activeEmailTagIndex, setActiveEmailTagIndex] = useState< + number | null + >(null); + const [loading, setLoading] = useState(false); + + const { data: alertRules, isLoading: alertRulesLoading } = useQuery( + orgQueries.alertRulesForSource({ orgId, siteId, resourceId }) + ); + + const { data: orgUsers = [] } = useQuery(orgQueries.users({ orgId })); + const { data: orgRoles = [] } = useQuery(orgQueries.roles({ orgId })); + + const allUsers = useMemo( + () => + orgUsers.map((u) => ({ + id: String(u.id), + text: getUserDisplayName({ + email: u.email, + name: u.name, + username: u.username + }) + })), + [orgUsers] + ); + + const allRoles = useMemo( + () => + orgRoles + .map((r) => ({ id: String(r.roleId), text: r.name })) + .filter((r) => r.text !== "Admin"), + [orgRoles] + ); + + const hasRules = (alertRules?.length ?? 0) > 0; + + async function handleSubmit() { + if ( + userTags.length === 0 && + roleTags.length === 0 && + emailTags.length === 0 + ) { + toast({ + variant: "destructive", + title: "No recipients", + description: + "Please add at least one user, role, or email to notify." + }); + return; + } + + setLoading(true); + try { + await api.put(`/org/${orgId}/alert-rule`, { + name, + eventType: siteId ? "site_toggle" : "resource_toggle", + enabled: true, + cooldownSeconds: 300, + siteIds: siteId ? [siteId] : [], + healthCheckIds: [], + resourceIds: resourceId ? [resourceId] : [], + userIds: userTags.map((tag) => tag.id), + roleIds: roleTags.map((tag) => Number(tag.id)), + emails: emailTags.map((tag) => tag.text), + webhookActions: [] + }); + + toast({ + title: "Alert created", + description: "You will be notified when this changes status." + }); + + setOpen(false); + setName("Uptime Alert"); + setUserTags([]); + setRoleTags([]); + setEmailTags([]); + + queryClient.invalidateQueries({ + queryKey: orgQueries.alertRulesForSource({ + orgId, + siteId, + resourceId + }).queryKey + }); + } catch (e) { + toast({ + variant: "destructive", + title: "Failed to create alert", + description: formatAxiosError(e, "An error occurred.") + }); + } + setLoading(false); + } + + const rulesListSearch = new URLSearchParams(); + if (siteId != null) rulesListSearch.set("siteId", String(siteId)); + if (resourceId != null) + rulesListSearch.set("resourceId", String(resourceId)); + const rulesListHref = `/${orgId}/settings/alerting/rules${ + rulesListSearch.toString() ? `?${rulesListSearch}` : "" + }`; + + const alertButton = alertRulesLoading ? ( + + ) : hasRules ? ( + + ) : ( + + ); + + return ( + <> + + +
+
+ Uptime + + Site availability over the last {days} days. + +
+ {alertButton} +
+
+ + + +
+ + + + + Create Email Alert + + Get notified by email when this{" "} + {siteId ? "site" : "resource"} goes offline or comes + back online. + + + +
+ +
+
+
+ + setName(e.target.value)} + placeholder="Alert name" + /> +
+
+ + { + const next = + typeof newTags === "function" + ? newTags(userTags) + : newTags; + setUserTags(next as Tag[]); + }} + enableAutocomplete + autocompleteOptions={allUsers} + restrictTagsToAutocompleteOptions + allowDuplicates={false} + sortTags + /> +
+
+ + { + const next = + typeof newTags === "function" + ? newTags(roleTags) + : newTags; + setRoleTags(next as Tag[]); + }} + enableAutocomplete + autocompleteOptions={allRoles} + restrictTagsToAutocompleteOptions + allowDuplicates={false} + sortTags + /> +
+
+ + { + const next = + typeof newTags === "function" + ? newTags(emailTags) + : newTags; + setEmailTags(next as Tag[]); + }} + allowDuplicates={false} + sortTags + validateTag={(tag) => + /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(tag) + } + delimiterList={[",", "Enter"]} + /> +
+
+
+
+
+ + + + + + +
+
+ + ); +} diff --git a/src/components/UptimeBar.tsx b/src/components/UptimeBar.tsx new file mode 100644 index 000000000..992484ea4 --- /dev/null +++ b/src/components/UptimeBar.tsx @@ -0,0 +1,242 @@ +"use client"; + +import { useQuery } from "@tanstack/react-query"; +import { orgQueries } from "@app/lib/queries"; +import { + Tooltip, + TooltipContent, + TooltipTrigger +} from "@app/components/ui/tooltip"; +import { useEnvContext } from "@app/hooks/useEnvContext"; +import { createApiClient } from "@app/lib/api"; +import { cn } from "@app/lib/cn"; + +function formatDuration(seconds: number): string { + if (seconds === 0) return "0s"; + if (seconds < 60) return `${Math.round(seconds)}s`; + const h = Math.floor(seconds / 3600); + const m = Math.floor((seconds % 3600) / 60); + const s = Math.round(seconds % 60); + if (h > 0) return s > 0 ? `${h}h ${m}m ${s}s` : `${h}h ${m}m`; + if (m > 0 && s > 0) return `${m}m ${s}s`; + return `${m}m`; +} + +function formatDate(dateStr: string): string { + return new Date(dateStr + "T00:00:00").toLocaleDateString([], { + month: "short", + day: "numeric", + year: "numeric" + }); +} + +function formatTime(ts: number): string { + return new Date(ts * 1000).toLocaleTimeString([], { + hour: "2-digit", + minute: "2-digit" + }); +} + +const barColorClass: Record = { + good: "bg-green-500", + degraded: "bg-yellow-500", + bad: "bg-red-500", + no_data: "bg-neutral-200 dark:bg-neutral-700" +}; + +type UptimeBarProps = { + orgId?: string; + siteId?: number; + resourceId?: number; + healthCheckId?: number; + days?: number; + title?: string; + className?: string; +}; + +export default function UptimeBar({ + orgId, + siteId, + resourceId, + healthCheckId, + days = 90, + title, + className +}: UptimeBarProps) { + const api = createApiClient(useEnvContext()); + + const siteQuery = useQuery({ + ...orgQueries.siteStatusHistory({ siteId: siteId ?? 0, days }), + enabled: siteId != null, + meta: { api } + }); + + const hcQuery = useQuery({ + ...orgQueries.healthCheckStatusHistory({ + orgId: orgId ?? "", + healthCheckId: healthCheckId ?? 0, + days + }), + enabled: healthCheckId != null && siteId == null && resourceId == null, + meta: { api } + }); + + const resourceQuery = useQuery({ + ...orgQueries.resourceStatusHistory({ resourceId, days }), + enabled: resourceId != null && siteId == null && healthCheckId == null, + meta: { api } + }); + + const { data, isLoading } = + siteId != null + ? siteQuery + : resourceId != null + ? resourceQuery + : hcQuery; + + if (isLoading) { + return ( +
+
+ {title && ( + {title} + )} +
+ + +
+
+
+ {Array.from({ length: days }).map((_, i) => ( +
+ ))} +
+
+ {days} days ago + Today +
+
+ ); + } + + if (!data) return null; + + const allNoData = data.days.every((d) => d.status === "no_data"); + + return ( +
+ {/* Header row */} +
+ {title && {title}} +
+ {!allNoData && ( + <> + + + {data.overallUptimePercent.toFixed(2)}% + {" "} + uptime + + {data.totalDowntimeSeconds > 0 && ( + + + {formatDuration( + data.totalDowntimeSeconds + )} + {" "} + downtime + + )} + + )} + {allNoData && ( + + No data available + + )} +
+
+ + {/* Bar row */} +
+ {data.days.map((day, i) => ( + + +
+ + +
+ {formatDate(day.date)} +
+ {day.status !== "no_data" && ( +
+ Uptime:{" "} + + {day.uptimePercent.toFixed(1)}% + +
+ )} + {day.totalDowntimeSeconds > 0 && ( +
+ Downtime:{" "} + + {formatDuration( + day.totalDowntimeSeconds + )} + +
+ )} + {day.downtimeWindows.length > 0 && ( +
+ {day.downtimeWindows.map((w, wi) => ( +
+ {formatTime(w.start)} + {w.end + ? ` – ${formatTime(w.end)}` + : " – ongoing"}{" "} + + ({w.status}) + +
+ ))} +
+ )} + {day.status === "no_data" && ( +
+ No monitoring data +
+ )} +
+ + ))} +
+ + {/* Date labels */} +
+ {days} days ago + Today +
+
+ ); +} diff --git a/src/components/UptimeMiniBar.tsx b/src/components/UptimeMiniBar.tsx new file mode 100644 index 000000000..5baabb4dd --- /dev/null +++ b/src/components/UptimeMiniBar.tsx @@ -0,0 +1,159 @@ +"use client"; + +import { useQuery } from "@tanstack/react-query"; +import { orgQueries } from "@app/lib/queries"; +import { + Tooltip, + TooltipContent, + TooltipTrigger +} from "@app/components/ui/tooltip"; +import { useEnvContext } from "@app/hooks/useEnvContext"; +import { createApiClient } from "@app/lib/api"; +import { cn } from "@app/lib/cn"; + +function formatDuration(seconds: number): string { + if (seconds === 0) return "0s"; + if (seconds < 60) return `${Math.round(seconds)}s`; + const h = Math.floor(seconds / 3600); + const m = Math.floor((seconds % 3600) / 60); + const s = Math.round(seconds % 60); + if (h > 0) return `${h}h ${m}m`; + if (m > 0 && s > 0) return `${m}m ${s}s`; + return `${m}m`; +} + +function formatDate(dateStr: string): string { + return new Date(dateStr + "T00:00:00").toLocaleDateString([], { + month: "short", + day: "numeric" + }); +} + +const barColorClass: Record = { + good: "bg-green-500", + degraded: "bg-yellow-500", + bad: "bg-red-500", + no_data: "bg-neutral-200 dark:bg-neutral-700" +}; + +type UptimeMiniBarProps = { + orgId?: string; + siteId?: number; + resourceId?: number; + healthCheckId?: number; + days?: number; +}; + +export default function UptimeMiniBar({ + orgId, + siteId, + resourceId, + healthCheckId, + days = 30 +}: UptimeMiniBarProps) { + const api = createApiClient(useEnvContext()); + + const siteQuery = useQuery({ + ...orgQueries.siteStatusHistory({ siteId: siteId ?? 0, days }), + enabled: siteId != null, + meta: { api }, + staleTime: 5 * 60 * 1000 + }); + + const hcQuery = useQuery({ + ...orgQueries.healthCheckStatusHistory({ + orgId: orgId ?? "", + healthCheckId: healthCheckId ?? 0, + days + }), + enabled: healthCheckId != null && siteId == null && resourceId == null, + meta: { api }, + staleTime: 5 * 60 * 1000 + }); + + const resourceQuery = useQuery({ + ...orgQueries.resourceStatusHistory({ resourceId, days }), + enabled: resourceId != null && siteId == null && healthCheckId == null, + meta: { api }, + staleTime: 5 * 60 * 1000 + }); + + const { data, isLoading } = + siteId != null + ? siteQuery + : resourceId != null + ? resourceQuery + : hcQuery; + + if (isLoading) { + return ( +
+
+ {Array.from({ length: days }).map((_, i) => ( +
+ ))} +
+ + + +
+ ); + } + + if (!data) return null; + + const allNoData = data.days.every((d) => d.status === "no_data"); + + return ( +
+
+ {data.days.map((day, i) => ( + + +
+ + +
+ {formatDate(day.date)} +
+
+ {day.status === "no_data" + ? "No data" + : `${day.uptimePercent.toFixed(1)}% uptime`} +
+ {day.totalDowntimeSeconds > 0 && ( +
+ Down:{" "} + {formatDuration(day.totalDowntimeSeconds)} +
+ )} +
+ + ))} +
+ + {allNoData + ? "No data" + : `${data.overallUptimePercent.toFixed(1)}%`} + +
+ ); +} diff --git a/src/components/UserDevicesTable.tsx b/src/components/UserDevicesTable.tsx index 4c5331015..88e495406 100644 --- a/src/components/UserDevicesTable.tsx +++ b/src/components/UserDevicesTable.tsx @@ -373,12 +373,12 @@ export default function UserDevicesTable({ - ) : ( @@ -427,7 +427,7 @@ export default function UserDevicesTable({ } else { return ( -
+
{t("disconnected")}
); diff --git a/src/components/UsersDataTable.tsx b/src/components/UsersDataTable.tsx deleted file mode 100644 index ececa4c17..000000000 --- a/src/components/UsersDataTable.tsx +++ /dev/null @@ -1,41 +0,0 @@ -"use client"; - -import { ColumnDef } from "@tanstack/react-table"; -import { DataTable } from "@app/components/ui/data-table"; -import { useTranslations } from "next-intl"; - -interface DataTableProps { - columns: ColumnDef[]; - data: TData[]; - inviteUser?: () => void; - onRefresh?: () => void; - isRefreshing?: boolean; -} - -export function UsersDataTable({ - columns, - data, - inviteUser, - onRefresh, - isRefreshing -}: DataTableProps) { - const t = useTranslations(); - - return ( - - ); -} diff --git a/src/components/UsersTable.tsx b/src/components/UsersTable.tsx index 3e2d4e578..50915c02b 100644 --- a/src/components/UsersTable.tsx +++ b/src/components/UsersTable.tsx @@ -1,29 +1,42 @@ "use client"; -import { ColumnDef } from "@tanstack/react-table"; -import { ExtendedColumnDef } from "@app/components/ui/data-table"; +import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog"; +import { Button } from "@app/components/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@app/components/ui/dropdown-menu"; -import { Button } from "@app/components/ui/button"; -import { ArrowRight, ArrowUpDown, Crown, MoreHorizontal } from "lucide-react"; -import { UsersDataTable } from "@app/components/UsersDataTable"; -import { useState, useEffect } from "react"; -import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog"; +import { useEnvContext } from "@app/hooks/useEnvContext"; +import { useNavigationContext } from "@app/hooks/useNavigationContext"; import { useOrgContext } from "@app/hooks/useOrgContext"; import { toast } from "@app/hooks/useToast"; +import { useUserContext } from "@app/hooks/useUserContext"; +import { createApiClient, formatAxiosError } from "@app/lib/api"; +import { getUserDisplayName } from "@app/lib/getUserDisplayName"; +import { getNextSortOrder, getSortDirection } from "@app/lib/sortColumn"; +import { type PaginationState } from "@tanstack/react-table"; +import { + ArrowDown01Icon, + ArrowRight, + ArrowUp10Icon, + ChevronsUpDownIcon, + MoreHorizontal +} from "lucide-react"; +import { useTranslations } from "next-intl"; import Link from "next/link"; import { useRouter } from "next/navigation"; -import { formatAxiosError } from "@app/lib/api"; -import { createApiClient } from "@app/lib/api"; -import { getUserDisplayName } from "@app/lib/getUserDisplayName"; -import { useEnvContext } from "@app/hooks/useEnvContext"; -import { useUserContext } from "@app/hooks/useUserContext"; -import { useTranslations } from "next-intl"; +import { useMemo, useState, useTransition } from "react"; +import { useDebouncedCallback } from "use-debounce"; +import z from "zod"; +import { ColumnFilterButton } from "./ColumnFilterButton"; +import { ColumnMultiFilterButton } from "./ColumnMultiFilterButton"; import IdpTypeBadge from "./IdpTypeBadge"; +import { + ControlledDataTable, + type ExtendedColumnDef +} from "./ui/controlled-data-table"; import UserRoleBadges from "./UserRoleBadges"; export type UserRow = { @@ -41,41 +54,90 @@ export type UserRow = { isOwner: boolean; }; +type FilterOption = { value: string; label: string }; + type UsersTableProps = { users: UserRow[]; + pagination: PaginationState; + rowCount: number; + idpFilterOptions: FilterOption[]; + roleFilterOptions: FilterOption[]; }; -export default function UsersTable({ users: u }: UsersTableProps) { +export default function UsersTable({ + users, + pagination, + rowCount, + idpFilterOptions, + roleFilterOptions +}: UsersTableProps) { const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); const [selectedUser, setSelectedUser] = useState(null); - const [users, setUsers] = useState(u); const router = useRouter(); const api = createApiClient(useEnvContext()); - const { user, updateUser } = useUserContext(); + const { user } = useUserContext(); const { org } = useOrgContext(); const t = useTranslations(); - const [isRefreshing, setIsRefreshing] = useState(false); + const [isNavigatingToAddPage, startNavigation] = useTransition(); + const [isRefreshing, startTransition] = useTransition(); + const { + navigate: filter, + isNavigating: isFiltering, + searchParams, + pathname + } = useNavigationContext(); - // Update local state when props change (e.g., after refresh) - useEffect(() => { - setUsers(u); - }, [u]); + const idpIdParamSchema = z + .union([z.literal("internal"), z.string().regex(/^\d+$/)]) + .optional() + .catch(undefined); + + const roleIdsFromSearchParams = useMemo(() => { + const sp = new URLSearchParams(searchParams); + return [ + ...new Set(sp.getAll("role_id").filter((id) => /^\d+$/.test(id))) + ]; + }, [searchParams.toString()]); + + function handleFilterChange( + column: string, + value: string | undefined | null + ) { + const sp = new URLSearchParams(searchParams); + sp.delete(column); + sp.delete("page"); + + if (value) { + sp.set(column, value); + } + startTransition(() => router.push(`${pathname}?${sp.toString()}`)); + } + + function handleRoleIdsChange(values: string[]) { + const sp = new URLSearchParams(searchParams); + sp.delete("role_id"); + sp.delete("page"); + for (const id of values) { + if (/^\d+$/.test(id)) { + sp.append("role_id", id); + } + } + startTransition(() => router.push(`${pathname}?${sp.toString()}`)); + } const refreshData = async () => { - console.log("Data refreshed"); - setIsRefreshing(true); - try { - await new Promise((resolve) => setTimeout(resolve, 200)); - router.refresh(); - } catch (error) { - toast({ - title: t("error"), - description: t("refreshError"), - variant: "destructive" - }); - } finally { - setIsRefreshing(false); - } + startTransition(async () => { + try { + await new Promise((resolve) => setTimeout(resolve, 200)); + router.refresh(); + } catch (error) { + toast({ + title: t("error"), + description: t("refreshError"), + variant: "destructive" + }); + } + }); }; const columns: ExtendedColumnDef[] = [ @@ -84,15 +146,21 @@ export default function UsersTable({ users: u }: UsersTableProps) { enableHiding: false, friendlyName: t("username"), header: ({ column }) => { + const nameOrder = getSortDirection("username", searchParams); + const Icon = + nameOrder === "asc" + ? ArrowDown01Icon + : nameOrder === "desc" + ? ArrowUp10Icon + : ChevronsUpDownIcon; return ( ); } @@ -100,17 +168,21 @@ export default function UsersTable({ users: u }: UsersTableProps) { { accessorKey: "idpName", friendlyName: t("identityProvider"), - header: ({ column }) => { + header: () => { return ( - + searchPlaceholder={t("searchPlaceholder")} + emptyMessage={t("emptySearchOptions")} + label={t("identityProvider")} + className="p-3" + /> ); }, cell: ({ row }) => { @@ -128,17 +200,17 @@ export default function UsersTable({ users: u }: UsersTableProps) { id: "role", accessorFn: (row) => row.roleLabels.join(", "), friendlyName: t("role"), - header: ({ column }) => { + header: () => { return ( - + ); }, cell: ({ row }) => { @@ -180,10 +252,8 @@ export default function UsersTable({ users: u }: UsersTableProps) { isDisabled && e.preventDefault() } > - - {t("accessUsersManage")} + + {t("accessUserManage")} {!isDisabled && ( @@ -214,10 +284,7 @@ export default function UsersTable({ users: u }: UsersTableProps) { - @@ -252,15 +319,36 @@ export default function UsersTable({ users: u }: UsersTableProps) { email: selectedUser.email || "" }) }); - - setUsers((prev) => - prev.filter((u) => u.id !== selectedUser?.id) - ); } } + router.refresh(); setIsDeleteModalOpen(false); } + function toggleSort(column: string) { + const newSearch = getNextSortOrder(column, searchParams); + + filter({ + searchParams: newSearch + }); + } + + const handlePaginationChange = (newPage: PaginationState) => { + searchParams.set("page", (newPage.pageIndex + 1).toString()); + searchParams.set("pageSize", newPage.pageSize.toString()); + filter({ + searchParams + }); + }; + + const handleSearchChange = useDebouncedCallback((query: string) => { + searchParams.set("query", query); + searchParams.delete("page"); + filter({ + searchParams + }); + }, 300); + return ( <> } buttonText={t("userRemoveOrgConfirm")} - onConfirm={removeUser} + onConfirm={async () => startTransition(removeUser)} string={ selectedUser ? getUserDisplayName({ @@ -289,16 +377,27 @@ export default function UsersTable({ users: u }: UsersTableProps) { title={t("userRemoveOrg")} /> - { - router.push( - `/${org?.org.orgId}/settings/access/users/create` + pagination={pagination} + rowCount={rowCount} + isNavigatingToAddPage={isNavigatingToAddPage} + addButtonText={t("accessUserCreate")} + searchQuery={searchParams.get("query")?.toString()} + onSearch={handleSearchChange} + onPaginationChange={handlePaginationChange} + rows={users} + searchPlaceholder={t("accessUsersSearch")} + tableId="users-table" + onAdd={() => { + startNavigation(() => + router.push( + `/${org?.org.orgId}/settings/access/users/create` + ) ); }} onRefresh={refreshData} - isRefreshing={isRefreshing} + isRefreshing={isRefreshing || isFiltering} /> ); diff --git a/src/components/ViewDevicesDialog.tsx b/src/components/ViewDevicesDialog.tsx index 9c29b219c..b29cdcc75 100644 --- a/src/components/ViewDevicesDialog.tsx +++ b/src/components/ViewDevicesDialog.tsx @@ -27,7 +27,7 @@ import { TableHeader, TableRow } from "@app/components/ui/table"; -import { Tabs, TabsList, TabsTrigger, TabsContent } from "@app/components/ui/tabs"; +import { HorizontalTabs } from "@app/components/HorizontalTabs"; import { Loader2, RefreshCw } from "lucide-react"; import moment from "moment"; import { useUserContext } from "@app/hooks/useUserContext"; @@ -58,7 +58,6 @@ export default function ViewDevicesDialog({ const [devices, setDevices] = useState([]); const [loading, setLoading] = useState(false); - const [activeTab, setActiveTab] = useState<"available" | "archived">("available"); const fetchDevices = async () => { setLoading(true); @@ -177,34 +176,21 @@ export default function ViewDevicesDialog({
) : ( - - setActiveTab(value as "available" | "archived") - } - className="w-full" + !d.archived).length})`, + href: "#available" + }, + { + title: `${t("archived") || "Archived"} (${devices.filter((d) => d.archived).length})`, + href: "#archived" + } + ]} > - - - {t("available") || "Available"} ( - { - devices.filter( - (d) => !d.archived - ).length - } - ) - - - {t("archived") || "Archived"} ( - { - devices.filter( - (d) => d.archived - ).length - } - ) - - - +
{devices.filter((d) => !d.archived) .length === 0 ? (
@@ -271,8 +257,8 @@ export default function ViewDevicesDialog({
)} - - +
+
{devices.filter((d) => d.archived) .length === 0 ? (
@@ -336,8 +322,8 @@ export default function ViewDevicesDialog({
)} - - +
+
)} diff --git a/src/components/WorldMap.tsx b/src/components/WorldMap.tsx index ac227c553..09548400b 100644 --- a/src/components/WorldMap.tsx +++ b/src/components/WorldMap.tsx @@ -218,7 +218,7 @@ function drawInteractiveCountries( }); hoverPath .datum(country) - .attr("d", path(country) as string) + .attr("d", path(country as any) as string) .style("display", null); }) diff --git a/src/components/alert-rule-editor/AlertRuleFields.tsx b/src/components/alert-rule-editor/AlertRuleFields.tsx new file mode 100644 index 000000000..bb99d57f3 --- /dev/null +++ b/src/components/alert-rule-editor/AlertRuleFields.tsx @@ -0,0 +1,1357 @@ +"use client"; + +import { Button } from "@app/components/ui/button"; +import { Checkbox } from "@app/components/ui/checkbox"; +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList +} from "@app/components/ui/command"; +import { + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage +} from "@app/components/ui/form"; +import { Input } from "@app/components/ui/input"; +import { + Popover, + PopoverContent, + PopoverTrigger +} from "@app/components/ui/popover"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue +} from "@app/components/ui/select"; +import { + RadioGroup, + RadioGroupItem +} from "@app/components/ui/radio-group"; +import { Label } from "@app/components/ui/label"; +import { StrategySelect } from "@app/components/StrategySelect"; +import { TagInput, type Tag } from "@app/components/tags/tag-input"; +import { getUserDisplayName } from "@app/lib/getUserDisplayName"; +import { + type AlertRuleFormAction, + type AlertRuleFormValues +} from "@app/lib/alertRuleForm"; +import { orgQueries } from "@app/lib/queries"; +import { useQuery } from "@tanstack/react-query"; +import { ContactSalesBanner } from "@app/components/ContactSalesBanner"; +import { Bell, Globe, ChevronsUpDown, Plus, Trash2 } from "lucide-react"; +import { useTranslations } from "next-intl"; +import { useEffect, useMemo, useRef, useState } from "react"; +import type { Control, UseFormReturn } from "react-hook-form"; +import { useFormContext, useWatch } from "react-hook-form"; +import { useDebounce } from "use-debounce"; + +export function AddActionPanel({ + onAdd +}: { + onAdd: (type: AlertRuleFormAction["type"]) => void; +}) { + const t = useTranslations(); + + + const EXTERNAL_INTEGRATIONS = [ + { + id: "pagerduty", + name: "PagerDuty", + logo: "/third-party/pgd.png", + description: "Send alerts to PagerDuty for incident management", + descriptionKey: t("alertingExternalPagerDutyDescription") + }, + { + id: "opsgenie", + name: "Opsgenie", + logo: "/third-party/opsgenie.png", + description: "Route alerts to Opsgenie for on-call management", + descriptionKey: t("alertingExternalOpsgenieDescription") + }, + { + id: "servicenow", + name: "ServiceNow", + logo: "/third-party/servicenow.png", + description: "Create ServiceNow incidents from alert events", + descriptionKey: t("alertingExternalServiceNowDescription") + }, + { + id: "incidentio", + name: "Incident.io", + logo: "/third-party/incidentio.png", + description: "Trigger Incident.io workflows from alert events", + descriptionKey: t("alertingExternalIncidentIoDescription") + } + ] as const; + + const EXTERNAL_IDS = EXTERNAL_INTEGRATIONS.map((i) => i.id); + + const [selected, setSelected] = useState("notify"); + + const isPremiumSelected = + selected !== null && EXTERNAL_IDS.includes(selected as any); + const isBuiltInSelected = selected !== null && !isPremiumSelected; + + const actionTypeOptions = [ + { + id: "notify", + title: t("alertingActionNotify"), + description: t("alertingActionNotifyDescription"), + icon: + }, + { + id: "webhook", + title: t("alertingActionWebhook"), + description: t("alertingActionWebhookDescription"), + icon: + }, + ...EXTERNAL_INTEGRATIONS.map((integration) => ({ + id: integration.id, + title: integration.name, + description: integration.description, + icon: ( + {integration.name} + ) + })) + ]; + + const handleAdd = () => { + if (!isBuiltInSelected) return; + onAdd(selected as AlertRuleFormAction["type"]); + setSelected(null); + }; + + return ( +
+ setSelected(v)} + /> + {isPremiumSelected && } + {!isPremiumSelected && ( + + )} +
+ ); +} + +function SiteMultiSelect({ + orgId, + value, + onChange +}: { + orgId: string; + value: number[]; + onChange: (v: number[]) => void; +}) { + const t = useTranslations(); + const [open, setOpen] = useState(false); + const [q, setQ] = useState(""); + const [debounced] = useDebounce(q, 150); + const { data: sites = [] } = useQuery( + orgQueries.sites({ orgId, query: debounced, perPage: 500 }) + ); + const toggle = (id: number) => { + if (value.includes(id)) { + onChange(value.filter((x) => x !== id)); + } else { + onChange([...value, id]); + } + }; + const summary = + value.length === 0 + ? t("alertingSelectSites") + : t("alertingSitesSelected", { count: value.length }); + return ( + + + + + + + + + {t("siteNotFound")} + + {sites.map((s) => ( + toggle(s.siteId)} + className="cursor-pointer" + > + + {s.name} + + ))} + + + + + + ); +} + +function HealthCheckMultiSelect({ + orgId, + value, + onChange +}: { + orgId: string; + value: number[]; + onChange: (v: number[]) => void; +}) { + const t = useTranslations(); + const [open, setOpen] = useState(false); + const [q, setQ] = useState(""); + const [debounced] = useDebounce(q, 150); + + const { data: healthChecks = [] } = useQuery( + orgQueries.healthChecks({ orgId }) + ); + + const shown = useMemo(() => { + const query = debounced.trim().toLowerCase(); + const base = query + ? healthChecks.filter((hc) => + hc.name.toLowerCase().includes(query) + ) + : healthChecks; + // Always keep already-selected items visible even if they fall outside the search + if (query && value.length > 0) { + const selectedNotInBase = healthChecks.filter( + (hc) => + value.includes(hc.targetHealthCheckId) && + !base.some( + (b) => b.targetHealthCheckId === hc.targetHealthCheckId + ) + ); + return [...selectedNotInBase, ...base]; + } + return base; + }, [healthChecks, debounced, value]); + + const toggle = (id: number) => { + if (value.includes(id)) { + onChange(value.filter((x) => x !== id)); + } else { + onChange([...value, id]); + } + }; + + const summary = + value.length === 0 + ? t("alertingSelectHealthChecks") + : t("alertingHealthChecksSelected", { count: value.length }); + + return ( + + + + + + + + + + {t("alertingHealthChecksEmpty")} + + + {shown.map((hc) => ( + + toggle(hc.targetHealthCheckId) + } + className="cursor-pointer" + > + + + {hc.name} + + + ))} + + + + + + ); +} + +function ResourceMultiSelect({ + orgId, + value, + onChange +}: { + orgId: string; + value: number[]; + onChange: (v: number[]) => void; +}) { + const t = useTranslations(); + const [open, setOpen] = useState(false); + const [q, setQ] = useState(""); + const [debounced] = useDebounce(q, 150); + + const { data: resources = [] } = useQuery( + orgQueries.resources({ orgId, query: debounced, perPage: 10 }) + ); + + const shown = useMemo(() => { + return resources; + }, [resources]); + + const toggle = (id: number) => { + if (value.includes(id)) { + onChange(value.filter((x) => x !== id)); + } else { + onChange([...value, id]); + } + }; + + const summary = + value.length === 0 + ? t("alertingSelectResources") + : t("alertingResourcesSelected", { count: value.length }); + + return ( + + + + + + + + + + {t("alertingResourcesEmpty")} + + + {shown.map((r) => ( + toggle(r.resourceId)} + className="cursor-pointer" + > + + {r.name} + + ))} + + + + + + ); +} + +export function ActionBlock({ + orgId, + index, + control, + form, + onRemove, + onUpdate, + canRemove +}: { + orgId: string; + index: number; + control: Control; + form: UseFormReturn; + onRemove: () => void; + onUpdate: (val: AlertRuleFormAction) => void; + canRemove: boolean; +}) { + const t = useTranslations(); + const type = useWatch({ control, name: `actions.${index}.type` }); + + const typeHeader = + type === "notify" ? ( +
+ + {t("alertingActionNotify")} +
+ ) : ( +
+ + {t("alertingActionWebhook")} +
+ ); + + return ( +
+ {canRemove && ( + + )} + {typeHeader} + {type === "notify" && ( + + )} + {type === "webhook" && ( + + )} +
+ ); +} + +function NotifyActionFields({ + orgId, + index, + control, + form +}: { + orgId: string; + index: number; + control: Control; + form: UseFormReturn; +}) { + const t = useTranslations(); + + const [emailActiveIdx, setEmailActiveIdx] = useState(null); + const [activeUsersTagIndex, setActiveUsersTagIndex] = useState< + number | null + >(null); + const [activeRolesTagIndex, setActiveRolesTagIndex] = useState< + number | null + >(null); + + const { data: orgUsers = [], isLoading: isLoadingUsers } = useQuery(orgQueries.users({ orgId })); + const { data: orgRoles = [], isLoading: isLoadingRoles } = useQuery(orgQueries.roles({ orgId })); + + const allUsers = useMemo( + () => + orgUsers.map((u) => ({ + id: String(u.id), + text: getUserDisplayName({ + email: u.email, + name: u.name, + username: u.username + }) + })), + [orgUsers] + ); + + const allRoles = useMemo( + () => + orgRoles + .map((r) => ({ id: String(r.roleId), text: r.name })) + .filter((r) => r.text !== "Admin"), + [orgRoles] + ); + + const hasResolvedTagsRef = useRef(false); + + useEffect(() => { + if (isLoadingUsers || isLoadingRoles) return; + if (hasResolvedTagsRef.current) return; + + const currentUserTags = form.getValues( + `actions.${index}.userTags` + ) as Tag[]; + const currentRoleTags = form.getValues( + `actions.${index}.roleTags` + ) as Tag[]; + + const resolvedUserTags = currentUserTags.map((tag) => { + const match = allUsers.find((u) => u.id === tag.id); + return match ? { id: tag.id, text: match.text } : tag; + }); + + const resolvedRoleTags = currentRoleTags.map((tag) => { + const match = allRoles.find((r) => r.id === tag.id); + return match ? { id: tag.id, text: match.text } : tag; + }); + + const userTagsNeedUpdate = resolvedUserTags.some( + (t, i) => t.text !== currentUserTags[i]?.text + ); + const roleTagsNeedUpdate = resolvedRoleTags.some( + (t, i) => t.text !== currentRoleTags[i]?.text + ); + + if (userTagsNeedUpdate) { + form.setValue(`actions.${index}.userTags`, resolvedUserTags, { + shouldDirty: false + }); + } + if (roleTagsNeedUpdate) { + form.setValue(`actions.${index}.roleTags`, resolvedRoleTags, { + shouldDirty: false + }); + } + + hasResolvedTagsRef.current = true; + }, [isLoadingUsers, isLoadingRoles, allUsers, allRoles]); + + const userTags = (useWatch({ control, name: `actions.${index}.userTags` }) ?? []) as Tag[]; + const roleTags = (useWatch({ control, name: `actions.${index}.roleTags` }) ?? []) as Tag[]; + const emailTags = (useWatch({ control, name: `actions.${index}.emailTags` }) ?? []) as Tag[]; + + return ( +
+ ( + + {t("alertingNotifyUsers")} + + { + const next = + typeof newTags === "function" + ? newTags(userTags) + : newTags; + form.setValue( + `actions.${index}.userTags`, + next as Tag[], + { shouldDirty: true } + ); + }} + enableAutocomplete={true} + autocompleteOptions={allUsers} + allowDuplicates={false} + restrictTagsToAutocompleteOptions={true} + sortTags={true} + /> + + + + )} + /> + ( + + {t("alertingNotifyRoles")} + + { + const next = + typeof newTags === "function" + ? newTags(roleTags) + : newTags; + form.setValue( + `actions.${index}.roleTags`, + next as Tag[], + { shouldDirty: true } + ); + }} + enableAutocomplete={true} + autocompleteOptions={allRoles} + allowDuplicates={false} + restrictTagsToAutocompleteOptions={true} + sortTags={true} + /> + + + + )} + /> + ( + + {t("alertingNotifyEmails")} + + { + const next = + typeof updater === "function" + ? updater(emailTags) + : updater; + form.setValue( + `actions.${index}.emailTags`, + next as Tag[], + { shouldDirty: true } + ); + }} + activeTagIndex={emailActiveIdx} + setActiveTagIndex={setEmailActiveIdx} + placeholder={t("alertingEmailPlaceholder")} + size="sm" + allowDuplicates={false} + sortTags={true} + validateTag={(tag) => + /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(tag) + } + delimiterList={[",", "Enter"]} + /> + + + + )} + /> +
+ ); +} + +function WebhookActionFields({ + index, + control, + form +}: { + index: number; + control: Control; + form: UseFormReturn; +}) { + const t = useTranslations(); + return ( +
+ ( + + URL + + + + + + )} + /> + ( + + {t("alertingWebhookMethod")} + + + + )} + /> + {/* Authentication */} +
+
+ +

+ {t("httpDestAuthDescription")} +

+
+ ( + + + + {/* None */} +
+ +
+ +

+ {t("httpDestAuthNoneDescription")} +

+
+
+ + {/* Bearer */} +
+ +
+
+ +

+ {t("httpDestAuthBearerDescription")} +

+
+ {field.value === "bearer" && ( + ( + + + + + + + )} + /> + )} +
+
+ + {/* Basic */} +
+ +
+
+ +

+ {t("httpDestAuthBasicDescription")} +

+
+ {field.value === "basic" && ( + ( + + + + + + + )} + /> + )} +
+
+ + {/* Custom */} +
+ +
+
+ +

+ {t("httpDestAuthCustomDescription")} +

+
+ {field.value === "custom" && ( +
+ ( + + + + + + + )} + /> + ( + + + + + + + )} + /> +
+ )} +
+
+
+
+ +
+ )} + /> +
+ +
+ ); +} + +function WebhookHeadersField({ + index, + control, + form +}: { + index: number; + control: Control; + form: UseFormReturn; +}) { + const t = useTranslations(); + const headers = + (useWatch({ control, name: `actions.${index}.headers` as const }) ?? []); + return ( +
+ {t("alertingWebhookHeaders")} + {headers.map((_, hi) => ( +
+ ( + + + + + + )} + /> + ( + + + + + + )} + /> + +
+ ))} + +
+ ); +} + +export function AlertRuleSourceFields({ + orgId, + control +}: { + orgId: string; + control: Control; +}) { + const t = useTranslations(); + const { setValue, getValues } = useFormContext(); + const sourceType = useWatch({ control, name: "sourceType" }); + const allSites = useWatch({ control, name: "allSites" }); + const allHealthChecks = useWatch({ control, name: "allHealthChecks" }); + const allResources = useWatch({ control, name: "allResources" }); + + const siteStrategyOptions = useMemo( + () => [ + { + id: "all" as const, + title: t("alertingAllSites"), + description: t("alertingAllSitesDescription") + }, + { + id: "specific" as const, + title: t("alertingSpecificSites"), + description: t("alertingSpecificSitesDescription") + } + ], + [t] + ); + + const healthCheckStrategyOptions = useMemo( + () => [ + { + id: "all" as const, + title: t("alertingAllHealthChecks"), + description: t("alertingAllHealthChecksDescription") + }, + { + id: "specific" as const, + title: t("alertingSpecificHealthChecks"), + description: t("alertingSpecificHealthChecksDescription") + } + ], + [t] + ); + + const resourceStrategyOptions = useMemo( + () => [ + { + id: "all" as const, + title: t("alertingAllResources"), + description: t("alertingAllResourcesDescription") + }, + { + id: "specific" as const, + title: t("alertingSpecificResources"), + description: t("alertingSpecificResourcesDescription") + } + ], + [t] + ); + + return ( +
+ ( + + {t("alertingSourceType")} + + + + )} + /> + {sourceType === "site" ? ( + <> + ( + + { + field.onChange(v === "all"); + if (v === "all") { + setValue("siteIds", []); + } + }} + cols={2} + /> + + + )} + /> + {!allSites && ( + ( + + + {t("alertingPickSites")} + + + + + )} + /> + )} + + ) : sourceType === "resource" ? ( + <> + ( + + { + field.onChange(v === "all"); + if (v === "all") { + setValue("resourceIds", []); + } + }} + cols={2} + /> + + + )} + /> + {!allResources && ( + ( + + + {t("alertingPickResources")} + + + + + )} + /> + )} + + ) : ( + <> + ( + + { + field.onChange(v === "all"); + if (v === "all") { + setValue("healthCheckIds", []); + } + }} + cols={2} + /> + + + )} + /> + {!allHealthChecks && ( + ( + + + {t("alertingPickHealthChecks")} + + + + + )} + /> + )} + + )} +
+ ); +} + +export function AlertRuleTriggerFields({ + control +}: { + control: Control; +}) { + const t = useTranslations(); + const sourceType = useWatch({ control, name: "sourceType" }); + return ( + ( + + {t("alertingTrigger")} + + + + )} + /> + ); +} diff --git a/src/components/alert-rule-editor/AlertRuleGraphEditor.tsx b/src/components/alert-rule-editor/AlertRuleGraphEditor.tsx new file mode 100644 index 000000000..c41cf32bd --- /dev/null +++ b/src/components/alert-rule-editor/AlertRuleGraphEditor.tsx @@ -0,0 +1,417 @@ +"use client"; + +import { + ActionBlock, + AddActionPanel, + AlertRuleSourceFields, + AlertRuleTriggerFields +} from "@app/components/alert-rule-editor/AlertRuleFields"; +import { SettingsContainer } from "@app/components/Settings"; +import { Button } from "@app/components/ui/button"; +import { Card, CardContent } from "@app/components/ui/card"; +import { + Form, + FormControl, + FormDescription, + FormField, + FormItem, + FormLabel, + FormMessage +} from "@app/components/ui/form"; +import { Input } from "@app/components/ui/input"; +import { toast } from "@app/hooks/useToast"; +import { + buildFormSchema, + defaultFormValues, + formValuesToApiPayload, + type AlertRuleFormValues +} from "@app/lib/alertRuleForm"; +import { createApiClient, formatAxiosError } from "@app/lib/api"; +import { useEnvContext } from "@app/hooks/useEnvContext"; +import type { CreateAlertRuleResponse } from "@server/private/routers/alertRule"; +import type { AxiosResponse } from "axios"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { ChevronLeft, Cog, Flag, Zap } from "lucide-react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useMemo, useState, type ReactNode } from "react"; +import { useFieldArray, useForm, type Resolver } from "react-hook-form"; +import { useTranslations } from "next-intl"; +import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert"; +import { SwitchInput } from "@app/components/SwitchInput"; +import { tierMatrix } from "@server/lib/billing/tierMatrix"; +import { Badge } from "../ui/badge"; + +const FORM_ID = "alert-rule-form"; + +type StepAccent = { + labelClass: string; + icon: typeof Flag; +}; + +type AlertRuleGraphEditorProps = { + orgId: string; + alertRuleId?: number; + initialValues: AlertRuleFormValues; + isNew: boolean; + disabled?: boolean; +}; + +function VerticalRuleStep({ + stepNumber, + isLast, + title, + accent, + children +}: { + stepNumber: number; + isLast: boolean; + title: string; + accent: StepAccent; + children: ReactNode; +}) { + const Icon = accent.icon; + return ( +
  • +
    +
    + {stepNumber} +
    + {!isLast && ( +
    + )} +
    +
    +
    + + {title} +
    +
    + {children} +
    +
    +
  • + ); +} + +export default function AlertRuleGraphEditor({ + orgId, + alertRuleId, + initialValues, + isNew, + disabled = false +}: AlertRuleGraphEditorProps) { + const t = useTranslations(); + const router = useRouter(); + const api = createApiClient(useEnvContext()); + const [isSaving, setIsSaving] = useState(false); + const schema = useMemo(() => buildFormSchema(t), [t]); + const form = useForm({ + resolver: zodResolver(schema) as Resolver, + defaultValues: initialValues ?? defaultFormValues() + }); + + const { fields, append, remove, update } = useFieldArray({ + control: form.control, + name: "actions" + }); + + const onSubmit = form.handleSubmit(async (values) => { + setIsSaving(true); + try { + const payload = formValuesToApiPayload(values); + if (isNew) { + const res = await api.put< + AxiosResponse + >(`/org/${orgId}/alert-rule`, payload); + toast({ + title: t("alertingRuleSaved"), + description: t("alertingRuleSavedCreatedDescription") + }); + router.replace( + `/${orgId}/settings/alerting/${res.data.data.alertRuleId}` + ); + } else { + await api.post( + `/org/${orgId}/alert-rule/${alertRuleId}`, + payload + ); + toast({ + title: t("alertingRuleSaved"), + description: t("alertingRuleSavedUpdatedDescription") + }); + } + } catch (e) { + toast({ + title: t("error"), + description: formatAxiosError(e), + variant: "destructive" + }); + } finally { + setIsSaving(false); + } + }); + + return ( + + + + +
    + + +
    +
      + +
      + +
      +
      + +
      + +
      +
      + +
      +
      + { + if (type === "notify") { + append({ + type: "notify", + userTags: [], + roleTags: [], + emailTags: [] + }); + } else { + append({ + type: "webhook", + url: "", + method: "POST", + headers: [ + { + key: "", + value: "" + } + ], + authType: "none", + bearerToken: "", + basicCredentials: + "", + customHeaderName: + "", + customHeaderValue: + "" + }); + } + }} + /> + {fields.length > 0 && ( +
      + )} + {fields.map((f, index) => ( +
      + {index > 0 && ( +
      + )} + + remove(index) + } + onUpdate={(val) => + update(index, val) + } + canRemove + /> +
      + ))} +
      +
      +
      +
    +
    +
    +
    + + + ); +} diff --git a/src/components/machines-selector.tsx b/src/components/machines-selector.tsx index 9c31a0bd3..99515135e 100644 --- a/src/components/machines-selector.tsx +++ b/src/components/machines-selector.tsx @@ -3,18 +3,9 @@ import type { ListClientsResponse } from "@server/routers/client"; import { useQuery } from "@tanstack/react-query"; import { useMemo, useState } from "react"; import { useDebounce } from "use-debounce"; -import { - Command, - CommandEmpty, - CommandGroup, - CommandInput, - CommandItem, - CommandList -} from "./ui/command"; -import { cn } from "@app/lib/cn"; -import { CheckIcon } from "lucide-react"; import { useTranslations } from "next-intl"; +import { MultiSelectTags } from "./multi-select-tags"; export type SelectedMachine = Pick< ListClientsResponse["clients"][number], @@ -57,52 +48,71 @@ export function MachinesSelector({ return allMachines; }, [machines, selectedMachines, debouncedValue]); - const selectedMachinesIds = new Set( - selectedMachines.map((m) => m.clientId) - ); + // const selectedMachinesIds = new Set( + // selectedMachines.map((m) => m.clientId) + // ); return ( - - - - {t("machineNotFound")} - - {machinesShown.map((m) => ( - { - let newMachineClients = []; - if (selectedMachinesIds.has(m.clientId)) { - newMachineClients = selectedMachines.filter( - (mc) => mc.clientId !== m.clientId - ); - } else { - newMachineClients = [ - ...selectedMachines, - m - ]; - } - onSelectMachines(newMachineClients); - }} - > - - {`${m.name}`} - - ))} - - - + ({ + ...m, + text: m.name, + id: m.clientId.toString() + }))} + onChange={(values) => { + onSelectMachines(values); + }} + options={machinesShown.map((m) => ({ + ...m, + id: m.clientId.toString(), + text: m.name + }))} + onSearch={setMachineSearchQuery} + searchQuery={machineSearchQuery} + /> + // + // + // + // {t("machineNotFound")} + // + // {machinesShown.map((m) => ( + // { + // let newMachineClients = []; + // if (selectedMachinesIds.has(m.clientId)) { + // newMachineClients = selectedMachines.filter( + // (mc) => mc.clientId !== m.clientId + // ); + // } else { + // newMachineClients = [ + // ...selectedMachines, + // m + // ]; + // } + // onSelectMachines(newMachineClients); + // }} + // > + // + // {`${m.name}`} + // + // ))} + // + // + // ); } diff --git a/src/components/multi-select-tags.tsx b/src/components/multi-select-tags.tsx new file mode 100644 index 000000000..2fb9b097d --- /dev/null +++ b/src/components/multi-select-tags.tsx @@ -0,0 +1,77 @@ +import type { Ref } from "react"; +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList +} from "./ui/command"; +import { cn } from "@app/lib/cn"; +import { CheckIcon } from "lucide-react"; + +export type TagValue = { text: string; id: string }; + +export type MultiSelectTagsProps = { + emptyPlaceholder: string; + searchPlaceholder: string; + searchQuery?: string; + options: Array; + value: Array; + onChange: (newValue: Array) => void; + onSearch: (query: string) => void; + ref?: Ref; +}; + +export function MultiSelectTags({ + emptyPlaceholder, + searchPlaceholder, + searchQuery, + value, + options, + onSearch, + onChange +}: MultiSelectTagsProps) { + const selectedValues = new Set(value.map((v) => v.id)); + return ( + + + + {emptyPlaceholder} + + {options.map((option) => ( + { + let newValues = []; + if (selectedValues.has(option.id)) { + newValues = value.filter( + (v) => v.id !== option.id + ); + } else { + newValues = [...value, option]; + } + onChange(newValues); + }} + > + + {`${option.text}`} + + ))} + + + + ); +} diff --git a/src/components/multi-site-selector.tsx b/src/components/multi-site-selector.tsx new file mode 100644 index 000000000..407e3b3e1 --- /dev/null +++ b/src/components/multi-site-selector.tsx @@ -0,0 +1,117 @@ +import { orgQueries } from "@app/lib/queries"; +import { useQuery } from "@tanstack/react-query"; +import { useMemo, useState } from "react"; +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList +} from "./ui/command"; +import { Checkbox } from "./ui/checkbox"; +import { useTranslations } from "next-intl"; +import { useDebounce } from "use-debounce"; +import type { Selectedsite } from "./site-selector"; + +export type MultiSitesSelectorProps = { + orgId: string; + selectedSites: Selectedsite[]; + onSelectionChange: (sites: Selectedsite[]) => void; + filterTypes?: string[]; +}; + +export function formatMultiSitesSelectorLabel( + selectedSites: Selectedsite[], + t: (key: string, values?: { count: number }) => string +): string { + if (selectedSites.length === 0) { + return t("selectSites"); + } + if (selectedSites.length === 1) { + return selectedSites[0]!.name; + } + return t("multiSitesSelectorSitesCount", { + count: selectedSites.length + }); +} + +export function MultiSitesSelector({ + orgId, + selectedSites, + onSelectionChange, + filterTypes +}: MultiSitesSelectorProps) { + const t = useTranslations(); + const [siteSearchQuery, setSiteSearchQuery] = useState(""); + const [debouncedQuery] = useDebounce(siteSearchQuery, 150); + + const { data: sites = [] } = useQuery( + orgQueries.sites({ + orgId, + query: debouncedQuery, + perPage: 10 + }) + ); + + const sitesShown = useMemo(() => { + const base = filterTypes + ? sites.filter((s) => filterTypes.includes(s.type)) + : [...sites]; + if (debouncedQuery.trim().length === 0 && selectedSites.length > 0) { + const selectedNotInBase = selectedSites.filter( + (sel) => !base.some((s) => s.siteId === sel.siteId) + ); + return [...selectedNotInBase, ...base]; + } + return base; + }, [debouncedQuery, sites, selectedSites, filterTypes]); + + const selectedIds = useMemo( + () => new Set(selectedSites.map((s) => s.siteId)), + [selectedSites] + ); + + const toggleSite = (site: Selectedsite) => { + if (selectedIds.has(site.siteId)) { + onSelectionChange( + selectedSites.filter((s) => s.siteId !== site.siteId) + ); + } else { + onSelectionChange([...selectedSites, site]); + } + }; + + return ( + + setSiteSearchQuery(v)} + /> + + {t("siteNotFound")} + + {sitesShown.map((site) => ( + { + toggleSite(site); + }} + > + {}} + aria-hidden + tabIndex={-1} + /> + {site.name} + + ))} + + + + ); +} diff --git a/src/components/resource-target-address-item.tsx b/src/components/resource-target-address-item.tsx index 851b64b54..c801844ce 100644 --- a/src/components/resource-target-address-item.tsx +++ b/src/components/resource-target-address-item.tsx @@ -12,14 +12,6 @@ import { useTranslations } from "next-intl"; import { useMemo, useState } from "react"; import { ContainersSelector } from "./ContainersSelector"; import { Button } from "./ui/button"; -import { - Command, - CommandEmpty, - CommandGroup, - CommandInput, - CommandItem, - CommandList -} from "./ui/command"; import { Input } from "./ui/input"; import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover"; import { Select, SelectContent, SelectItem, SelectTrigger } from "./ui/select"; @@ -212,6 +204,12 @@ export function ResourceTargetAddressItem({ proxyTarget.port === 0 ? "" : proxyTarget.port } className="w-18.75 px-2 border-none placeholder-gray-400 rounded-l-xs" + type="number" + onKeyDown={(e) => { + if (["e", "E", "+", "-", "."].includes(e.key)) { + e.preventDefault(); + } + }} onBlur={(e) => { const value = parseInt(e.target.value, 10); if (!isNaN(value) && value > 0) { @@ -227,6 +225,7 @@ export function ResourceTargetAddressItem({ } }} /> +
    ); diff --git a/src/components/tags/tag-input.tsx b/src/components/tags/tag-input.tsx index e8cfa370a..fafd2144f 100644 --- a/src/components/tags/tag-input.tsx +++ b/src/components/tags/tag-input.tsx @@ -1,8 +1,8 @@ "use client"; -import React from "react"; -import { Input } from "../ui/input"; -import { Button } from "../ui/button"; +import * as React from "react"; +import { Input } from "@app/components/ui/input"; +import { Button } from "@app/components/ui/button"; import { type VariantProps } from "class-variance-authority"; // import { CommandInput } from '../ui/command'; import { TagPopover } from "./tag-popover"; @@ -103,201 +103,89 @@ export interface TagInputProps addOnPaste?: boolean; addTagsOnBlur?: boolean; generateTagId?: () => string; + ref?: React.Ref; } -const TagInput = React.forwardRef( - (props, ref) => { - const { - id, - placeholder, - tags, - setTags, - variant, - size, - shape, - enableAutocomplete, - autocompleteOptions, - maxTags, - delimiter = Delimiter.Comma, - onTagAdd, - onTagRemove, - allowDuplicates, - showCount, - validateTag, - placeholderWhenFull = "Max tags reached", - sortTags, - delimiterList, - truncate, - autocompleteFilter, - borderStyle, - textCase, - interaction, - animation, - textStyle, - minLength, - maxLength, - direction = "row", - onInputChange, - customTagRenderer, - onFocus, - onBlur, - onTagClick, - draggable = false, - inputFieldPosition = "bottom", - clearAll = false, - onClearAll, - usePopoverForTags = false, - inputProps = {}, - restrictTagsToAutocompleteOptions, - inlineTags = true, - addTagsOnBlur = false, - activeTagIndex, - setActiveTagIndex, - styleClasses = {}, - disabled = false, - usePortal = false, - addOnPaste = false, - generateTagId = uuid - } = props; +export function TagInput({ ref, ...props }: TagInputProps) { + const { + id, + placeholder, + tags, + setTags, + variant, + size, + shape, + enableAutocomplete, + autocompleteOptions, + maxTags, + delimiter = Delimiter.Comma, + onTagAdd, + onTagRemove, + allowDuplicates, + showCount, + validateTag, + placeholderWhenFull = "Max tags reached", + sortTags, + delimiterList, + truncate, + autocompleteFilter, + borderStyle, + textCase, + interaction, + animation, + textStyle, + minLength, + maxLength, + direction = "row", + onInputChange, + customTagRenderer, + onFocus, + onBlur, + onTagClick, + draggable = false, + inputFieldPosition = "bottom", + clearAll = false, + onClearAll, + usePopoverForTags = false, + inputProps = {}, + restrictTagsToAutocompleteOptions, + inlineTags = true, + addTagsOnBlur = false, + activeTagIndex, + setActiveTagIndex, + styleClasses = {}, + disabled = false, + usePortal = false, + addOnPaste = false, + generateTagId = uuid + } = props; - const [inputValue, setInputValue] = React.useState(""); - const [tagCount, setTagCount] = React.useState( - Math.max(0, tags.length) - ); - const inputRef = React.useRef(null); + const [inputValue, setInputValue] = React.useState(""); + const [tagCount, setTagCount] = React.useState(Math.max(0, tags.length)); + const inputRef = React.useRef(null); - const t = useTranslations(); + const t = useTranslations(); - if ( - (maxTags !== undefined && maxTags < 0) || - (props.minTags !== undefined && props.minTags < 0) - ) { - console.warn(t("tagsWarnCannotBeLessThanZero")); - // error - return null; - } + if ( + (maxTags !== undefined && maxTags < 0) || + (props.minTags !== undefined && props.minTags < 0) + ) { + console.warn(t("tagsWarnCannotBeLessThanZero")); + // error + return null; + } - const handleInputChange = (e: React.ChangeEvent) => { - const newValue = e.target.value; - if (addOnPaste && newValue.includes(delimiter)) { - const splitValues = newValue - .split(delimiter) - .map((v) => v.trim()) - .filter((v) => v); - splitValues.forEach((value) => { - if (!value) return; // Skip empty strings from split + const handleInputChange = (e: React.ChangeEvent) => { + const newValue = e.target.value; + if (addOnPaste && newValue.includes(delimiter)) { + const splitValues = newValue + .split(delimiter) + .map((v) => v.trim()) + .filter((v) => v); + splitValues.forEach((value) => { + if (!value) return; // Skip empty strings from split - const newTagText = value.trim(); - - // Check if the tag is in the autocomplete options if restrictTagsToAutocomplete is true - if ( - restrictTagsToAutocompleteOptions && - !autocompleteOptions?.some( - (option) => option.text === newTagText - ) - ) { - console.warn( - t("tagsWarnNotAllowedAutocompleteOptions") - ); - return; - } - - if (validateTag && !validateTag(newTagText)) { - console.warn(t("tagsWarnInvalid")); - return; - } - - if (minLength && newTagText.length < minLength) { - console.warn( - t("tagWarnTooShort", { tagText: newTagText }) - ); - return; - } - - if (maxLength && newTagText.length > maxLength) { - console.warn( - t("tagWarnTooLong", { tagText: newTagText }) - ); - return; - } - - const newTagId = generateTagId(); - - // Add tag if duplicates are allowed or tag does not already exist - if ( - allowDuplicates || - !tags.some((tag) => tag.text === newTagText) - ) { - if (maxTags === undefined || tags.length < maxTags) { - // Check for maxTags limit - const newTag = { id: newTagId, text: newTagText }; - setTags((prevTags) => [...prevTags, newTag]); - onTagAdd?.(newTagText); - } else { - console.warn(t("tagsWarnReachedMaxNumber")); - } - } else { - console.warn( - t("tagWarnDuplicate", { tagText: newTagText }) - ); - } - }); - setInputValue(""); - } else { - setInputValue(newValue); - } - onInputChange?.(newValue); - }; - - const handleInputFocus = ( - event: React.FocusEvent - ) => { - setActiveTagIndex(null); // Reset active tag index when the input field gains focus - onFocus?.(event); - }; - - const handleInputBlur = (event: React.FocusEvent) => { - if (addTagsOnBlur && inputValue.trim()) { - const newTagText = inputValue.trim(); - - if (validateTag && !validateTag(newTagText)) { - return; - } - - if (minLength && newTagText.length < minLength) { - console.warn(t("tagWarnTooShort")); - return; - } - - if (maxLength && newTagText.length > maxLength) { - console.warn(t("tagWarnTooLong")); - return; - } - - if ( - (allowDuplicates || - !tags.some((tag) => tag.text === newTagText)) && - (maxTags === undefined || tags.length < maxTags) - ) { - const newTagId = generateTagId(); - setTags([...tags, { id: newTagId, text: newTagText }]); - onTagAdd?.(newTagText); - setTagCount((prevTagCount) => prevTagCount + 1); - setInputValue(""); - } - } - - onBlur?.(event); - }; - - const handleKeyDown = (e: React.KeyboardEvent) => { - if ( - delimiterList - ? delimiterList.includes(e.key) - : e.key === delimiter || e.key === Delimiter.Enter - ) { - e.preventDefault(); - const newTagText = inputValue.trim(); + const newTagText = value.trim(); // Check if the tag is in the autocomplete options if restrictTagsToAutocomplete is true if ( @@ -306,189 +194,442 @@ const TagInput = React.forwardRef( (option) => option.text === newTagText ) ) { - // error + console.warn(t("tagsWarnNotAllowedAutocompleteOptions")); return; } if (validateTag && !validateTag(newTagText)) { + console.warn(t("tagsWarnInvalid")); return; } if (minLength && newTagText.length < minLength) { - console.warn(t("tagWarnTooShort")); - // error + console.warn(t("tagWarnTooShort", { tagText: newTagText })); return; } - // Validate maxLength if (maxLength && newTagText.length > maxLength) { - // error - console.warn(t("tagWarnTooLong")); + console.warn(t("tagWarnTooLong", { tagText: newTagText })); return; } const newTagId = generateTagId(); + // Add tag if duplicates are allowed or tag does not already exist if ( - newTagText && - (allowDuplicates || - !tags.some((tag) => tag.text === newTagText)) && - (maxTags === undefined || tags.length < maxTags) + allowDuplicates || + !tags.some((tag) => tag.text === newTagText) ) { - setTags([...tags, { id: newTagId, text: newTagText }]); - onTagAdd?.(newTagText); - setTagCount((prevTagCount) => prevTagCount + 1); + if (maxTags === undefined || tags.length < maxTags) { + // Check for maxTags limit + const newTag = { id: newTagId, text: newTagText }; + setTags((prevTags) => [...prevTags, newTag]); + onTagAdd?.(newTagText); + } else { + console.warn(t("tagsWarnReachedMaxNumber")); + } + } else { + console.warn( + t("tagWarnDuplicate", { tagText: newTagText }) + ); } - setInputValue(""); - } else { - switch (e.key) { - case "Delete": - if (activeTagIndex !== null) { - e.preventDefault(); - const newTags = [...tags]; - newTags.splice(activeTagIndex, 1); - setTags(newTags); - setActiveTagIndex((prev) => - newTags.length === 0 - ? null - : prev! >= newTags.length - ? newTags.length - 1 - : prev - ); - setTagCount((prevTagCount) => prevTagCount - 1); - onTagRemove?.(tags[activeTagIndex].text); - } - break; - case "Backspace": - if (activeTagIndex !== null) { - e.preventDefault(); - const newTags = [...tags]; - newTags.splice(activeTagIndex, 1); - setTags(newTags); - setActiveTagIndex((prev) => - prev! === 0 ? null : prev! - 1 - ); - setTagCount((prevTagCount) => prevTagCount - 1); - onTagRemove?.(tags[activeTagIndex].text); - } - break; - case "ArrowRight": - e.preventDefault(); - if (activeTagIndex === null) { - setActiveTagIndex(0); - } else { - setActiveTagIndex((prev) => - prev! + 1 >= tags.length ? 0 : prev! + 1 - ); - } - break; - case "ArrowLeft": - e.preventDefault(); - if (activeTagIndex === null) { - setActiveTagIndex(tags.length - 1); - } else { - setActiveTagIndex((prev) => - prev! === 0 ? tags.length - 1 : prev! - 1 - ); - } - break; - case "Home": - e.preventDefault(); - setActiveTagIndex(0); - break; - case "End": - e.preventDefault(); - setActiveTagIndex(tags.length - 1); - break; - } - } - }; - - const removeTag = (idToRemove: string) => { - setTags(tags.filter((tag) => tag.id !== idToRemove)); - onTagRemove?.( - tags.find((tag) => tag.id === idToRemove)?.text || "" - ); - setTagCount((prevTagCount) => prevTagCount - 1); - }; - - const onSortEnd = (oldIndex: number, newIndex: number) => { - setTags((currentTags) => { - const newTags = [...currentTags]; - const [removedTag] = newTags.splice(oldIndex, 1); - newTags.splice(newIndex, 0, removedTag); - - return newTags; }); - }; + setInputValue(""); + } else { + setInputValue(newValue); + } + onInputChange?.(newValue); + }; - const handleClearAll = () => { - if (!onClearAll) { - setActiveTagIndex(-1); - setTags([]); + const handleInputFocus = (event: React.FocusEvent) => { + setActiveTagIndex(null); // Reset active tag index when the input field gains focus + onFocus?.(event); + }; + + const handleInputBlur = (event: React.FocusEvent) => { + if (addTagsOnBlur && inputValue.trim()) { + const newTagText = inputValue.trim(); + + if (validateTag && !validateTag(newTagText)) { return; } - onClearAll?.(); - }; - // const filteredAutocompleteOptions = autocompleteFilter - // ? autocompleteOptions?.filter((option) => autocompleteFilter(option.text)) - // : autocompleteOptions; - const displayedTags = sortTags ? [...tags].sort() : tags; + if (minLength && newTagText.length < minLength) { + console.warn(t("tagWarnTooShort")); + return; + } - const truncatedTags = truncate - ? tags.map((tag) => ({ - id: tag.id, - text: - tag.text?.length > truncate - ? `${tag.text.substring(0, truncate)}...` - : tag.text - })) - : displayedTags; + if (maxLength && newTagText.length > maxLength) { + console.warn(t("tagWarnTooLong")); + return; + } - return ( -
    0 ? "gap-3" : ""} ${ - inputFieldPosition === "bottom" - ? "flex-col" - : inputFieldPosition === "top" - ? "flex-col-reverse" - : "flex-row" - }`} - > - {!usePopoverForTags && - (!inlineTags ? ( - - ) : ( - !enableAutocomplete && ( -
    + if ( + (allowDuplicates || + !tags.some((tag) => tag.text === newTagText)) && + (maxTags === undefined || tags.length < maxTags) + ) { + const newTagId = generateTagId(); + setTags([...tags, { id: newTagId, text: newTagText }]); + onTagAdd?.(newTagText); + setTagCount((prevTagCount) => prevTagCount + 1); + setInputValue(""); + } + } + + onBlur?.(event); + }; + + const handleKeyDown = (e: React.KeyboardEvent) => { + if ( + delimiterList + ? delimiterList.includes(e.key) + : e.key === delimiter || e.key === Delimiter.Enter + ) { + e.preventDefault(); + const newTagText = inputValue.trim(); + + // Check if the tag is in the autocomplete options if restrictTagsToAutocomplete is true + if ( + restrictTagsToAutocompleteOptions && + !autocompleteOptions?.some( + (option) => option.text === newTagText + ) + ) { + // error + return; + } + + if (validateTag && !validateTag(newTagText)) { + return; + } + + if (minLength && newTagText.length < minLength) { + console.warn(t("tagWarnTooShort")); + // error + return; + } + + // Validate maxLength + if (maxLength && newTagText.length > maxLength) { + // error + console.warn(t("tagWarnTooLong")); + return; + } + + const newTagId = generateTagId(); + + if ( + newTagText && + (allowDuplicates || + !tags.some((tag) => tag.text === newTagText)) && + (maxTags === undefined || tags.length < maxTags) + ) { + setTags([...tags, { id: newTagId, text: newTagText }]); + onTagAdd?.(newTagText); + setTagCount((prevTagCount) => prevTagCount + 1); + } + setInputValue(""); + } else { + switch (e.key) { + case "Delete": + if (activeTagIndex !== null) { + e.preventDefault(); + const newTags = [...tags]; + newTags.splice(activeTagIndex, 1); + setTags(newTags); + setActiveTagIndex((prev) => + newTags.length === 0 + ? null + : prev! >= newTags.length + ? newTags.length - 1 + : prev + ); + setTagCount((prevTagCount) => prevTagCount - 1); + onTagRemove?.(tags[activeTagIndex].text); + } + break; + case "Backspace": + if (activeTagIndex !== null) { + e.preventDefault(); + const newTags = [...tags]; + newTags.splice(activeTagIndex, 1); + setTags(newTags); + setActiveTagIndex((prev) => + prev! === 0 ? null : prev! - 1 + ); + setTagCount((prevTagCount) => prevTagCount - 1); + onTagRemove?.(tags[activeTagIndex].text); + } + break; + case "ArrowRight": + e.preventDefault(); + if (activeTagIndex === null) { + setActiveTagIndex(0); + } else { + setActiveTagIndex((prev) => + prev! + 1 >= tags.length ? 0 : prev! + 1 + ); + } + break; + case "ArrowLeft": + e.preventDefault(); + if (activeTagIndex === null) { + setActiveTagIndex(tags.length - 1); + } else { + setActiveTagIndex((prev) => + prev! === 0 ? tags.length - 1 : prev! - 1 + ); + } + break; + case "Home": + e.preventDefault(); + setActiveTagIndex(0); + break; + case "End": + e.preventDefault(); + setActiveTagIndex(tags.length - 1); + break; + } + } + }; + + const removeTag = (idToRemove: string) => { + setTags(tags.filter((tag) => tag.id !== idToRemove)); + onTagRemove?.(tags.find((tag) => tag.id === idToRemove)?.text || ""); + setTagCount((prevTagCount) => prevTagCount - 1); + }; + + const onSortEnd = (oldIndex: number, newIndex: number) => { + setTags((currentTags) => { + const newTags = [...currentTags]; + const [removedTag] = newTags.splice(oldIndex, 1); + newTags.splice(newIndex, 0, removedTag); + + return newTags; + }); + }; + + const handleClearAll = () => { + if (!onClearAll) { + setActiveTagIndex(-1); + setTags([]); + return; + } + onClearAll?.(); + }; + + // const filteredAutocompleteOptions = autocompleteFilter + // ? autocompleteOptions?.filter((option) => autocompleteFilter(option.text)) + // : autocompleteOptions; + const displayedTags = sortTags ? [...tags].sort() : tags; + + const truncatedTags = truncate + ? tags.map((tag) => ({ + id: tag.id, + text: + tag.text?.length > truncate + ? `${tag.text.substring(0, truncate)}...` + : tag.text + })) + : displayedTags; + + return ( +
    0 ? "gap-3" : ""} ${ + inputFieldPosition === "bottom" + ? "flex-col" + : inputFieldPosition === "top" + ? "flex-col-reverse" + : "flex-row" + }`} + > + {!usePopoverForTags && + (!inlineTags ? ( + + ) : ( + !enableAutocomplete && ( +
    +
    + + = maxTags + ? placeholderWhenFull + : placeholder + } + value={inputValue} + onChange={handleInputChange} + onKeyDown={handleKeyDown} + onFocus={handleInputFocus} + onBlur={handleInputBlur} + {...inputProps} + className={cn( + "border-0 px-0 h-5 bg-transparent focus-visible:ring-0 focus-visible:ring-transparent focus-visible:ring-offset-0 flex-1 w-fit shadow-none inset-shadow-none", + // className, + styleClasses?.input + )} + autoComplete={ + enableAutocomplete ? "on" : "off" + } + list={ + enableAutocomplete + ? "autocomplete-options" + : undefined + } + disabled={ + disabled || + (maxTags !== undefined && + tags.length >= maxTags) + } + /> +
    +
    + ) + ))} + {enableAutocomplete ? ( +
    + + {!usePopoverForTags ? ( + !inlineTags ? ( + // = maxTags ? placeholderWhenFull : placeholder} + // ref={inputRef} + // value={inputValue} + // disabled={disabled || (maxTags !== undefined && tags.length >= maxTags)} + // onChangeCapture={handleInputChange} + // onKeyDown={handleKeyDown} + // onFocus={handleInputFocus} + // onBlur={handleInputBlur} + // className={cn( + // 'w-full', + // // className, + // styleClasses?.input, + // )} + // /> + = maxTags + ? placeholderWhenFull + : placeholder + } + value={inputValue} + onChange={handleInputChange} + onKeyDown={handleKeyDown} + onFocus={handleInputFocus} + onBlur={handleInputBlur} + {...inputProps} + className={cn( + "border-0 h-5 bg-transparent focus-visible:ring-0 focus-visible:ring-transparent focus-visible:ring-offset-0 flex-1 w-fit shadow-none inset-shadow-none", + // className, + styleClasses?.input + )} + autoComplete={ + enableAutocomplete ? "on" : "off" + } + list={ + enableAutocomplete + ? "autocomplete-options" + : undefined + } + disabled={ + disabled || + (maxTags !== undefined && + tags.length >= maxTags) + } + /> + ) : (
    @@ -518,6 +659,22 @@ const TagInput = React.forwardRef( }} disabled={disabled} /> + {/* = maxTags ? placeholderWhenFull : placeholder} + ref={inputRef} + value={inputValue} + disabled={disabled || (maxTags !== undefined && tags.length >= maxTags)} + onChangeCapture={handleInputChange} + onKeyDown={handleKeyDown} + onFocus={handleInputFocus} + onBlur={handleInputBlur} + inlineTags={inlineTags} + className={cn( + 'border-0 flex-1 w-fit h-5', + // className, + styleClasses?.input, + )} + /> */} ( onBlur={handleInputBlur} {...inputProps} className={cn( - "border-0 h-5 bg-transparent focus-visible:ring-0 focus-visible:ring-transparent focus-visible:ring-offset-0 flex-1 w-fit shadow-none inset-shadow-none", + "border-0 px-0 h-5 bg-transparent focus-visible:ring-0 focus-visible:ring-transparent focus-visible:ring-offset-0 flex-1 w-fit shadow-none inset-shadow-none", // className, styleClasses?.input )} @@ -554,304 +711,7 @@ const TagInput = React.forwardRef( } />
    -
    - ) - ))} - {enableAutocomplete ? ( -
    - - {!usePopoverForTags ? ( - !inlineTags ? ( - // = maxTags ? placeholderWhenFull : placeholder} - // ref={inputRef} - // value={inputValue} - // disabled={disabled || (maxTags !== undefined && tags.length >= maxTags)} - // onChangeCapture={handleInputChange} - // onKeyDown={handleKeyDown} - // onFocus={handleInputFocus} - // onBlur={handleInputBlur} - // className={cn( - // 'w-full', - // // className, - // styleClasses?.input, - // )} - // /> - = maxTags - ? placeholderWhenFull - : placeholder - } - value={inputValue} - onChange={handleInputChange} - onKeyDown={handleKeyDown} - onFocus={handleInputFocus} - onBlur={handleInputBlur} - {...inputProps} - className={cn( - "border-0 h-5 bg-transparent focus-visible:ring-0 focus-visible:ring-transparent focus-visible:ring-offset-0 flex-1 w-fit shadow-none inset-shadow-none", - // className, - styleClasses?.input - )} - autoComplete={ - enableAutocomplete ? "on" : "off" - } - list={ - enableAutocomplete - ? "autocomplete-options" - : undefined - } - disabled={ - disabled || - (maxTags !== undefined && - tags.length >= maxTags) - } - /> - ) : ( -
    - - {/* = maxTags ? placeholderWhenFull : placeholder} - ref={inputRef} - value={inputValue} - disabled={disabled || (maxTags !== undefined && tags.length >= maxTags)} - onChangeCapture={handleInputChange} - onKeyDown={handleKeyDown} - onFocus={handleInputFocus} - onBlur={handleInputBlur} - inlineTags={inlineTags} - className={cn( - 'border-0 flex-1 w-fit h-5', - // className, - styleClasses?.input, - )} - /> */} - = maxTags - ? placeholderWhenFull - : placeholder - } - value={inputValue} - onChange={handleInputChange} - onKeyDown={handleKeyDown} - onFocus={handleInputFocus} - onBlur={handleInputBlur} - {...inputProps} - className={cn( - "border-0 h-5 bg-transparent focus-visible:ring-0 focus-visible:ring-transparent focus-visible:ring-offset-0 flex-1 w-fit shadow-none inset-shadow-none", - // className, - styleClasses?.input - )} - autoComplete={ - enableAutocomplete - ? "on" - : "off" - } - list={ - enableAutocomplete - ? "autocomplete-options" - : undefined - } - disabled={ - disabled || - (maxTags !== undefined && - tags.length >= maxTags) - } - /> -
    - ) - ) : ( - - {/* = maxTags ? placeholderWhenFull : placeholder} - ref={inputRef} - value={inputValue} - disabled={disabled || (maxTags !== undefined && tags.length >= maxTags)} - onChangeCapture={handleInputChange} - onKeyDown={handleKeyDown} - onFocus={handleInputFocus} - onBlur={handleInputBlur} - className={cn( - 'w-full', - // className, - styleClasses?.input, - )} - /> */} - = maxTags - ? placeholderWhenFull - : placeholder - } - value={inputValue} - onChange={handleInputChange} - onKeyDown={handleKeyDown} - onFocus={handleInputFocus} - onBlur={handleInputBlur} - {...inputProps} - className={cn( - "border-0 h-5 bg-transparent focus-visible:ring-0 focus-visible:ring-transparent focus-visible:ring-offset-0 flex-1 w-fit shadow-none inset-shadow-none", - // className, - styleClasses?.input - )} - autoComplete={ - enableAutocomplete ? "on" : "off" - } - list={ - enableAutocomplete - ? "autocomplete-options" - : undefined - } - disabled={ - disabled || - (maxTags !== undefined && - tags.length >= maxTags) - } - /> - - )} -
    -
    - ) : ( -
    - {!usePopoverForTags ? ( - !inlineTags ? ( - = maxTags - ? placeholderWhenFull - : placeholder - } - value={inputValue} - onChange={handleInputChange} - onKeyDown={handleKeyDown} - onFocus={handleInputFocus} - onBlur={handleInputBlur} - {...inputProps} - className={cn( - styleClasses?.input, - "shadow-none inset-shadow-none" - // className - )} - autoComplete={ - enableAutocomplete ? "on" : "off" - } - list={ - enableAutocomplete - ? "autocomplete-options" - : undefined - } - disabled={ - disabled || - (maxTags !== undefined && - tags.length >= maxTags) - } - /> - ) : null + ) ) : ( ( }} disabled={disabled} > + {/* = maxTags ? placeholderWhenFull : placeholder} + ref={inputRef} + value={inputValue} + disabled={disabled || (maxTags !== undefined && tags.length >= maxTags)} + onChangeCapture={handleInputChange} + onKeyDown={handleKeyDown} + onFocus={handleInputFocus} + onBlur={handleInputBlur} + className={cn( + 'w-full', + // className, + styleClasses?.input, + )} + /> */} ( onFocus={handleInputFocus} onBlur={handleInputBlur} {...inputProps} + className={cn( + "border-0 px-0 h-5 bg-transparent focus-visible:ring-0 focus-visible:ring-transparent focus-visible:ring-offset-0 flex-1 w-fit shadow-none inset-shadow-none", + // className, + styleClasses?.input + )} autoComplete={ enableAutocomplete ? "on" : "off" } @@ -907,42 +787,133 @@ const TagInput = React.forwardRef( (maxTags !== undefined && tags.length >= maxTags) } - className={cn( - "border-0 w-full shadow-none inset-shadow-none", - styleClasses?.input - // className - )} /> )} -
    - )} + +
    + ) : ( +
    + {!usePopoverForTags ? ( + !inlineTags ? ( + = maxTags + ? placeholderWhenFull + : placeholder + } + value={inputValue} + onChange={handleInputChange} + onKeyDown={handleKeyDown} + onFocus={handleInputFocus} + onBlur={handleInputBlur} + {...inputProps} + className={cn( + styleClasses?.input, + "shadow-none inset-shadow-none" + // className + )} + autoComplete={enableAutocomplete ? "on" : "off"} + list={ + enableAutocomplete + ? "autocomplete-options" + : undefined + } + disabled={ + disabled || + (maxTags !== undefined && + tags.length >= maxTags) + } + /> + ) : null + ) : ( + + = maxTags + ? placeholderWhenFull + : placeholder + } + value={inputValue} + onChange={handleInputChange} + onKeyDown={handleKeyDown} + onFocus={handleInputFocus} + onBlur={handleInputBlur} + {...inputProps} + autoComplete={enableAutocomplete ? "on" : "off"} + list={ + enableAutocomplete + ? "autocomplete-options" + : undefined + } + disabled={ + disabled || + (maxTags !== undefined && + tags.length >= maxTags) + } + className={cn( + "border-0 w-full shadow-none inset-shadow-none", + styleClasses?.input + // className + )} + /> + + )} +
    + )} - {showCount && maxTags && ( -
    - - {`${tagCount}`}/{`${maxTags}`} - -
    - )} - {clearAll && ( - - )} -
    - ); - } -); - -TagInput.displayName = "TagInput"; + {showCount && maxTags && ( +
    + + {`${tagCount}`}/{`${maxTags}`} + +
    + )} + {clearAll && ( + + )} +
    + ); +} export function uuid() { return crypto.getRandomValues(new Uint32Array(1))[0].toString(); } - -export { TagInput }; diff --git a/src/components/ui/badge.tsx b/src/components/ui/badge.tsx index 2b474f45b..d24788aff 100644 --- a/src/components/ui/badge.tsx +++ b/src/components/ui/badge.tsx @@ -4,7 +4,7 @@ import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@app/lib/cn"; const badgeVariants = cva( - "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors outline-none focus:outline-none focus-visible:outline-none focus-visible:ring-0", + "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs transition-colors outline-none focus:outline-none focus-visible:outline-none focus-visible:ring-0", { variants: { variant: { @@ -13,7 +13,7 @@ const badgeVariants = cva( outlinePrimary: "border-transparent bg-transparent border-primary text-primary", secondary: - "border-transparent bg-secondary text-secondary-foreground", + "bg-muted border text-secondary-foreground", destructive: "border-transparent bg-destructive text-destructive-foreground", outline: "text-foreground", diff --git a/src/components/ui/checkbox.tsx b/src/components/ui/checkbox.tsx index 261655bb0..5cffd8978 100644 --- a/src/components/ui/checkbox.tsx +++ b/src/components/ui/checkbox.tsx @@ -43,8 +43,8 @@ const Checkbox = React.forwardRef< className={cn(checkboxVariants({ variant }), className)} {...props} > - - + + )); diff --git a/src/components/ui/controlled-data-table.tsx b/src/components/ui/controlled-data-table.tsx index 1690d92a8..116ce644a 100644 --- a/src/components/ui/controlled-data-table.tsx +++ b/src/components/ui/controlled-data-table.tsx @@ -17,6 +17,7 @@ import { TableHeader, TableRow } from "@/components/ui/table"; +import { DataTableEmptyState } from "@/components/ui/data-table-empty-state"; import { DataTablePagination } from "@app/components/DataTablePagination"; import type { DataTableAddAction } from "@app/components/ui/data-table"; import { Button } from "@app/components/ui/button"; @@ -42,7 +43,7 @@ import { Search } from "lucide-react"; import { useTranslations } from "next-intl"; -import { useMemo, useState } from "react"; +import { useMemo, useState, type ReactNode } from "react"; // Extended ColumnDef type that includes optional friendlyName for column visibility dropdown export type ExtendedColumnDef = ColumnDef< @@ -84,6 +85,8 @@ type ControlledDataTableProps = { isNavigatingToAddPage?: boolean; searchPlaceholder?: string; filters?: DataTableFilter[]; + /** Extra filter controls (e.g. searchable entity pickers) shown after the filter dropdowns. */ + filterExtras?: ReactNode; filterDisplayMode?: "label" | "calculated"; // Global filter display mode (can be overridden per filter) columnVisibility?: Record; enableColumnVisibility?: boolean; @@ -108,6 +111,7 @@ export function ControlledDataTable({ refreshButtonDisabled = false, searchPlaceholder = "Search...", filters, + filterExtras, filterDisplayMode = "label", columnVisibility: defaultColumnVisibility, enableColumnVisibility = false, @@ -246,6 +250,38 @@ export function ControlledDataTable({ return ""; }; + const tableRows = table.getRowModel().rows; + const hasRows = tableRows.length > 0; + const hasAddAction = Boolean( + addButtonText && ((addActions && addActions.length > 0) || onAdd) + ); + const showAddActionInEmptyState = !hasRows && hasAddAction; + const addAction = addActions && addActions.length > 0 && addButtonText ? ( + + + + + + {addActions.map((action, i) => ( + action.onSelect()}> + {action.label} + + ))} + + + ) : onAdd && addButtonText ? ( + + ) : null; + return (
    @@ -343,6 +379,7 @@ export function ControlledDataTable({ })}
    )} + {filterExtras}
    {onRefresh && ( @@ -350,7 +387,9 @@ export function ControlledDataTable({
    )} - {addActions && addActions.length > 0 && addButtonText ? ( -
    - - - - - - {addActions.map((action, i) => ( - - action.onSelect() - } - > - {action.label} - - ))} - - -
    - ) : ( - onAdd && - addButtonText && ( -
    - -
    - ) + {addAction && ( + <> +
    {addAction}
    + {!showAddActionInEmptyState && ( +
    + {addAction} +
    + )} + )}
    @@ -598,14 +603,18 @@ export function ControlledDataTable({ )) ) : ( - - - No results found. - - + + {addAction} +
    + ) + : undefined + } + /> )} diff --git a/src/components/ui/data-table-empty-state.tsx b/src/components/ui/data-table-empty-state.tsx new file mode 100644 index 000000000..793c360f4 --- /dev/null +++ b/src/components/ui/data-table-empty-state.tsx @@ -0,0 +1,46 @@ +"use client"; + +import { TableCell, TableRow } from "@/components/ui/table"; +import { useTranslations } from "next-intl"; +import { type ReactNode } from "react"; + +const PLACEHOLDER_ROW_COUNT = 5; + +type DataTableEmptyStateProps = { + colSpan: number; + action?: ReactNode; +}; + +export function DataTableEmptyState({ + colSpan, + action +}: DataTableEmptyStateProps) { + const t = useTranslations(); + return ( + + +
    +
    + {Array.from({ length: PLACEHOLDER_ROW_COUNT }).map( + (_, i) => ( +
    + ) + )} +
    +
    +

    + {t("noResults")} +

    + {action} +
    +
    + + + ); +} diff --git a/src/components/ui/data-table.tsx b/src/components/ui/data-table.tsx index cf252f3ea..82aafe1f4 100644 --- a/src/components/ui/data-table.tsx +++ b/src/components/ui/data-table.tsx @@ -29,6 +29,7 @@ import { TableHeader, TableRow } from "@/components/ui/table"; +import { DataTableEmptyState } from "@/components/ui/data-table-empty-state"; import { Button } from "@app/components/ui/button"; import { useEffect, useMemo, useRef, useState } from "react"; import { Input } from "@app/components/ui/input"; @@ -199,6 +200,8 @@ type DataTableProps = { columnVisibility?: Record; enableColumnVisibility?: boolean; manualFiltering?: boolean; + /** When true, row order is controlled externally (e.g. server-side sorting). */ + manualSorting?: boolean; onSearch?: (input: string) => void; searchQuery?: string; pagination?: DataTablePaginationState; @@ -232,6 +235,7 @@ export function DataTable({ enableColumnVisibility = false, persistColumnVisibility = false, manualFiltering = false, + manualSorting = false, pagination: paginationState, stickyLeftColumn, onSearch, @@ -353,6 +357,7 @@ export function DataTable({ } : setPagination, manualFiltering, + manualSorting, manualPagination: Boolean(paginationState), pageCount: paginationState?.pageCount, initialState: { @@ -511,6 +516,36 @@ export function DataTable({ return ""; }; + const tableRows = table.getRowModel().rows; + const hasRows = tableRows.length > 0; + const hasAddAction = Boolean( + addButtonText && ((addActions && addActions.length > 0) || onAdd) + ); + const showAddActionInEmptyState = !hasRows && hasAddAction; + const addAction = addActions && addActions.length > 0 && addButtonText ? ( + + + + + + {addActions.map((action, i) => ( + action.onSelect()}> + {action.label} + + ))} + + + ) : onAdd && addButtonText ? ( + + ) : null; + return (
    @@ -647,45 +682,15 @@ export function DataTable({
    )} - {addActions && addActions.length > 0 && addButtonText ? ( -
    - - - - - - {addActions.map((action, i) => ( - - action.onSelect() - } - > - {action.label} - - ))} - - -
    - ) : ( - onAdd && - addButtonText && ( -
    - -
    - ) + {addAction && ( + <> +
    {addAction}
    + {!showAddActionInEmptyState && ( +
    + {addAction} +
    + )} + )}
    @@ -880,14 +885,18 @@ export function DataTable({
    )) ) : ( - - - No results found. - - + + {addAction} +
    + ) + : undefined + } + /> )} diff --git a/src/components/ui/progress-backwards.tsx b/src/components/ui/progress-backwards.tsx new file mode 100644 index 000000000..e2482f0e2 --- /dev/null +++ b/src/components/ui/progress-backwards.tsx @@ -0,0 +1,58 @@ +"use client"; + +import * as React from "react"; +import * as ProgressPrimitive from "@radix-ui/react-progress"; +import { cn } from "@app/lib/cn"; +import { cva, type VariantProps } from "class-variance-authority"; + +const progressVariants = cva( + "border relative h-2 w-full overflow-hidden rounded-full", + { + variants: { + variant: { + default: "bg-muted", + success: "bg-muted", + warning: "bg-muted", + danger: "bg-muted" + } + }, + defaultVariants: { + variant: "default" + } + } +); + +const indicatorVariants = cva("h-full w-full flex-1 transition-all", { + variants: { + variant: { + default: "bg-primary", + success: "bg-green-500", + warning: "bg-yellow-500", + danger: "bg-red-500" + } + }, + defaultVariants: { + variant: "default" + } +}); + +type ProgressProps = React.ComponentProps & + VariantProps; + +function ProgressBackwards({ className, value, variant, ...props }: ProgressProps) { + return ( + + + + ); +} + +export { ProgressBackwards }; \ No newline at end of file diff --git a/src/contexts/subscriptionStatusContext.ts b/src/contexts/subscriptionStatusContext.ts index 73503da4f..6ba30fe42 100644 --- a/src/contexts/subscriptionStatusContext.ts +++ b/src/contexts/subscriptionStatusContext.ts @@ -10,6 +10,10 @@ type SubscriptionStatusContextType = { subscribed: boolean; /** True when org has exceeded plan limits (sites, users, etc.). Only set when build === saas. */ limitsExceeded: boolean; + /** Unix timestamp (ms) when the trial expires, or null if not in trial. */ + trialExpiresAt: number | null; + /** True if the organization is currently in a trial period. */ + isTrial: boolean; }; const SubscriptionStatusContext = createContext< diff --git a/src/hooks/useSubscriptionStatusContext.ts b/src/hooks/useSubscriptionStatusContext.ts index 240168b10..59d6a6b9a 100644 --- a/src/hooks/useSubscriptionStatusContext.ts +++ b/src/hooks/useSubscriptionStatusContext.ts @@ -3,7 +3,7 @@ import { build } from "@server/build"; import { useContext } from "react"; export function useSubscriptionStatusContext() { - if (build == "oss") { + if (build != "saas") { return null; } const context = useContext(SubscriptionStatusContext); diff --git a/src/lib/alertRuleForm.ts b/src/lib/alertRuleForm.ts new file mode 100644 index 000000000..111487c48 --- /dev/null +++ b/src/lib/alertRuleForm.ts @@ -0,0 +1,503 @@ +import type { Tag } from "@app/components/tags/tag-input"; +import { z } from "zod"; + +// --------------------------------------------------------------------------- +// Shared primitive schemas +// --------------------------------------------------------------------------- + +export const tagSchema = z.object({ + id: z.string(), + text: z.string() +}); + +// --------------------------------------------------------------------------- +// Form-layer types +// NOTE: the form uses "health_check_unhealthy" internally; it maps to the +// backend's "health_check_unhealthy" at the API boundary. +// --------------------------------------------------------------------------- + +export type AlertTrigger = + | "site_online" + | "site_offline" + | "site_toggle" + | "health_check_healthy" + | "health_check_unhealthy" + | "health_check_toggle" + | "resource_healthy" + | "resource_unhealthy" + | "resource_toggle"; + +export type AlertRuleFormAction = + | { + type: "notify"; + userTags: Tag[]; + roleTags: Tag[]; + emailTags: Tag[]; + } + | { + type: "webhook"; + url: string; + method: string; + headers: { key: string; value: string }[]; + authType: "none" | "bearer" | "basic" | "custom"; + bearerToken: string; + basicCredentials: string; + customHeaderName: string; + customHeaderValue: string; + }; + +export type AlertRuleFormValues = { + name: string; + enabled: boolean; + cooldownSeconds: number; + sourceType: "site" | "health_check" | "resource"; + allSites: boolean; + siteIds: number[]; + allHealthChecks: boolean; + healthCheckIds: number[]; + allResources: boolean; + resourceIds: number[]; + trigger: AlertTrigger; + actions: AlertRuleFormAction[]; +}; + +// --------------------------------------------------------------------------- +// API boundary types +// --------------------------------------------------------------------------- + +export type AlertRuleApiPayload = { + name: string; + cooldownSeconds: number; + eventType: + | "site_online" + | "site_offline" + | "site_toggle" + | "health_check_healthy" + | "health_check_unhealthy" + | "health_check_toggle" + | "resource_healthy" + | "resource_unhealthy" + | "resource_toggle"; + enabled: boolean; + allSites: boolean; + siteIds: number[]; + allHealthChecks: boolean; + healthCheckIds: number[]; + allResources: boolean; + resourceIds: number[]; + userIds: string[]; + roleIds: number[]; + emails: string[]; + webhookActions: { + webhookUrl: string; + enabled: boolean; + config?: string; + }[]; +}; + +// Shape of what GET /org/:orgId/alert-rule/:alertRuleId returns +export type AlertRuleApiResponse = { + alertRuleId: number; + orgId: string; + name: string; + eventType: string; + enabled: boolean; + cooldownSeconds: number; + lastTriggeredAt: number | null; + createdAt: number; + updatedAt: number; + siteIds: number[]; + healthCheckIds: number[]; + resourceIds: number[]; + recipients: { + recipientId: number; + userId: string | null; + roleId: number | null; + email: string | null; + }[]; + webhookActions: { + webhookActionId: number; + webhookUrl: string; + enabled: boolean; + lastSentAt: number | null; + config: { + authType: string; + bearerToken?: string; + basicCredentials?: string; + customHeaderName?: string; + customHeaderValue?: string; + headers?: { key: string; value: string }[]; + method?: string; + } | null; + }[]; +}; + +// --------------------------------------------------------------------------- +// Zod form schema (for react-hook-form validation) +// --------------------------------------------------------------------------- + +export function buildFormSchema(t: (k: string) => string) { + return z + .object({ + name: z + .string() + .min(1, { message: t("alertingErrorNameRequired") }), + enabled: z.boolean(), + cooldownSeconds: z.number().int().nonnegative().default(0), + sourceType: z.enum(["site", "health_check", "resource"]), + allSites: z.boolean().default(true), + siteIds: z.array(z.number()).default([]), + allHealthChecks: z.boolean().default(true), + healthCheckIds: z.array(z.number()).default([]), + allResources: z.boolean().default(true), + resourceIds: z.array(z.number()).default([]), + trigger: z.enum([ + "site_online", + "site_offline", + "site_toggle", + "health_check_healthy", + "health_check_unhealthy", + "health_check_toggle", + "resource_healthy", + "resource_unhealthy", + "resource_toggle" + ]), + actions: z.array( + z.discriminatedUnion("type", [ + z.object({ + type: z.literal("notify"), + userTags: z.array(tagSchema), + roleTags: z.array(tagSchema), + emailTags: z.array(tagSchema) + }), + z.object({ + type: z.literal("webhook"), + url: z.string(), + method: z.string(), + headers: z.array( + z.object({ + key: z.string(), + value: z.string() + }) + ), + authType: z.enum(["none", "bearer", "basic", "custom"]), + bearerToken: z.string(), + basicCredentials: z.string(), + customHeaderName: z.string(), + customHeaderValue: z.string() + }) + ]) + ) + }) + .superRefine((val, ctx) => { + if (val.actions.length === 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t("alertingErrorActionsMin"), + path: ["actions"] + }); + } + if ( + val.sourceType === "site" && + !val.allSites && + val.siteIds.length === 0 + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t("alertingErrorPickSites"), + path: ["siteIds"] + }); + } + if ( + val.sourceType === "health_check" && + !val.allHealthChecks && + val.healthCheckIds.length === 0 + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t("alertingErrorPickHealthChecks"), + path: ["healthCheckIds"] + }); + } + if ( + val.sourceType === "resource" && + !val.allResources && + val.resourceIds.length === 0 + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t("alertingErrorPickResources"), + path: ["resourceIds"] + }); + } + const siteTriggers: AlertTrigger[] = [ + "site_online", + "site_offline", + "site_toggle" + ]; + const hcTriggers: AlertTrigger[] = [ + "health_check_healthy", + "health_check_unhealthy", + "health_check_toggle" + ]; + const resourceTriggers: AlertTrigger[] = [ + "resource_healthy", + "resource_unhealthy", + "resource_toggle" + ]; + if ( + val.sourceType === "site" && + !siteTriggers.includes(val.trigger) + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t("alertingErrorTriggerSite"), + path: ["trigger"] + }); + } + if ( + val.sourceType === "health_check" && + !hcTriggers.includes(val.trigger) + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t("alertingErrorTriggerHealth"), + path: ["trigger"] + }); + } + if ( + val.sourceType === "resource" && + !resourceTriggers.includes(val.trigger) + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t("alertingErrorTriggerResource"), + path: ["trigger"] + }); + } + val.actions.forEach((a, i) => { + if (a.type === "notify") { + if ( + a.userTags.length === 0 && + a.roleTags.length === 0 && + a.emailTags.length === 0 + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t("alertingErrorNotifyRecipients"), + path: ["actions", i, "userTags"] + }); + } + } + if (a.type === "webhook") { + try { + new URL(a.url.trim()); + } catch { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t("alertingErrorWebhookUrl"), + path: ["actions", i, "url"] + }); + } + } + }); + }); +} + +// --------------------------------------------------------------------------- +// defaultFormValues +// --------------------------------------------------------------------------- + +export function defaultFormValues(): AlertRuleFormValues { + return { + name: "", + enabled: true, + cooldownSeconds: 0, + sourceType: "site", + allSites: true, + siteIds: [], + allHealthChecks: true, + healthCheckIds: [], + allResources: true, + resourceIds: [], + trigger: "site_toggle", + actions: [] + }; +} + +// --------------------------------------------------------------------------- +// List/API row semantics: empty ID arrays mean "all" for that source kind +// --------------------------------------------------------------------------- + +export function alertRuleAllSitesSelected( + eventType: string, + siteIds: number[] +): boolean { + const siteEvent = + eventType === "site_online" || + eventType === "site_offline" || + eventType === "site_toggle"; + return siteEvent && siteIds.length === 0; +} + +export function alertRuleAllResourcesSelected( + eventType: string, + resourceIds: number[] | undefined +): boolean { + return eventType.startsWith("resource_") && (resourceIds?.length ?? 0) === 0; +} + +export function alertRuleAllHealthChecksSelected( + eventType: string, + healthCheckIds: number[] +): boolean { + if ( + eventType === "site_online" || + eventType === "site_offline" || + eventType === "site_toggle" || + eventType.startsWith("resource_") + ) { + return false; + } + return healthCheckIds.length === 0; +} + +// --------------------------------------------------------------------------- +// API response → form values +// --------------------------------------------------------------------------- + +export function apiResponseToFormValues( + rule: AlertRuleApiResponse +): AlertRuleFormValues { + const trigger = rule.eventType; + const sourceType = rule.eventType.startsWith("site_") + ? "site" + : rule.eventType.startsWith("resource_") + ? "resource" + : "health_check"; + + // Collect notify recipients into a single notify action (if any) + const userTags = rule.recipients + .filter((r) => r.userId != null) + .map((r) => ({ id: r.userId!, text: r.userId! })); + const roleTags = rule.recipients + .filter((r) => r.roleId != null) + .map((r) => ({ id: String(r.roleId!), text: String(r.roleId!) })); + const emailTags = rule.recipients + .filter((r) => r.email != null) + .map((r) => ({ id: r.email!, text: r.email! })); + + const actions: AlertRuleFormAction[] = []; + + if (userTags.length > 0 || roleTags.length > 0 || emailTags.length > 0) { + actions.push({ type: "notify", userTags, roleTags, emailTags }); + } + + // Each webhook action becomes its own form webhook action + for (const w of rule.webhookActions) { + const cfg = w.config; + actions.push({ + type: "webhook", + url: w.webhookUrl, + method: cfg?.method ?? "POST", + headers: cfg?.headers?.length + ? cfg.headers + : [{ key: "", value: "" }], + authType: + (cfg?.authType as "none" | "bearer" | "basic" | "custom") ?? + "none", + bearerToken: cfg?.bearerToken ?? "", + basicCredentials: cfg?.basicCredentials ?? "", + customHeaderName: cfg?.customHeaderName ?? "", + customHeaderValue: cfg?.customHeaderValue ?? "" + }); + } + + const allSites = alertRuleAllSitesSelected(rule.eventType, rule.siteIds); + const allHealthChecks = alertRuleAllHealthChecksSelected( + rule.eventType, + rule.healthCheckIds + ); + const allResources = alertRuleAllResourcesSelected( + rule.eventType, + rule.resourceIds + ); + + return { + name: rule.name, + enabled: rule.enabled, + cooldownSeconds: rule.cooldownSeconds ?? 0, + sourceType, + allSites, + siteIds: rule.siteIds, + allHealthChecks, + healthCheckIds: rule.healthCheckIds, + allResources, + resourceIds: rule.resourceIds ?? [], + trigger: trigger as AlertTrigger, + actions + }; +} + +// --------------------------------------------------------------------------- +// Form values → API payload +// --------------------------------------------------------------------------- + +export function formValuesToApiPayload( + values: AlertRuleFormValues +): AlertRuleApiPayload { + const eventType = values.trigger; + + // Collect all notify-type actions and merge their recipient lists + const allUserIds: string[] = []; + const allRoleIds: number[] = []; + const allEmails: string[] = []; + + const webhookActions: AlertRuleApiPayload["webhookActions"] = []; + + for (const action of values.actions) { + if (action.type === "notify") { + allUserIds.push(...action.userTags.map((t) => t.id)); + allRoleIds.push(...action.roleTags.map((t) => Number(t.id))); + allEmails.push( + ...action.emailTags.map((t) => t.text.trim()).filter(Boolean) + ); + } else if (action.type === "webhook") { + webhookActions.push({ + webhookUrl: action.url.trim(), + enabled: true, + config: JSON.stringify({ + authType: action.authType, + bearerToken: action.bearerToken || undefined, + basicCredentials: action.basicCredentials || undefined, + customHeaderName: action.customHeaderName || undefined, + customHeaderValue: action.customHeaderValue || undefined, + headers: action.headers.filter((h) => h.key.trim()), + method: action.method + }) + }); + } + } + + // Deduplicate + const uniqueUserIds = [...new Set(allUserIds)]; + const uniqueRoleIds: number[] = [...new Set(allRoleIds)]; + const uniqueEmails = [...new Set(allEmails)]; + + return { + name: values.name.trim(), + eventType, + enabled: values.enabled, + cooldownSeconds: values.cooldownSeconds, + allSites: values.allSites, + siteIds: values.allSites ? [] : values.siteIds, + allHealthChecks: values.allHealthChecks, + healthCheckIds: values.allHealthChecks ? [] : values.healthCheckIds, + allResources: values.allResources, + resourceIds: values.allResources ? [] : values.resourceIds, + userIds: uniqueUserIds, + roleIds: uniqueRoleIds, + emails: uniqueEmails, + webhookActions + }; +} diff --git a/src/lib/queries.ts b/src/lib/queries.ts index 2fd34e8ac..97515e796 100644 --- a/src/lib/queries.ts +++ b/src/lib/queries.ts @@ -1,12 +1,17 @@ import { build } from "@server/build"; import type { QueryRequestAnalyticsResponse } from "@server/routers/auditLogs"; import type { ListClientsResponse } from "@server/routers/client"; -import type { ListDomainsResponse } from "@server/routers/domain"; +import type { + ListDomainsResponse, + GetDNSRecordsResponse +} from "@server/routers/domain"; +import type { GetDomainResponse } from "@server/routers/domain/getDomain"; import type { GetResourceWhitelistResponse, ListResourceNamesResponse, ListResourcesResponse } from "@server/routers/resource"; +import type { ListAlertRulesResponse } from "@server/private/routers/alertRule"; import type { ListRolesResponse } from "@server/routers/role"; import type { ListSitesResponse } from "@server/routers/site"; import type { @@ -26,7 +31,8 @@ import type { AxiosResponse } from "axios"; import z from "zod"; import { remote } from "./api"; import { durationToMs } from "./durationToMs"; -import { wait } from "./wait"; +import { ListHealthChecksResponse } from "@server/routers/healthChecks/types"; +import { StatusHistoryResponse } from "@server/lib/statusHistory"; export type ProductUpdate = { link: string | null; @@ -155,7 +161,8 @@ export const orgQueries = { queryKey: ["ORG", orgId, "SITES", { query, perPage }] as const, queryFn: async ({ signal, meta }) => { const sp = new URLSearchParams({ - pageSize: perPage.toString() + pageSize: perPage.toString(), + status: "approved" }); if (query?.trim()) { @@ -229,6 +236,278 @@ export const orgQueries = { return res.data.data.resources; } + }), + + healthChecks: ({ + orgId, + perPage = 10_000 + }: { + orgId: string; + perPage?: number; + }) => + queryOptions({ + queryKey: ["ORG", orgId, "HEALTH_CHECKS", { perPage }] as const, + queryFn: async ({ signal, meta }) => { + const sp = new URLSearchParams({ + limit: perPage.toString(), + offset: "0" + }); + const res = await meta!.api.get< + AxiosResponse + >(`/org/${orgId}/health-checks?${sp.toString()}`, { signal }); + return res.data.data.healthChecks; + } + }), + + alertRules: ({ + orgId, + limit = 20, + offset = 0, + query, + siteId, + resourceId, + healthCheckId, + sortBy, + order, + enabled + }: { + orgId: string; + limit?: number; + offset?: number; + query?: string; + siteId?: number; + resourceId?: number; + healthCheckId?: number; + sortBy?: string; + order?: string; + enabled?: string; + }) => + queryOptions({ + queryKey: [ + "ORG", + orgId, + "ALERT_RULES", + { + limit, + offset, + query, + siteId, + resourceId, + healthCheckId, + sortBy, + order, + enabled + } + ] as const, + queryFn: async ({ signal, meta }) => { + const sp = new URLSearchParams(); + sp.set("limit", String(limit)); + sp.set("offset", String(offset)); + if (query) sp.set("query", query); + if (siteId != null) sp.set("siteId", String(siteId)); + if (resourceId != null) + sp.set("resourceId", String(resourceId)); + if (healthCheckId != null) + sp.set("healthCheckId", String(healthCheckId)); + if (sortBy) { + sp.set("sort_by", sortBy); + if (order) sp.set("order", order); + } + if (enabled) sp.set("enabled", enabled); + const res = await meta!.api.get< + AxiosResponse + >(`/org/${orgId}/alert-rules?${sp.toString()}`, { signal }); + return { + alertRules: res.data.data.alertRules, + pagination: res.data.data.pagination + }; + } + }), + + alertRulesForSource: ({ + orgId, + siteId, + resourceId, + healthCheckId + }: { + orgId: string; + siteId?: number; + resourceId?: number; + healthCheckId?: number; + }) => + queryOptions({ + queryKey: [ + "ORG", + orgId, + "ALERT_RULES", + { siteId, resourceId, healthCheckId } + ] as const, + queryFn: async ({ signal, meta }) => { + const sp = new URLSearchParams(); + if (siteId != null && siteId !== undefined) + sp.set("siteId", String(siteId)); + if (resourceId != null && resourceId !== undefined) + sp.set("resourceId", String(resourceId)); + if (healthCheckId != null && healthCheckId !== undefined) + sp.set("healthCheckId", String(healthCheckId)); + const res = await meta!.api.get< + AxiosResponse + >(`/org/${orgId}/alert-rules?${sp.toString()}`, { signal }); + return res.data.data.alertRules; + } + }), + + standaloneHealthChecks: ({ + orgId, + limit = 20, + offset = 0, + query, + hcMode, + siteId, + resourceId, + hcHealth, + hcEnabled + }: { + orgId: string; + limit?: number; + offset?: number; + query?: string; + hcMode?: "http" | "tcp" | "snmp" | "ping"; + siteId?: number; + resourceId?: number; + hcHealth?: "healthy" | "unhealthy" | "unknown"; + hcEnabled?: "true" | "false"; + }) => + queryOptions({ + queryKey: [ + "ORG", + orgId, + "STANDALONE_HEALTH_CHECKS", + { + limit, + offset, + query, + hcMode, + siteId, + resourceId, + hcHealth, + hcEnabled + } + ] as const, + queryFn: async ({ signal, meta }) => { + const sp = new URLSearchParams(); + sp.set("limit", String(limit)); + sp.set("offset", String(offset)); + if (query) sp.set("query", query); + if (hcMode) sp.set("hcMode", hcMode); + if (siteId != null) sp.set("siteId", String(siteId)); + if (resourceId != null) + sp.set("resourceId", String(resourceId)); + if (hcHealth) sp.set("hcHealth", hcHealth); + if (hcEnabled) sp.set("hcEnabled", hcEnabled); + const res = await meta!.api.get< + AxiosResponse<{ + healthChecks: { + targetHealthCheckId: number; + name: string; + siteId: number | null; + siteName: string | null; + siteNiceId: string | null; + hcEnabled: boolean; + hcHealth: "unknown" | "healthy" | "unhealthy"; + hcMode: string | null; + hcHostname: string | null; + hcPort: number | null; + hcPath: string | null; + hcScheme: string | null; + hcMethod: string | null; + hcInterval: number | null; + hcUnhealthyInterval: number | null; + hcTimeout: number | null; + hcHeaders: string | null; + hcFollowRedirects: boolean | null; + hcStatus: number | null; + hcTlsServerName: string | null; + hcHealthyThreshold: number | null; + hcUnhealthyThreshold: number | null; + resourceId: number | null; + resourceName: string | null; + resourceNiceId: string | null; + }[]; + pagination: { + total: number; + limit: number; + offset: number; + }; + }> + >(`/org/${orgId}/health-checks?${sp.toString()}`, { signal }); + return { + healthChecks: res.data.data.healthChecks, + pagination: res.data.data.pagination + }; + } + }), + siteStatusHistory: ({ + siteId, + days = 90 + }: { + siteId: number; + days?: number; + }) => + queryOptions({ + queryKey: ["SITE_STATUS_HISTORY", siteId, days] as const, + queryFn: async ({ signal, meta }) => { + const res = await meta!.api.get< + AxiosResponse + >(`/site/${siteId}/status-history?days=${days}`, { signal }); + return res.data.data; + } + }), + + resourceStatusHistory: ({ + resourceId, + days = 90 + }: { + resourceId?: number; + days?: number; + }) => + queryOptions({ + queryKey: ["RESOURCE_STATUS_HISTORY", resourceId, days] as const, + queryFn: async ({ signal, meta }) => { + const res = await meta!.api.get< + AxiosResponse + >(`/resource/${resourceId}/status-history?days=${days}`, { + signal + }); + return res.data.data; + } + }), + + healthCheckStatusHistory: ({ + orgId, + healthCheckId, + days = 90 + }: { + orgId: string; + healthCheckId: number; + days?: number; + }) => + queryOptions({ + queryKey: [ + "HC_STATUS_HISTORY", + orgId, + healthCheckId, + days + ] as const, + queryFn: async ({ signal, meta }) => { + const res = await meta!.api.get< + AxiosResponse + >( + `/org/${orgId}/health-check/${healthCheckId}/status-history?days=${days}`, + { signal } + ); + return res.data.data; + } }) }; @@ -472,3 +751,34 @@ export const approvalQueries = { } }) }; + +export const domainQueries = { + getDomain: ({ orgId, domainId }: { orgId: string; domainId: string }) => + queryOptions({ + queryKey: ["ORG", orgId, "DOMAIN", domainId] as const, + queryFn: async ({ signal, meta }) => { + const res = await meta!.api.get< + AxiosResponse + >(`/org/${orgId}/domain/${domainId}`, { signal }); + return res.data.data; + }, + refetchInterval: durationToMs(10, "seconds") + }), + getDNSRecords: ({ orgId, domainId }: { orgId: string; domainId: string }) => + queryOptions({ + queryKey: [ + "ORG", + orgId, + "DOMAIN", + domainId, + "DNS_RECORDS" + ] as const, + queryFn: async ({ signal, meta }) => { + const res = await meta!.api.get< + AxiosResponse + >(`/org/${orgId}/domain/${domainId}/dns-records`, { signal }); + return res.data.data; + }, + refetchInterval: durationToMs(10, "seconds") + }) +}; diff --git a/src/providers/SubscriptionStatusProvider.tsx b/src/providers/SubscriptionStatusProvider.tsx index a105e5d58..e1e781193 100644 --- a/src/providers/SubscriptionStatusProvider.tsx +++ b/src/providers/SubscriptionStatusProvider.tsx @@ -71,6 +71,19 @@ export function SubscriptionStatusProvider({ const limitsExceeded = subscriptionStatusState?.limitsExceeded ?? false; + const trialExpiresAt = (() => { + if (subscriptionStatusState?.subscriptions) { + for (const { subscription } of subscriptionStatusState.subscriptions) { + if (subscription.expiresAt != null) { + return subscription.expiresAt * 1000; // convert seconds to ms + } + } + } + return null; + })(); + + const isTrial = subscriptionStatusState?.subscriptions?.some(({ subscription }) => subscription.trial) ?? false; + return ( {children} diff --git a/src/services/locale.ts b/src/services/locale.ts index 81be42bc1..2d3e1d21f 100644 --- a/src/services/locale.ts +++ b/src/services/locale.ts @@ -17,14 +17,14 @@ export async function getUserLocale(): Promise { return cookieLocale as Locale; } - // No cookie found — try to restore from user's saved locale in DB + // No cookie found - try to restore from user's saved locale in DB try { const res = await internal.get("/user", await authCookieHeader()); const userLocale = res.data?.data?.locale; if (userLocale && locales.includes(userLocale as Locale)) { // Try to cache in a cookie so subsequent requests skip the API // call. cookies().set() is only permitted in Server Actions and - // Route Handlers — not during rendering — so we isolate it so + // Route Handlers - not during rendering - so we isolate it so // that a write failure doesn't prevent the locale from being // returned for the current request. try { @@ -40,7 +40,7 @@ export async function getUserLocale(): Promise { return userLocale as Locale; } } catch { - // User not logged in or API unavailable — fall through + // User not logged in or API unavailable - fall through } const headerList = await headers();