diff --git a/.cursor/rules/Localization.mdc b/.cursor/rules/Localization.mdc new file mode 100644 index 000000000..3014c6177 --- /dev/null +++ b/.cursor/rules/Localization.mdc @@ -0,0 +1,5 @@ +--- +alwaysApply: true +--- + +Always localize strings and use the `t` function to convert keys to strings. Add the keys to the en-us.json file. Never edit the other language files, as en-us.json is the single source of truth. diff --git a/.cursor/rules/Nomenclature.mdc b/.cursor/rules/Nomenclature.mdc new file mode 100644 index 000000000..d290f212e --- /dev/null +++ b/.cursor/rules/Nomenclature.mdc @@ -0,0 +1,7 @@ +--- +description: +alwaysApply: true +--- + +Proxy resources = public resources +Private resources = client resources = site resources diff --git a/.github/workflows/cicd.yml b/.github/workflows/cicd.yml index befc96b17..7a9004ee8 100644 --- a/.github/workflows/cicd.yml +++ b/.github/workflows/cicd.yml @@ -414,28 +414,18 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - name: Install cosign - # cosign is used to sign and verify container images (key and keyless) + # cosign is used to sign container images using keyless (OIDC) signing uses: sigstore/cosign-installer@cad07c2e89fa2edd6e2d7bab4c1aa38e53f76003 # v4.1.1 - - name: Dual-sign and verify (GHCR & Docker Hub) - # Sign each image by digest using keyless (OIDC) and key-based signing, - # then verify both the public key signature and the keyless OIDC signature. + - name: Sign (GHCR, keyless) + # Sign each GHCR image by digest using keyless (OIDC) signing via Sigstore/Rekor. + # Signatures are stored in the registry alongside the image. env: TAG: ${{ env.TAG }} - COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }} - COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }} - COSIGN_PUBLIC_KEY: ${{ secrets.COSIGN_PUBLIC_KEY }} COSIGN_YES: "true" run: | set -euo pipefail - issuer="https://token.actions.githubusercontent.com" - id_regex="^https://github.com/${{ github.repository }}/.+" # accept this repo (all workflows/refs) - - # Track failures - FAILED_TAGS=() - SUCCESSFUL_TAGS=() - # Determine if this is an RC release IS_RC="false" if [[ "$TAG" == *"-rc."* ]]; then @@ -463,95 +453,47 @@ jobs: ) fi - # Sign each image variant for both registries - for BASE_IMAGE in "${GHCR_IMAGE}" "${DOCKERHUB_IMAGE}"; do - for IMAGE_TAG in "${IMAGE_TAGS[@]}"; do - echo "Processing ${BASE_IMAGE}:${IMAGE_TAG}" - TAG_FAILED=false + FAILED_TAGS=() + SUCCESSFUL_TAGS=() - # Wrap the entire tag processing in error handling - ( - set -e - DIGEST="$(skopeo inspect --retry-times 3 docker://${BASE_IMAGE}:${IMAGE_TAG} | jq -r '.Digest')" - REF="${BASE_IMAGE}@${DIGEST}" - echo "Resolved digest: ${REF}" + for IMAGE_TAG in "${IMAGE_TAGS[@]}"; do + echo "Processing ${GHCR_IMAGE}:${IMAGE_TAG}" + TAG_FAILED=false - echo "==> cosign sign (keyless) --recursive ${REF}" - cosign sign --recursive "${REF}" + ( + set -e + DIGEST="$(skopeo inspect --retry-times 3 docker://${GHCR_IMAGE}:${IMAGE_TAG} | jq -r '.Digest')" + REF="${GHCR_IMAGE}@${DIGEST}" + echo "Resolved digest: ${REF}" - echo "==> cosign sign (key) --recursive ${REF}" - cosign sign --key env://COSIGN_PRIVATE_KEY --recursive "${REF}" + echo "==> cosign sign (keyless) --recursive ${REF}" + cosign sign --recursive "${REF}" + ) || TAG_FAILED=true - # Retry wrapper for verification to handle registry propagation delays - retry_verify() { - local cmd="$1" - local attempts=6 - local delay=5 - local i=1 - until eval "$cmd"; do - if [ $i -ge $attempts ]; then - echo "Verification failed after $attempts attempts" - return 1 - fi - echo "Verification not yet available. Retry $i/$attempts after ${delay}s..." - sleep $delay - i=$((i+1)) - delay=$((delay*2)) - # Cap the delay to avoid very long waits - if [ $delay -gt 60 ]; then delay=60; fi - done - return 0 - } - - echo "==> cosign verify (public key) ${REF}" - if retry_verify "cosign verify --key env://COSIGN_PUBLIC_KEY '${REF}' -o text"; then - VERIFIED_INDEX=true - else - VERIFIED_INDEX=false - fi - - echo "==> cosign verify (keyless policy) ${REF}" - if retry_verify "cosign verify --certificate-oidc-issuer '${issuer}' --certificate-identity-regexp '${id_regex}' '${REF}' -o text"; then - VERIFIED_INDEX_KEYLESS=true - else - VERIFIED_INDEX_KEYLESS=false - fi - - # Check if verification succeeded - if [ "${VERIFIED_INDEX}" != "true" ] && [ "${VERIFIED_INDEX_KEYLESS}" != "true" ]; then - echo "⚠️ WARNING: Verification not available for ${BASE_IMAGE}:${IMAGE_TAG}" - echo "This may be due to registry propagation delays. Continuing anyway." - fi - ) || TAG_FAILED=true - - if [ "$TAG_FAILED" = "true" ]; then - echo "⚠️ WARNING: Failed to sign/verify ${BASE_IMAGE}:${IMAGE_TAG}" - FAILED_TAGS+=("${BASE_IMAGE}:${IMAGE_TAG}") - else - echo "✓ Successfully signed and verified ${BASE_IMAGE}:${IMAGE_TAG}" - SUCCESSFUL_TAGS+=("${BASE_IMAGE}:${IMAGE_TAG}") - fi - done + if [ "$TAG_FAILED" = "true" ]; then + echo "⚠️ WARNING: Failed to sign ${GHCR_IMAGE}:${IMAGE_TAG}" + FAILED_TAGS+=("${GHCR_IMAGE}:${IMAGE_TAG}") + else + echo "✓ Successfully signed ${GHCR_IMAGE}:${IMAGE_TAG}" + SUCCESSFUL_TAGS+=("${GHCR_IMAGE}:${IMAGE_TAG}") + fi done - # Report summary echo "" echo "==========================================" - echo "Sign and Verify Summary" + echo "Sign Summary" echo "==========================================" echo "Successful: ${#SUCCESSFUL_TAGS[@]}" echo "Failed: ${#FAILED_TAGS[@]}" - echo "" if [ ${#FAILED_TAGS[@]} -gt 0 ]; then echo "Failed tags:" for tag in "${FAILED_TAGS[@]}"; do echo " - $tag" done - echo "" - echo "⚠️ WARNING: Some tags failed to sign/verify, but continuing anyway" + echo "⚠️ WARNING: Some tags failed to sign, but continuing anyway" else - echo "✓ All images signed and verified successfully!" + echo "✓ All images signed successfully!" fi shell: bash diff --git a/messages/bg-BG.json b/messages/bg-BG.json index bf953e4d4..0b743adbc 100644 --- a/messages/bg-BG.json +++ b/messages/bg-BG.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "Копирах конфигурацията", "searchSitesProgress": "Търсене на сайтове...", "siteAdd": "Добавете сайт", + "sitesTableViewPublicResources": "Вижте публични ресурси", + "sitesTableViewPrivateResources": "Вижте частни ресурси", "siteInstallNewt": "Инсталирайте Newt", "siteInstallNewtDescription": "Пуснете Newt на вашата система", "WgConfiguration": "WireGuard конфигурация", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "Сайтът е актуализиран.", "siteGeneralDescription": "Конфигурирайте общи настройки за този сайт", "siteSettingDescription": "Конфигурирайте настройките на сайта", + "siteResourcesTab": "Ресурси", + "siteResourcesNoneOnSite": "Този сайт все още няма публични или частни ресурси.", + "siteResourcesSectionPublic": "Публични ресурси", + "siteResourcesSectionPrivate": "Частни ресурси", + "siteResourcesSectionPublicDescription": "Ресурси, които са изложени външно чрез домейни или портове.", + "siteResourcesSectionPrivateDescription": "Ресурси, които са достъпни в частната ви мрежа през сайта.", + "siteResourcesViewAllPublic": "Виж всички ресурси", + "siteResourcesViewAllPrivate": "Виж всички ресурси", + "siteResourcesDialogDescription": "Преглед на публични и частни ресурси, свързани с този сайт.", + "siteResourcesShowMore": "Покажи повече", + "siteResourcesPermissionDenied": "Нямате разрешение да изброите тези ресурси.", + "siteResourcesEmptyPublic": "Няма публични ресурси, насочени към този сайт все още.", + "siteResourcesEmptyPrivate": "Няма частни ресурси, свързани с този сайт още.", + "siteResourcesHowToAccess": "Как да получите достъп", + "siteResourcesTargetsOnSite": "Цели на този сайт", "siteSetting": "Настройки на {siteName}", "siteNewtTunnel": "Нов Сайт (Препоръчително)", "siteNewtTunnelDescription": "Най-лесният начин да създадете точка за достъп до всяка мрежа. Няма нужда от допълнителни настройки.", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "Състоянието на проверката се променя", "alertingTriggerResourceHealthy": "Ресурсът е здрав", "alertingTriggerResourceUnhealthy": "Ресурсът не е здрав", + "alertingTriggerResourceDegraded": "Деградирал ресурс", "alertingSearchHealthChecks": "Търсене на проверки на състоянието…", "alertingHealthChecksEmpty": "Няма налични проверки на състоянието.", "alertingTriggerResourceToggle": "Състоянието на ресурса се променя", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "Създайте администраторски акаунт на сървъра. Може да съществува само един администраторски акаунт. Винаги можете да промените тези данни по-късно.", "createAdminAccount": "Създаване на админ акаунт", "setupErrorCreateAdmin": "Възникна грешка при създаване на админ акаунт.", - "certificateStatus": "Статус на сертификата", + "certificateStatus": "Сертификат", + "certificateStatusAutoRefreshHint": "Състоянието се опреснява автоматично.", "loading": "Зареждане", "loadingAnalytics": "Зареждане на анализи", "restart": "Рестарт", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "Конфигуриране на проверка на здравето", "configureHealthCheckDescription": "Настройте мониторинг на здравето за {target}", "enableHealthChecks": "Разрешаване на проверки на здравето", + "healthCheckDisabledStateDescription": "Когато е деактивиран, сайтът не изпълнява проверки и състоянието се счита за неизвестно.", "enableHealthChecksDescription": "Мониторинг на здравето на тази цел. Можете да наблюдавате различен краен пункт от целта, ако е необходимо.", "healthScheme": "Метод", "healthSelectScheme": "Избор на метод", @@ -1947,6 +1967,8 @@ "httpMethod": "HTTP Метод", "selectHttpMethod": "Изберете HTTP метод", "domainPickerSubdomainLabel": "Поддомен", + "domainPickerWildcard": "Уайлдкард", + "domainPickerWildcardPaidOnly": "Уайлдкард подсайтовете са платена функция. Моля, надстройте за достъп до тази функция.", "domainPickerBaseDomainLabel": "Основен домейн", "domainPickerSearchDomains": "Търсене на домейни...", "domainPickerNoDomainsFound": "Не са намерени домейни", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "Този адрес е част от подсистемата на организацията. Използва се за разрешаване на псевдонимни записи чрез вътрешно DNS разрешаване.", "resourcesTableClients": "Клиенти", "resourcesTableAndOnlyAccessibleInternally": "и са достъпни само вътрешно при свързване с клиент.", - "resourcesTableNoTargets": "Без цели", "resourcesTableHealthy": "Здрав", "resourcesTableDegraded": "Влошен", - "resourcesTableOffline": "Извън линия", + "resourcesTableUnhealthy": "Нездравословно", "resourcesTableUnknown": "Неизвестно", "resourcesTableNotMonitored": "Не е наблюдавано", + "resourcesTableNoTargets": "Няма цели", "editInternalResourceDialogEditClientResource": "Редактиране на частен ресурс", "editInternalResourceDialogUpdateResourceProperties": "Актуализирайте конфигурацията на ресурса и контрола на достъпа за {resourceName}", "editInternalResourceDialogResourceProperties": "Свойствата на ресурса", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "Проверено", "domainPickerUnverified": "Непроверено", "domainPickerManual": "Ръчно", - "domainPickerInvalidSubdomainStructure": "Този поддомен съдържа невалидни знаци или структура. Ще бъде автоматично пречистен при запазване.", + "domainPickerInvalidSubdomainStructure": "Невалидните символи ще бъдат почистени при записване.", "domainPickerError": "Грешка", "domainPickerErrorLoadDomains": "Неуспешно зареждане на домейни на организацията", "domainPickerErrorCheckAvailability": "Неуспешна проверка на наличността на домейни", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "Добавяне на клиенти.", "editInternalResourceDialogDestinationLabel": "Дестинация.", "editInternalResourceDialogDestinationDescription": "Посочете адреса дестинация за вътрешния ресурс. Това може да бъде име на хост, IP адрес или CIDR обхват в зависимост от избрания режим. По избор настройте вътрешен DNS алиас за по-лесно идентифициране.", + "internalResourceFormMultiSiteRoutingHelp": "Избирайки няколко сайта, се осигурява сигурен път и пренасочване при висока достъпност.", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "Научете повече", "editInternalResourceDialogPortRestrictionsDescription": "Ограничете достъпа до конкретни TCP/UDP портове или позволете/блокирайте всички портове.", "createInternalResourceDialogHttpConfiguration": "Конфигурация HTTP", "createInternalResourceDialogHttpConfigurationDescription": "Изберете домейна, който клиентите ще използват, за да достигнат този ресурс чрез HTTP или HTTPS.", @@ -2908,6 +2932,7 @@ "maintenancePageTimeTitle": "Очаквано време за завършване (по избор).", "privateMaintenanceScreenTitle": "Екран за поддръжка", "privateMaintenanceScreenMessage": "Този домейн се използва при частен ресурс. Моля, свържете се с клиента на Pangolin, за да получите достъп до този ресурс.", + "privateMaintenanceScreenSteps": "След свързване, ако все още виждате това съобщение, кешът на DNS на вашия браузър все още може да сочи към стария адрес. За да коригирате това: напълно затворете и отворете отново този раздел, или браузъра си, след това се върнете на тази страница.", "maintenanceTime": "например, 2 часа, 1 ноември в 17:00.", "maintenanceEstimatedTimeDescription": "Кога очаквате поддръжката да бъде завършена?", "editDomain": "Редактиране на домейна.", @@ -3142,5 +3167,39 @@ "idpDeleteAllOrgsMenu": "Изтриване", "publicIpEndpoint": "Крайна точка", "lastTriggeredAt": "Последен тригер", - "reject": "Отхвърляне" + "reject": "Отхвърляне", + "uptimeDaysAgo": "{count} days ago", + "uptimeToday": "Днес", + "uptimeNoDataAvailable": "Няма налични данни", + "uptimeSuffix": "време без прекъсване", + "uptimeDowntimeSuffix": "време на прекъсване", + "uptimeTooltipUptimeLabel": "Време без прекъсване", + "uptimeTooltipDowntimeLabel": "Време на прекъсване", + "uptimeOngoing": "текущо", + "uptimeNoMonitoringData": "Няма данни за наблюдение", + "uptimeNoData": "Няма данни", + "uptimeMiniBarDown": "Прекъсване", + "uptimeSectionTitle": "Време без прекъсване", + "uptimeSectionDescription": "Наличност през последните {days} дни", + "uptimeAddAlert": "Добавяне на известие", + "uptimeViewAlerts": "Преглед на известията", + "uptimeCreateEmailAlert": "Създаване на електронна известие", + "uptimeAlertDescriptionSite": "Получавайте известия по електронна поща, когато този сайт се изключи или отново стане онлайн.", + "uptimeAlertDescriptionResource": "Получавайте известия по електронна поща, когато този ресурс се изключи или отново стане онлайн.", + "uptimeAlertNamePlaceholder": "Име на известието", + "uptimeAdditionalEmails": "Допълнителни имейли", + "uptimeCreateAlert": "Създаване на известие", + "uptimeAlertNoRecipients": "Няма получатели", + "uptimeAlertNoRecipientsDescription": "Моля, добавете поне един потребител, рол, или имейл за известяване.", + "uptimeAlertCreated": "Известието е създадено", + "uptimeAlertCreatedDescription": "Ще бъдете известени, когато това промени статуса си.", + "uptimeAlertCreateFailed": "Неуспешно създаване на известие", + "webhookUrlLabel": "URL", + "webhookHeaderKeyPlaceholder": "Ключ", + "webhookHeaderValuePlaceholder": "Стойност", + "alertLabel": "Известие", + "domainPickerWildcardSubdomainNotAllowed": "Уайлдкард подсайтове не са позволени.", + "domainPickerWildcardCertWarning": "Ресурсите с уайлдкард може да изискват допълнителна конфигурация за правилна работа.", + "domainPickerWildcardCertWarningLink": "Научете повече", + "health": "Здраве" } diff --git a/messages/cs-CZ.json b/messages/cs-CZ.json index 0e43a4043..309d52a90 100644 --- a/messages/cs-CZ.json +++ b/messages/cs-CZ.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "Konfiguraci jsem zkopíroval", "searchSitesProgress": "Hledat lokality...", "siteAdd": "Přidat lokalitu", + "sitesTableViewPublicResources": "Zobrazit veřejné zdroje", + "sitesTableViewPrivateResources": "Zobrazit soukromé zdroje", "siteInstallNewt": "Nainstalovat Newt", "siteInstallNewtDescription": "Spustit Newt na vašem systému", "WgConfiguration": "Konfigurace WireGuard", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "Lokalita byla upravena.", "siteGeneralDescription": "Upravte obecná nastavení pro tuto lokalitu", "siteSettingDescription": "Konfigurace nastavení na webu", + "siteResourcesTab": "Zdroje", + "siteResourcesNoneOnSite": "Tento web zatím nemá veřejné ani soukromé zdroje.", + "siteResourcesSectionPublic": "Veřejné zdroje", + "siteResourcesSectionPrivate": "Soukromé zdroje", + "siteResourcesSectionPublicDescription": "Zdroje zpřístupněné externě prostřednictvím domén nebo portů.", + "siteResourcesSectionPrivateDescription": "Zdroje dostupné ve vaší soukromé síti prostřednictvím webu.", + "siteResourcesViewAllPublic": "Zobrazit všechny zdroje", + "siteResourcesViewAllPrivate": "Zobrazit všechny zdroje", + "siteResourcesDialogDescription": "Přehled veřejných a soukromých zdrojů spojených s tímto webem.", + "siteResourcesShowMore": "Ukázat více", + "siteResourcesPermissionDenied": "Nemáte oprávnění k vypsání těchto zdrojů.", + "siteResourcesEmptyPublic": "Žádné veřejné zdroje ještě necílí na tento web.", + "siteResourcesEmptyPrivate": "Žádné soukromé zdroje ještě nejsou spojené s tímto webem.", + "siteResourcesHowToAccess": "Jak získat přístup", + "siteResourcesTargetsOnSite": "Cíle na tomto webu", "siteSetting": "Nastavení {siteName}", "siteNewtTunnel": "Novinka (doporučeno)", "siteNewtTunnelDescription": "Nejjednodušší způsob, jak vytvořit vstupní bod do jakékoli sítě. Žádné další nastavení.", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "Změny stavu kontroly stavu", "alertingTriggerResourceHealthy": "Zdroj je zdravý", "alertingTriggerResourceUnhealthy": "Zdroj je nezdravý", + "alertingTriggerResourceDegraded": "Zhoršený zdroj", "alertingSearchHealthChecks": "Hledat kontroly stavu…", "alertingHealthChecksEmpty": "Nejsou dostupné kontroly stavu.", "alertingTriggerResourceToggle": "Změny stavu zdroje", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "Vytvořte účet správce intial serveru. Pouze jeden správce serveru může existovat. Tyto přihlašovací údaje můžete kdykoliv změnit.", "createAdminAccount": "Vytvořit účet správce", "setupErrorCreateAdmin": "Došlo k chybě při vytváření účtu správce serveru.", - "certificateStatus": "Stav certifikátu", + "certificateStatus": "Certifikát", + "certificateStatusAutoRefreshHint": "Stav se automaticky obnovuje.", "loading": "Načítání", "loadingAnalytics": "Načítání analytiky", "restart": "Restartovat", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "Konfigurace kontroly stavu", "configureHealthCheckDescription": "Nastavit sledování zdravotního stavu pro {target}", "enableHealthChecks": "Povolit kontrolu stavu", + "healthCheckDisabledStateDescription": "Pokud je zakázáno, web nebude provádět zdravotní kontroly a stav bude považován za neznámý.", "enableHealthChecksDescription": "Sledujte zdraví tohoto cíle. V případě potřeby můžete sledovat jiný cílový bod, než je cíl.", "healthScheme": "Způsob", "healthSelectScheme": "Vybrat metodu", @@ -1947,6 +1967,8 @@ "httpMethod": "HTTP metoda", "selectHttpMethod": "Vyberte HTTP metodu", "domainPickerSubdomainLabel": "Subdoména", + "domainPickerWildcard": "Zástupný znak", + "domainPickerWildcardPaidOnly": "Zástupné poddomény jsou placenou funkcí. Upgradujte, prosím, pro přístup k této funkci.", "domainPickerBaseDomainLabel": "Základní doména", "domainPickerSearchDomains": "Hledat domény...", "domainPickerNoDomainsFound": "Nebyly nalezeny žádné domény", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "Tato adresa je součástí subsítě veřejných služeb organizace. Používá se k řešení záznamů aliasů pomocí interního rozlišení DNS.", "resourcesTableClients": "Klienti", "resourcesTableAndOnlyAccessibleInternally": "a jsou interně přístupné pouze v případě, že jsou propojeni s klientem.", - "resourcesTableNoTargets": "Žádné cíle", "resourcesTableHealthy": "Zdravé", "resourcesTableDegraded": "Rozklad", - "resourcesTableOffline": "Offline", + "resourcesTableUnhealthy": "Nezdravý", "resourcesTableUnknown": "Neznámý", "resourcesTableNotMonitored": "Není sledováno", + "resourcesTableNoTargets": "Žádné cíle", "editInternalResourceDialogEditClientResource": "Upravit soukromý dokument", "editInternalResourceDialogUpdateResourceProperties": "Aktualizovat konfiguraci zdroje a ovládací prvky přístupu pro {resourceName}", "editInternalResourceDialogResourceProperties": "Vlastnosti zdroje", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "Ověřeno", "domainPickerUnverified": "Neověřeno", "domainPickerManual": "Ruční nastavení", - "domainPickerInvalidSubdomainStructure": "Tato subdoména obsahuje neplatné znaky nebo strukturu. Bude automaticky sanitována při uložení.", + "domainPickerInvalidSubdomainStructure": "Neplatné znaky budou při ukládání vyčištěny.", "domainPickerError": "Chyba", "domainPickerErrorLoadDomains": "Nepodařilo se načíst domény organizace", "domainPickerErrorCheckAvailability": "Kontrola dostupnosti domény se nezdařila", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "Přidat klienty", "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.", + "internalResourceFormMultiSiteRoutingHelp": "Výběrem více webů se povolí odolné směrování a přepojení pro vysokou dostupnost.", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "Zjistit více", "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.", @@ -2908,6 +2932,7 @@ "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.", + "privateMaintenanceScreenSteps": "Jakmile se připojíte, pokud stále vidíte tuto zprávu, možná je mezipaměť DNS vašeho prohlížeče stále nasměrována na starou adresu. Abyste to opravili: úplně zavřete a znovu otevřete tuto záložku nebo prohlížeč, a poté se vraťte na tuto stránku.", "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", @@ -3142,5 +3167,39 @@ "idpDeleteAllOrgsMenu": "Odstranit", "publicIpEndpoint": "Koncový bod", "lastTriggeredAt": "Poslední spouštěč", - "reject": "Odmítnout" + "reject": "Odmítnout", + "uptimeDaysAgo": "Před {count} dny", + "uptimeToday": "Dnes", + "uptimeNoDataAvailable": "Dostupná žádná data", + "uptimeSuffix": "doba dostupnosti", + "uptimeDowntimeSuffix": "doba nedostupnosti", + "uptimeTooltipUptimeLabel": "Doba dostupnosti", + "uptimeTooltipDowntimeLabel": "Doba nedostupnosti", + "uptimeOngoing": "probíhá", + "uptimeNoMonitoringData": "Žádné monitorovací údaje", + "uptimeNoData": "Žádná data", + "uptimeMiniBarDown": "Nedostupný", + "uptimeSectionTitle": "Doba dostupnosti", + "uptimeSectionDescription": "Dostupnost za posledních {days} dní", + "uptimeAddAlert": "Přidat upozornění", + "uptimeViewAlerts": "Zobrazit upozornění", + "uptimeCreateEmailAlert": "Vytvořit e-mailové upozornění", + "uptimeAlertDescriptionSite": "Pošleme vám upozornění e-mailem, když bude tento web offline nebo se vrátí online.", + "uptimeAlertDescriptionResource": "Pošleme vám upozornění e-mailem, když bude tento zdroj offline nebo se vrátí online.", + "uptimeAlertNamePlaceholder": "Název upozornění", + "uptimeAdditionalEmails": "Další e-maily", + "uptimeCreateAlert": "Vytvořit upozornění", + "uptimeAlertNoRecipients": "Žádní příjemci", + "uptimeAlertNoRecipientsDescription": "Přidejte prosím alespoň jednoho uživatele, roli nebo e-mailovou adresu pro upozornění.", + "uptimeAlertCreated": "Upozornění vytvořeno", + "uptimeAlertCreatedDescription": "Budete upozorněni, když se tento stav změní.", + "uptimeAlertCreateFailed": "Nepodařilo se vytvořit upozornění", + "webhookUrlLabel": "URL", + "webhookHeaderKeyPlaceholder": "Klíč", + "webhookHeaderValuePlaceholder": "Hodnota", + "alertLabel": "Upozornění", + "domainPickerWildcardSubdomainNotAllowed": "Zástupné poddomény nejsou povoleny.", + "domainPickerWildcardCertWarning": "Zástupné zdroje mohou vyžadovat dodatečnou konfiguraci pro správnou funkci.", + "domainPickerWildcardCertWarningLink": "Zjistit více", + "health": "Zdraví" } diff --git a/messages/de-DE.json b/messages/de-DE.json index 07e5d93ac..74247798f 100644 --- a/messages/de-DE.json +++ b/messages/de-DE.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "Ich habe die Konfiguration kopiert", "searchSitesProgress": "Standorte durchsuchen...", "siteAdd": "Standort hinzufügen", + "sitesTableViewPublicResources": "Öffentliche Ressourcen anzeigen", + "sitesTableViewPrivateResources": "Private Ressourcen anzeigen", "siteInstallNewt": "Newt installieren", "siteInstallNewtDescription": "Installiere Newt auf deinem System.", "WgConfiguration": "WireGuard Konfiguration", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "Der Standort wurde aktualisiert.", "siteGeneralDescription": "Allgemeine Einstellungen für diesen Standort konfigurieren", "siteSettingDescription": "Standorteinstellungen konfigurieren", + "siteResourcesTab": "Ressourcen", + "siteResourcesNoneOnSite": "Diese Seite hat noch keine öffentlichen oder privaten Ressourcen.", + "siteResourcesSectionPublic": "Öffentliche Ressourcen", + "siteResourcesSectionPrivate": "Private Ressourcen", + "siteResourcesSectionPublicDescription": "Ressourcen, die extern über Domains oder Ports bereitgestellt werden.", + "siteResourcesSectionPrivateDescription": "Ressourcen, die in Ihrem privaten Netzwerk über die Seite verfügbar sind.", + "siteResourcesViewAllPublic": "Alle Ressourcen anzeigen", + "siteResourcesViewAllPrivate": "Alle Ressourcen anzeigen", + "siteResourcesDialogDescription": "Überblick über öffentliche und private Ressourcen, die mit dieser Seite verbunden sind.", + "siteResourcesShowMore": "Mehr anzeigen", + "siteResourcesPermissionDenied": "Sie haben keine Berechtigung, diese Ressourcen aufzulisten.", + "siteResourcesEmptyPublic": "Noch sind keine öffentlichen Ressourcen für diese Seite vorhanden.", + "siteResourcesEmptyPrivate": "Noch sind keine privaten Ressourcen mit dieser Seite verbunden.", + "siteResourcesHowToAccess": "Zugriffsmöglichkeiten", + "siteResourcesTargetsOnSite": "Ziele auf dieser Seite", "siteSetting": "{siteName} Einstellungen", "siteNewtTunnel": "Newt Standort (empfohlen)", "siteNewtTunnelDescription": "Einfachster Weg, einen Einstiegspunkt in jedes Netzwerk zu erstellen. Keine zusätzliche Einrichtung.", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "Gesundheits-Check-Status ändern", "alertingTriggerResourceHealthy": "Ressource gesund", "alertingTriggerResourceUnhealthy": "Ressource ungesund", + "alertingTriggerResourceDegraded": "Ressource verschlechtert", "alertingSearchHealthChecks": "Gesundheits-Checks suchen…", "alertingHealthChecksEmpty": "Keine Gesundheits-Checks verfügbar.", "alertingTriggerResourceToggle": "Ressourcenstatus ändern", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "Erstellen Sie das initiale Server-Admin-Konto. Es kann nur einen Server-Admin geben. Sie können diese Anmeldedaten später immer ändern.", "createAdminAccount": "Admin-Konto erstellen", "setupErrorCreateAdmin": "Beim Erstellen des Server-Admin-Kontos ist ein Fehler aufgetreten.", - "certificateStatus": "Zertifikatsstatus", + "certificateStatus": "Zertifikat", + "certificateStatusAutoRefreshHint": "Der Status wird automatisch aktualisiert.", "loading": "Laden", "loadingAnalytics": "Analytik wird geladen", "restart": "Neustart", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "Gesundheits-Check konfigurieren", "configureHealthCheckDescription": "Richten Sie die Gesundheitsüberwachung für {target} ein", "enableHealthChecks": "Gesundheits-Checks aktivieren", + "healthCheckDisabledStateDescription": "Wenn deaktiviert, führt die Seite keine Gesundheitsprüfungen durch und der Zustand wird als unbekannt betrachtet.", "enableHealthChecksDescription": "Überwachen Sie die Gesundheit dieses Ziels. Bei Bedarf können Sie einen anderen Endpunkt als das Ziel überwachen.", "healthScheme": "Methode", "healthSelectScheme": "Methode auswählen", @@ -1947,6 +1967,8 @@ "httpMethod": "HTTP-Methode", "selectHttpMethod": "HTTP-Methode auswählen", "domainPickerSubdomainLabel": "Subdomain", + "domainPickerWildcard": "Platzhalter", + "domainPickerWildcardPaidOnly": "Wildcard-Subdomains sind ein kostenpflichtiges Feature. Bitte upgraden Sie, um auf dieses Feature zuzugreifen.", "domainPickerBaseDomainLabel": "Basisdomain", "domainPickerSearchDomains": "Domains suchen...", "domainPickerNoDomainsFound": "Keine Domains gefunden", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "Diese Adresse ist Teil des Utility-Subnetzes der Organisation. Sie wird verwendet, um Alias-Einträge mit interner DNS-Auflösung aufzulösen.", "resourcesTableClients": "Clients", "resourcesTableAndOnlyAccessibleInternally": "und sind nur intern zugänglich, wenn mit einem Client verbunden.", - "resourcesTableNoTargets": "Keine Ziele", "resourcesTableHealthy": "Gesund", "resourcesTableDegraded": "Degradiert", - "resourcesTableOffline": "Offline", + "resourcesTableUnhealthy": "Ungesund", "resourcesTableUnknown": "Unbekannt", "resourcesTableNotMonitored": "Nicht überwacht", + "resourcesTableNoTargets": "Keine Ziele", "editInternalResourceDialogEditClientResource": "Private Ressource bearbeiten", "editInternalResourceDialogUpdateResourceProperties": "Ressourcen-Konfiguration und Zugriffssteuerung für {resourceName} aktualisieren", "editInternalResourceDialogResourceProperties": "Ressourceneigenschaften", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "Verifiziert", "domainPickerUnverified": "Nicht verifiziert", "domainPickerManual": "Manuell", - "domainPickerInvalidSubdomainStructure": "Diese Subdomain enthält ungültige Zeichen oder Struktur. Sie wird beim Speichern automatisch bereinigt.", + "domainPickerInvalidSubdomainStructure": "Ungültige Zeichen werden beim Speichern bereinigt.", "domainPickerError": "Fehler", "domainPickerErrorLoadDomains": "Fehler beim Laden der Organisations-Domains", "domainPickerErrorCheckAvailability": "Fehler beim Prüfen der Domain-Verfügbarkeit", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "Clients hinzufügen", "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.", + "internalResourceFormMultiSiteRoutingHelp": "Durch die Auswahl mehrerer Seiten wird ein ausfallsicheres Routing und Failover für hohe Verfügbarkeit ermöglicht.", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "Mehr erfahren", "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.", @@ -2908,6 +2932,7 @@ "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.", + "privateMaintenanceScreenSteps": "Sobald verbunden, wenn Sie diese Nachricht weiterhin sehen, zeigt der DNS-Cache Ihres Browsers möglicherweise noch auf die alte Adresse. Um dies zu beheben: Schließen Sie diesen Tab vollständig und öffnen Sie ihn erneut oder starten Sie Ihren Browser neu und rufen Sie dann diese Seite erneut auf.", "maintenanceTime": "z.B.: 2 Stunden, Nov 1 um 17:00 Uhr", "maintenanceEstimatedTimeDescription": "Wann Sie den Abschluss der Wartung erwarten", "editDomain": "Domain bearbeiten", @@ -3142,5 +3167,39 @@ "idpDeleteAllOrgsMenu": "Löschen", "publicIpEndpoint": "Endpunkt", "lastTriggeredAt": "Letzter Auslöser", - "reject": "Zurückweisen" + "reject": "Zurückweisen", + "uptimeDaysAgo": "vor {count} Tagen", + "uptimeToday": "Heute", + "uptimeNoDataAvailable": "Keine Daten verfügbar", + "uptimeSuffix": "Betriebzeit", + "uptimeDowntimeSuffix": "Ausfallzeit", + "uptimeTooltipUptimeLabel": "Betriebszeit", + "uptimeTooltipDowntimeLabel": "Ausfallzeit", + "uptimeOngoing": "im Gange", + "uptimeNoMonitoringData": "Keine Überwachungsdaten", + "uptimeNoData": "Keine Daten", + "uptimeMiniBarDown": "Unten", + "uptimeSectionTitle": "Betriebszeit", + "uptimeSectionDescription": "Verfügbarkeit in den letzten {days} Tagen", + "uptimeAddAlert": "Warnmeldung hinzufügen", + "uptimeViewAlerts": "Warnungen anzeigen", + "uptimeCreateEmailAlert": "E-Mail Alarm erstellen", + "uptimeAlertDescriptionSite": "Werde per E-Mail benachrichtigt, wenn diese Seite offline oder wieder online ist.", + "uptimeAlertDescriptionResource": "Werde per E-Mail benachrichtigt, wenn diese Ressource offline oder wieder online ist.", + "uptimeAlertNamePlaceholder": "Alarmname", + "uptimeAdditionalEmails": "Zusätzliche E-Mails", + "uptimeCreateAlert": "Alarm erstellen", + "uptimeAlertNoRecipients": "Kein Empfänger", + "uptimeAlertNoRecipientsDescription": "Bitte fügen Sie mindestens einen Benutzer, eine Rolle oder eine E-Mail zur Benachrichtigung hinzu.", + "uptimeAlertCreated": "Alarm erstellt", + "uptimeAlertCreatedDescription": "Sie werden benachrichtigt, wenn dieser Status sich ändert", + "uptimeAlertCreateFailed": "Fehler beim Erstellen der Benachrichtigung", + "webhookUrlLabel": "URL", + "webhookHeaderKeyPlaceholder": "Schlüssel", + "webhookHeaderValuePlaceholder": "Wert", + "alertLabel": "Alarm", + "domainPickerWildcardSubdomainNotAllowed": "Wildcard-Subdomains sind nicht erlaubt.", + "domainPickerWildcardCertWarning": "Wildcard-Ressourcen erfordern möglicherweise zusätzliche Konfigurationen, um ordnungsgemäß zu funktionieren.", + "domainPickerWildcardCertWarningLink": "Mehr erfahren", + "health": "Gesundheit" } diff --git a/messages/en-US.json b/messages/en-US.json index e85eff9e7..eb4d3ae3c 100644 --- a/messages/en-US.json +++ b/messages/en-US.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "I have copied the config", "searchSitesProgress": "Search sites...", "siteAdd": "Add Site", + "sitesTableViewPublicResources": "View Public Resources", + "sitesTableViewPrivateResources": "View Private Resources", "siteInstallNewt": "Install Site", "siteInstallNewtDescription": "Install the site connector for your system", "WgConfiguration": "WireGuard Configuration", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "The site has been updated.", "siteGeneralDescription": "Configure the general settings for this site", "siteSettingDescription": "Configure the settings on the site", + "siteResourcesTab": "Resources", + "siteResourcesNoneOnSite": "This site has no public or private resources yet.", + "siteResourcesSectionPublic": "Public Resources", + "siteResourcesSectionPrivate": "Private Resources", + "siteResourcesSectionPublicDescription": "Resources exposed externally through domains or ports.", + "siteResourcesSectionPrivateDescription": "Resources available on your private network through the site.", + "siteResourcesViewAllPublic": "View all resources", + "siteResourcesViewAllPrivate": "View all resources", + "siteResourcesDialogDescription": "Overview of public and private resources associated with this site.", + "siteResourcesShowMore": "Show more", + "siteResourcesPermissionDenied": "You do not have permission to list these resources.", + "siteResourcesEmptyPublic": "No public resources target this site yet.", + "siteResourcesEmptyPrivate": "No private resources are associated with this site yet.", + "siteResourcesHowToAccess": "How to access", + "siteResourcesTargetsOnSite": "Targets on this site", "siteSetting": "{siteName} Settings", "siteNewtTunnel": "Newt Site (Recommended)", "siteNewtTunnelDescription": "Easiest way to create an entrypoint into any network. No extra setup.", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "Health check status changes", "alertingTriggerResourceHealthy": "Resource healthy", "alertingTriggerResourceUnhealthy": "Resource unhealthy", + "alertingTriggerResourceDegraded": "Resource degraded", "alertingSearchHealthChecks": "Search health checks…", "alertingHealthChecksEmpty": "No health checks available.", "alertingTriggerResourceToggle": "Resource status changes", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "Create the intial server admin account. Only one server admin can exist. You can always change these credentials later.", "createAdminAccount": "Create Admin Account", "setupErrorCreateAdmin": "An error occurred while creating the server admin account.", - "certificateStatus": "Certificate Status", + "certificateStatus": "Certificate", + "certificateStatusAutoRefreshHint": "Status refreshes automatically.", "loading": "Loading", "loadingAnalytics": "Loading Analytics", "restart": "Restart", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "Configure Health Check", "configureHealthCheckDescription": "Set up health monitoring for {target}", "enableHealthChecks": "Enable Health Checks", + "healthCheckDisabledStateDescription": "When disabled, the site will not perform health checks and the state will be considered unknown.", "enableHealthChecksDescription": "Monitor the health of this target. You can monitor a different endpoint than the target if required.", "healthScheme": "Method", "healthSelectScheme": "Select Method", @@ -1947,6 +1967,8 @@ "httpMethod": "Scheme", "selectHttpMethod": "Select scheme", "domainPickerSubdomainLabel": "Subdomain", + "domainPickerWildcard": "Wildcard", + "domainPickerWildcardPaidOnly": "Wildcard subdomains are a paid feature. Please upgrade to access this feature.", "domainPickerBaseDomainLabel": "Base Domain", "domainPickerSearchDomains": "Search domains...", "domainPickerNoDomainsFound": "No domains found", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "This address is part of the organization's utility subnet. It's used to resolve alias records using internal DNS resolution.", "resourcesTableClients": "Clients", "resourcesTableAndOnlyAccessibleInternally": "and are only accessible internally when connected with a client.", - "resourcesTableNoTargets": "No targets", "resourcesTableHealthy": "Healthy", "resourcesTableDegraded": "Degraded", - "resourcesTableOffline": "Offline", + "resourcesTableUnhealthy": "Unhealthy", "resourcesTableUnknown": "Unknown", "resourcesTableNotMonitored": "Not monitored", + "resourcesTableNoTargets": "No targets", "editInternalResourceDialogEditClientResource": "Edit Private Resource", "editInternalResourceDialogUpdateResourceProperties": "Update the resource configuration and access controls for {resourceName}", "editInternalResourceDialogResourceProperties": "Resource Properties", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "Verified", "domainPickerUnverified": "Unverified", "domainPickerManual": "Manual", - "domainPickerInvalidSubdomainStructure": "This subdomain contains invalid characters or structure. It will be sanitized automatically when you save.", + "domainPickerInvalidSubdomainStructure": "Invalid characters will be sanitized when saved.", "domainPickerError": "Error", "domainPickerErrorLoadDomains": "Failed to load organization domains", "domainPickerErrorCheckAvailability": "Failed to check domain availability", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "Add Clients", "editInternalResourceDialogDestinationLabel": "Destination", "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.", + "internalResourceFormMultiSiteRoutingHelp": "Selecting multiple sites enables resilient routing and failover for high availability.", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "Learn more", "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.", @@ -3156,7 +3180,7 @@ "uptimeNoData": "No data", "uptimeMiniBarDown": "Down", "uptimeSectionTitle": "Uptime", - "uptimeSectionDescription": "Site availability over the last {days} days.", + "uptimeSectionDescription": "Availability over the last {days} days", "uptimeAddAlert": "Add Alert", "uptimeViewAlerts": "View Alerts", "uptimeCreateEmailAlert": "Create Email Alert", @@ -3173,5 +3197,9 @@ "webhookUrlLabel": "URL", "webhookHeaderKeyPlaceholder": "Key", "webhookHeaderValuePlaceholder": "Value", - "alertLabel": "Alert" + "alertLabel": "Alert", + "domainPickerWildcardSubdomainNotAllowed": "Wildcard subdomains are not allowed.", + "domainPickerWildcardCertWarning": "Wildcard resources may require additional configuration to work properly.", + "domainPickerWildcardCertWarningLink": "Learn more", + "health": "Health" } diff --git a/messages/es-ES.json b/messages/es-ES.json index e119adc1b..ea5e33b25 100644 --- a/messages/es-ES.json +++ b/messages/es-ES.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "He copiado la configuración", "searchSitesProgress": "Buscar sitios...", "siteAdd": "Añadir sitio", + "sitesTableViewPublicResources": "Ver Recursos Públicos", + "sitesTableViewPrivateResources": "Ver Recursos Privados", "siteInstallNewt": "Instalar Newt", "siteInstallNewtDescription": "Recibe Newt corriendo en tu sistema", "WgConfiguration": "Configuración de Wirex Guard", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "El sitio ha sido actualizado.", "siteGeneralDescription": "Configurar la configuración general de este sitio", "siteSettingDescription": "Configurar los ajustes en el sitio", + "siteResourcesTab": "Recursos", + "siteResourcesNoneOnSite": "Este sitio aún no tiene recursos públicos o privados.", + "siteResourcesSectionPublic": "Recursos Públicos", + "siteResourcesSectionPrivate": "Recursos Privados", + "siteResourcesSectionPublicDescription": "Recursos expuestos externamente a través de dominios o puertos.", + "siteResourcesSectionPrivateDescription": "Recursos disponibles en tu red privada a través del sitio.", + "siteResourcesViewAllPublic": "Ver todos los recursos", + "siteResourcesViewAllPrivate": "Ver todos los recursos", + "siteResourcesDialogDescription": "Descripción general de los recursos públicos y privados asociados con este sitio.", + "siteResourcesShowMore": "Mostrar más", + "siteResourcesPermissionDenied": "No tienes permiso para listar estos recursos.", + "siteResourcesEmptyPublic": "Aún no hay recursos públicos apuntando a este sitio.", + "siteResourcesEmptyPrivate": "Aún no hay recursos privados asociados con este sitio.", + "siteResourcesHowToAccess": "Cómo acceder", + "siteResourcesTargetsOnSite": "Objetivos en este sitio", "siteSetting": "Ajustes {siteName}", "siteNewtTunnel": "Sitio nuevo (recomendado)", "siteNewtTunnelDescription": "La forma más fácil de crear un punto de entrada en cualquier red. Sin configuración extra.", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "El estado del chequeo de salud cambia", "alertingTriggerResourceHealthy": "Recurso saludable", "alertingTriggerResourceUnhealthy": "Recurso no saludable", + "alertingTriggerResourceDegraded": "Recurso degradado", "alertingSearchHealthChecks": "Buscar chequeos de salud…", "alertingHealthChecksEmpty": "No hay chequeos de salud disponibles.", "alertingTriggerResourceToggle": "El estado del recurso cambia", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "Cree la cuenta de administrador del servidor inicial. Solo puede existir un administrador del servidor. Siempre puede cambiar estas credenciales más tarde.", "createAdminAccount": "Crear cuenta de administrador", "setupErrorCreateAdmin": "Se produjo un error al crear la cuenta de administrador del servidor.", - "certificateStatus": "Estado del certificado", + "certificateStatus": "Certificado", + "certificateStatusAutoRefreshHint": "El estado se actualiza automáticamente.", "loading": "Cargando", "loadingAnalytics": "Cargando analíticas", "restart": "Reiniciar", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "Configurar Chequeo de Salud", "configureHealthCheckDescription": "Configura la monitorización de salud para {target}", "enableHealthChecks": "Activar Chequeos de Salud", + "healthCheckDisabledStateDescription": "Cuando está deshabilitado, el sitio no realizará comprobaciones de salud y el estado se considerará desconocido.", "enableHealthChecksDescription": "Controlar la salud de este objetivo. Puedes supervisar un punto final diferente al objetivo si es necesario.", "healthScheme": "Método", "healthSelectScheme": "Seleccionar método", @@ -1947,6 +1967,8 @@ "httpMethod": "Método HTTP", "selectHttpMethod": "Seleccionar método HTTP", "domainPickerSubdomainLabel": "Subdominio", + "domainPickerWildcard": "Comodín", + "domainPickerWildcardPaidOnly": "Los subdominios comodín son una característica paga. Por favor, mejora tu plan para acceder a esta característica.", "domainPickerBaseDomainLabel": "Dominio base", "domainPickerSearchDomains": "Buscar dominios...", "domainPickerNoDomainsFound": "No se encontraron dominios", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "Esta dirección es parte de la subred de utilidad de la organización. Se utiliza para resolver registros de alias usando resolución DNS interna.", "resourcesTableClients": "Clientes", "resourcesTableAndOnlyAccessibleInternally": "y solo son accesibles internamente cuando se conectan con un cliente.", - "resourcesTableNoTargets": "Sin objetivos", "resourcesTableHealthy": "Saludable", "resourcesTableDegraded": "Degrado", - "resourcesTableOffline": "Desconectado", + "resourcesTableUnhealthy": "No saludable", "resourcesTableUnknown": "Desconocido", "resourcesTableNotMonitored": "No supervisado", + "resourcesTableNoTargets": "Sin objetivos", "editInternalResourceDialogEditClientResource": "Editar recurso privado", "editInternalResourceDialogUpdateResourceProperties": "Actualizar la configuración del recurso y los controles de acceso para {resourceName}", "editInternalResourceDialogResourceProperties": "Propiedades del recurso", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "Verificado", "domainPickerUnverified": "Sin verificar", "domainPickerManual": "Manual", - "domainPickerInvalidSubdomainStructure": "Este subdominio contiene caracteres o estructura no válidos. Se limpiará automáticamente al guardar.", + "domainPickerInvalidSubdomainStructure": "Los caracteres inválidos serán saneados al guardar.", "domainPickerError": "Error", "domainPickerErrorLoadDomains": "Error al cargar los dominios de la organización", "domainPickerErrorCheckAvailability": "No se pudo comprobar la disponibilidad del dominio", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "Agregar clientes", "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.", + "internalResourceFormMultiSiteRoutingHelp": "Seleccionar múltiples sitios habilita el enrutamiento resistente y la conmutación por error para alta disponibilidad.", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "Más información", "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.", @@ -2908,6 +2932,7 @@ "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.", + "privateMaintenanceScreenSteps": "Una vez conectado, si sigues viendo este mensaje, la caché de DNS de tu navegador puede seguir apuntando a la dirección antigua. Para solucionarlo: cierra por completo y vuelve a abrir esta pestaña o tu navegador, luego regresa a esta página.", "maintenanceTime": "Ej., 2 horas, 1 de noviembre a las 5:00 PM", "maintenanceEstimatedTimeDescription": "Cuando espera que el mantenimiento esté terminado", "editDomain": "Editar dominio", @@ -3142,5 +3167,39 @@ "idpDeleteAllOrgsMenu": "Eliminar", "publicIpEndpoint": "Punto final", "lastTriggeredAt": "Último disparo", - "reject": "Rechazar" + "reject": "Rechazar", + "uptimeDaysAgo": "Hace {count} días", + "uptimeToday": "Hoy", + "uptimeNoDataAvailable": "No hay datos disponibles", + "uptimeSuffix": "disponibilidad", + "uptimeDowntimeSuffix": "tiempo de inactividad", + "uptimeTooltipUptimeLabel": "Disponibilidad", + "uptimeTooltipDowntimeLabel": "Tiempo de inactividad", + "uptimeOngoing": "en curso", + "uptimeNoMonitoringData": "No hay datos de monitoreo", + "uptimeNoData": "Sin datos", + "uptimeMiniBarDown": "Caído", + "uptimeSectionTitle": "Disponibilidad", + "uptimeSectionDescription": "Disponibilidad durante los últimos {days} días", + "uptimeAddAlert": "Agregar alerta", + "uptimeViewAlerts": "Ver alertas", + "uptimeCreateEmailAlert": "Crear alerta de correo electrónico", + "uptimeAlertDescriptionSite": "Recibe notificaciones por correo electrónico cuando este sitio esté fuera de línea o vuelva en línea.", + "uptimeAlertDescriptionResource": "Recibe notificaciones por correo electrónico cuando este recurso esté fuera de línea o vuelva en línea.", + "uptimeAlertNamePlaceholder": "Nombre de la alerta", + "uptimeAdditionalEmails": "Emails adicionales", + "uptimeCreateAlert": "Crear alerta", + "uptimeAlertNoRecipients": "Sin destinatarios", + "uptimeAlertNoRecipientsDescription": "Por favor, agrega al menos un usuario, rol o correo electrónico para notificación.", + "uptimeAlertCreated": "Alerta creada", + "uptimeAlertCreatedDescription": "Serás notificado cuando cambie de estado.", + "uptimeAlertCreateFailed": "Error al crear la alerta", + "webhookUrlLabel": "URL", + "webhookHeaderKeyPlaceholder": "Clave", + "webhookHeaderValuePlaceholder": "Valor", + "alertLabel": "Alerta", + "domainPickerWildcardSubdomainNotAllowed": "No se permiten subdominios comodín.", + "domainPickerWildcardCertWarning": "Los recursos comodín pueden requerir configuración adicional para funcionar correctamente.", + "domainPickerWildcardCertWarningLink": "Más información", + "health": "Salud" } diff --git a/messages/fr-FR.json b/messages/fr-FR.json index f2ed46e2c..57825eff0 100644 --- a/messages/fr-FR.json +++ b/messages/fr-FR.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "J'ai copié la configuration", "searchSitesProgress": "Rechercher des nœuds...", "siteAdd": "Ajouter un nœud", + "sitesTableViewPublicResources": "Voir les ressources publiques", + "sitesTableViewPrivateResources": "Voir les ressources privées", "siteInstallNewt": "Installer Newt", "siteInstallNewtDescription": "Faites fonctionner Newt sur votre système", "WgConfiguration": "Configuration WireGuard", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "Le nœud a été mis à jour.", "siteGeneralDescription": "Configurer les paramètres par défaut de ce nœud", "siteSettingDescription": "Configurer les paramètres du site", + "siteResourcesTab": "Ressources", + "siteResourcesNoneOnSite": "Ce site n'a pas encore de ressources publiques ou privées.", + "siteResourcesSectionPublic": "Ressources publiques", + "siteResourcesSectionPrivate": "Ressources privées", + "siteResourcesSectionPublicDescription": "Ressources exposées à l'extérieur via des domaines ou des ports.", + "siteResourcesSectionPrivateDescription": "Ressources disponibles sur votre réseau privé via le site.", + "siteResourcesViewAllPublic": "Voir toutes les ressources", + "siteResourcesViewAllPrivate": "Voir toutes les ressources", + "siteResourcesDialogDescription": "Aperçu des ressources publiques et privées associées à ce site.", + "siteResourcesShowMore": "Afficher plus", + "siteResourcesPermissionDenied": "Vous n'avez pas la permission de lister ces ressources.", + "siteResourcesEmptyPublic": "Aucune ressource publique ne cible encore ce site.", + "siteResourcesEmptyPrivate": "Aucune ressource privée n'est encore associée à ce site.", + "siteResourcesHowToAccess": "Comment accéder", + "siteResourcesTargetsOnSite": "Cibles sur ce site", "siteSetting": "Paramètres de {siteName}", "siteNewtTunnel": "Site Newt (Recommandé)", "siteNewtTunnelDescription": "La façon la plus simple de créer un point d'entrée dans n'importe quel réseau. Pas de configuration supplémentaire.", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "Les changements d'état de la vérification de l'état de santé", "alertingTriggerResourceHealthy": "Ressource saine", "alertingTriggerResourceUnhealthy": "Ressource non saine", + "alertingTriggerResourceDegraded": "Ressource dégradée", "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", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "Créer le compte administrateur du serveur initial. Un seul administrateur serveur peut exister. Vous pouvez toujours changer ces informations d'identification plus tard.", "createAdminAccount": "Créer un compte administrateur", "setupErrorCreateAdmin": "Une erreur s'est produite lors de la création du compte administrateur du serveur.", - "certificateStatus": "Statut du certificat", + "certificateStatus": "Certificat", + "certificateStatusAutoRefreshHint": "L'état se rafraîchit automatiquement.", "loading": "Chargement", "loadingAnalytics": "Chargement de l'analyse", "restart": "Redémarrer", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "Configurer la vérification de l'état de santé", "configureHealthCheckDescription": "Configurer la surveillance de la santé pour {target}", "enableHealthChecks": "Activer les vérifications de santé", + "healthCheckDisabledStateDescription": "Lorsqu'il est désactivé, le site ne procédera pas aux vérifications de santé et l'état sera considéré comme inconnu.", "enableHealthChecksDescription": "Surveiller la vie de cette cible. Vous pouvez surveiller un point de terminaison différent de la cible si nécessaire.", "healthScheme": "Méthode", "healthSelectScheme": "Sélectionnez la méthode", @@ -1947,6 +1967,8 @@ "httpMethod": "Méthode HTTP", "selectHttpMethod": "Sélectionnez la méthode HTTP", "domainPickerSubdomainLabel": "Sous-domaine", + "domainPickerWildcard": "Joker", + "domainPickerWildcardPaidOnly": "Les sous-domaines Joker sont une fonctionnalité payante. Veuillez mettre à niveau pour accéder à cette fonctionnalité.", "domainPickerBaseDomainLabel": "Domaine de base", "domainPickerSearchDomains": "Rechercher des domaines...", "domainPickerNoDomainsFound": "Aucun domaine trouvé", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "Cette adresse fait partie du sous-réseau utilitaire de l'organisation. Elle est utilisée pour résoudre les enregistrements d'alias en utilisant une résolution DNS interne.", "resourcesTableClients": "Clients", "resourcesTableAndOnlyAccessibleInternally": "et sont uniquement accessibles en interne lorsqu'elles sont connectées avec un client.", - "resourcesTableNoTargets": "Aucune cible", "resourcesTableHealthy": "Sain", "resourcesTableDegraded": "Dégradé", - "resourcesTableOffline": "Hors ligne", + "resourcesTableUnhealthy": "En mauvaise santé", "resourcesTableUnknown": "Inconnu", "resourcesTableNotMonitored": "Non-monitoré", + "resourcesTableNoTargets": "Aucune cible", "editInternalResourceDialogEditClientResource": "Modifier une ressource privée", "editInternalResourceDialogUpdateResourceProperties": "Mettre à jour la configuration de la ressource et les contrôles d'accès pour {resourceName}", "editInternalResourceDialogResourceProperties": "Propriétés de la ressource", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "Vérifié", "domainPickerUnverified": "Non vérifié", "domainPickerManual": "Manuel", - "domainPickerInvalidSubdomainStructure": "Ce sous-domaine contient des caractères ou une structure non valide. Il sera automatiquement nettoyé lorsque vous enregistrez.", + "domainPickerInvalidSubdomainStructure": "Les caractères invalides seront nettoyés lors de l'enregistrement.", "domainPickerError": "Erreur", "domainPickerErrorLoadDomains": "Impossible de charger les domaines de l'organisation", "domainPickerErrorCheckAvailability": "Impossible de vérifier la disponibilité du domaine", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "Ajouter des clients", "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.", + "internalResourceFormMultiSiteRoutingHelp": "La sélection de plusieurs sites permet un routage résilient et un basculement pour une haute disponibilité.", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "En savoir plus", "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.", @@ -2908,6 +2932,7 @@ "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.", + "privateMaintenanceScreenSteps": "Une fois connecté, si vous voyez toujours ce message, le cache DNS de votre navigateur peut toujours pointer vers l'ancienne adresse. Pour résoudre cela : fermez complètement et rouvrez cet onglet, ou votre navigateur, puis retournez sur cette page.", "maintenanceTime": "par exemple, 2 heures, le 1er nov. à 17:00", "maintenanceEstimatedTimeDescription": "Quand vous attendez que la maintenance soit terminée", "editDomain": "Modifier le domaine", @@ -3143,5 +3168,39 @@ "idpDeleteAllOrgsMenu": "Supprimer", "publicIpEndpoint": "Point de terminaison", "lastTriggeredAt": "Dernier déclenchement", - "reject": "Rejeter" + "reject": "Rejeter", + "uptimeDaysAgo": "Il y a {count} jours", + "uptimeToday": "Aujourd'hui", + "uptimeNoDataAvailable": "Aucune donnée disponible", + "uptimeSuffix": "disponibilité", + "uptimeDowntimeSuffix": "indisponibilité", + "uptimeTooltipUptimeLabel": "Disponibilité", + "uptimeTooltipDowntimeLabel": "Indisponibilité", + "uptimeOngoing": "en cours", + "uptimeNoMonitoringData": "Pas de données de surveillance", + "uptimeNoData": "Aucune donnée", + "uptimeMiniBarDown": "Non disponible", + "uptimeSectionTitle": "Disponibilité", + "uptimeSectionDescription": "Disponibilité sur les {days} derniers jours", + "uptimeAddAlert": "Ajouter une alerte", + "uptimeViewAlerts": "Voir les alertes", + "uptimeCreateEmailAlert": "Créer une alerte par e-mail", + "uptimeAlertDescriptionSite": "Recevez un e-mail lorsque ce site est hors ligne ou revient en ligne.", + "uptimeAlertDescriptionResource": "Recevez un e-mail lorsque cette ressource est hors ligne ou revient en ligne.", + "uptimeAlertNamePlaceholder": "Nom de l'alerte", + "uptimeAdditionalEmails": "E-mails supplémentaires", + "uptimeCreateAlert": "Créer une alerte", + "uptimeAlertNoRecipients": "Aucun destinataire", + "uptimeAlertNoRecipientsDescription": "Veuillez ajouter au moins un utilisateur, rôle ou e-mail à notifier.", + "uptimeAlertCreated": "Alerte créé", + "uptimeAlertCreatedDescription": "Vous serez notifié lorsque ce statut changera.", + "uptimeAlertCreateFailed": "Échec de la création de l'alerte", + "webhookUrlLabel": "URL", + "webhookHeaderKeyPlaceholder": "Clé", + "webhookHeaderValuePlaceholder": "Valeur", + "alertLabel": "Alerte", + "domainPickerWildcardSubdomainNotAllowed": "Les sous-domaines Joker ne sont pas autorisés.", + "domainPickerWildcardCertWarning": "Les ressources Joker peuvent nécessiter une configuration supplémentaire pour fonctionner correctement.", + "domainPickerWildcardCertWarningLink": "En savoir plus", + "health": "Santé" } diff --git a/messages/it-IT.json b/messages/it-IT.json index e1e3a586e..9e810c259 100644 --- a/messages/it-IT.json +++ b/messages/it-IT.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "Ho copiato la configurazione", "searchSitesProgress": "Cerca siti...", "siteAdd": "Aggiungi Sito", + "sitesTableViewPublicResources": "Visualizza Risorse Pubbliche", + "sitesTableViewPrivateResources": "Visualizza Risorse Private", "siteInstallNewt": "Installa Newt", "siteInstallNewtDescription": "Esegui Newt sul tuo sistema", "WgConfiguration": "Configurazione WireGuard", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "Il sito è stato aggiornato.", "siteGeneralDescription": "Configura le impostazioni generali per questo sito", "siteSettingDescription": "Configura le impostazioni del sito", + "siteResourcesTab": "Risorse", + "siteResourcesNoneOnSite": "Questo sito non ha ancora risorse pubbliche o private.", + "siteResourcesSectionPublic": "Risorse Pubbliche", + "siteResourcesSectionPrivate": "Risorse Private", + "siteResourcesSectionPublicDescription": "Risorse esposte esternamente attraverso domini o porte.", + "siteResourcesSectionPrivateDescription": "Risorse disponibili sulla tua rete privata tramite il sito.", + "siteResourcesViewAllPublic": "Visualizza tutte le risorse", + "siteResourcesViewAllPrivate": "Visualizza tutte le risorse", + "siteResourcesDialogDescription": "Panoramica delle risorse pubbliche e private associate a questo sito.", + "siteResourcesShowMore": "Mostra Altro", + "siteResourcesPermissionDenied": "Non hai il permesso di elencare queste risorse.", + "siteResourcesEmptyPublic": "Ancora nessuna risorsa pubblica punta a questo sito.", + "siteResourcesEmptyPrivate": "Ancora nessuna risorsa privata è associata a questo sito.", + "siteResourcesHowToAccess": "Come accedere", + "siteResourcesTargetsOnSite": "Obiettivi su questo sito", "siteSetting": "Impostazioni del sito {siteName}", "siteNewtTunnel": "Nuovo Sito (Consigliato)", "siteNewtTunnelDescription": "Modo più semplice per creare un entrypoint in qualsiasi rete. Nessuna configurazione aggiuntiva.", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "I cambiamenti di stato del controllo di salute", "alertingTriggerResourceHealthy": "Risorsa in buona salute", "alertingTriggerResourceUnhealthy": "Risorsa in cattiva salute", + "alertingTriggerResourceDegraded": "Risorsa degradata", "alertingSearchHealthChecks": "Cerca controlli di salute…", "alertingHealthChecksEmpty": "Nessun controllo di salute disponibile.", "alertingTriggerResourceToggle": "Variazioni di stato della risorsa", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "Crea l'account amministratore del server iniziale. Può esistere solo un amministratore del server. È sempre possibile modificare queste credenziali in seguito.", "createAdminAccount": "Crea Account Admin", "setupErrorCreateAdmin": "Si è verificato un errore durante la creazione dell'account amministratore del server.", - "certificateStatus": "Stato del Certificato", + "certificateStatus": "Certificato", + "certificateStatusAutoRefreshHint": "Lo stato si aggiorna automaticamente.", "loading": "Caricamento", "loadingAnalytics": "Caricamento Delle Analisi", "restart": "Riavvia", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "Configura Controllo Salute", "configureHealthCheckDescription": "Imposta il monitoraggio della salute per {target}", "enableHealthChecks": "Abilita i Controlli di Salute", + "healthCheckDisabledStateDescription": "Quando disabilitato, il sito non eseguirà controlli di integrità e lo stato sarà considerato sconosciuto.", "enableHealthChecksDescription": "Monitorare lo stato di salute di questo obiettivo. Se necessario, è possibile monitorare un endpoint diverso da quello del bersaglio.", "healthScheme": "Metodo", "healthSelectScheme": "Seleziona Metodo", @@ -1947,6 +1967,8 @@ "httpMethod": "Metodo HTTP", "selectHttpMethod": "Seleziona metodo HTTP", "domainPickerSubdomainLabel": "Sottodominio", + "domainPickerWildcard": "Jolly", + "domainPickerWildcardPaidOnly": "Sotto-domini wildcard sono una funzione a pagamento. Si prega di aggiornare per accedere a questa funzione.", "domainPickerBaseDomainLabel": "Dominio Base", "domainPickerSearchDomains": "Cerca domini...", "domainPickerNoDomainsFound": "Nessun dominio trovato", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "Questo indirizzo fa parte della subnet di utilità dell'organizzazione. È usato per risolvere i record alias usando la risoluzione DNS interna.", "resourcesTableClients": "Client", "resourcesTableAndOnlyAccessibleInternally": "e sono accessibili solo internamente quando connessi con un client.", - "resourcesTableNoTargets": "Nessun obiettivo", "resourcesTableHealthy": "Sano", "resourcesTableDegraded": "Degraded", - "resourcesTableOffline": "Offline", + "resourcesTableUnhealthy": "Non Sano", "resourcesTableUnknown": "Sconosciuto", "resourcesTableNotMonitored": "Non monitorato", + "resourcesTableNoTargets": "Nessun obiettivo", "editInternalResourceDialogEditClientResource": "Modifica Risorse Private", "editInternalResourceDialogUpdateResourceProperties": "Aggiorna la configurazione delle risorse e i controlli di accesso per {resourceName}", "editInternalResourceDialogResourceProperties": "Proprietà della Risorsa", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "Verificato", "domainPickerUnverified": "Non Verificato", "domainPickerManual": "Manuale", - "domainPickerInvalidSubdomainStructure": "Questo sottodominio contiene caratteri o struttura non validi. Sarà sanificato automaticamente quando si salva.", + "domainPickerInvalidSubdomainStructure": "I caratteri non validi saranno sanitizzati quando salvati.", "domainPickerError": "Errore", "domainPickerErrorLoadDomains": "Impossibile caricare i domini dell'organizzazione", "domainPickerErrorCheckAvailability": "Impossibile verificare la disponibilità del dominio", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "Aggiungi Clienti", "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.", + "internalResourceFormMultiSiteRoutingHelp": "Selezionare più siti consente un routing resiliente e Failover per alta disponibilità.", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "Scopri di più", "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.", @@ -2908,6 +2932,7 @@ "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.", + "privateMaintenanceScreenSteps": "Una volta connesso, se ancora visualizzi questo messaggio, la cache DNS del tuo browser potrebbe ancora puntare al vecchio indirizzo. Per risolvere: chiudi e riapri completamente questa scheda o il tuo browser, quindi torna su questa pagina.", "maintenanceTime": "es. 2 ore, 1 novembre alle 17:00", "maintenanceEstimatedTimeDescription": "Quando prevedi che la manutenzione sarà completata", "editDomain": "Modifica Dominio", @@ -3142,5 +3167,39 @@ "idpDeleteAllOrgsMenu": "Elimina", "publicIpEndpoint": "Endpoint", "lastTriggeredAt": "Ultimo trigger", - "reject": "Rifiuta" + "reject": "Rifiuta", + "uptimeDaysAgo": "{count} giorni fa", + "uptimeToday": "Oggi", + "uptimeNoDataAvailable": "Nessun dato disponibile", + "uptimeSuffix": "tempo di attività", + "uptimeDowntimeSuffix": "tempo di inattività", + "uptimeTooltipUptimeLabel": "Tempo di attività", + "uptimeTooltipDowntimeLabel": "Tempo di inattività", + "uptimeOngoing": "in corso", + "uptimeNoMonitoringData": "Nessun dato di monitoraggio", + "uptimeNoData": "Nessun dato", + "uptimeMiniBarDown": "Giù", + "uptimeSectionTitle": "Tempo di attività", + "uptimeSectionDescription": "Disponibilità negli ultimi {days} giorni", + "uptimeAddAlert": "Aggiungi Avviso", + "uptimeViewAlerts": "Visualizza Avvisi", + "uptimeCreateEmailAlert": "Crea Avviso Email", + "uptimeAlertDescriptionSite": "Ricevi notifica via email quando questo sito va offline o torna online.", + "uptimeAlertDescriptionResource": "Ricevi notifica via email quando questa risorsa va offline o torna online.", + "uptimeAlertNamePlaceholder": "Nome avviso", + "uptimeAdditionalEmails": "Email aggiuntive", + "uptimeCreateAlert": "Crea Avviso", + "uptimeAlertNoRecipients": "Nessun destinatario", + "uptimeAlertNoRecipientsDescription": "Si prega di aggiungere almeno un utente, ruolo o e-mail da notificare.", + "uptimeAlertCreated": "Avviso creato", + "uptimeAlertCreatedDescription": "Riceverai una notifica quando questo cambia stato.", + "uptimeAlertCreateFailed": "Errore nella creazione dell'avviso", + "webhookUrlLabel": "URL", + "webhookHeaderKeyPlaceholder": "Chiave", + "webhookHeaderValuePlaceholder": "Valore", + "alertLabel": "Avviso", + "domainPickerWildcardSubdomainNotAllowed": "I sottodomini wildcard non sono permessi.", + "domainPickerWildcardCertWarning": "Le risorse wildcard potrebbero richiedere configurazioni aggiuntive per funzionare correttamente.", + "domainPickerWildcardCertWarningLink": "Scopri di più", + "health": "Salute" } diff --git a/messages/ko-KR.json b/messages/ko-KR.json index c3e08dca4..e98fc65fa 100644 --- a/messages/ko-KR.json +++ b/messages/ko-KR.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "구성을 복사했습니다.", "searchSitesProgress": "사이트 검색...", "siteAdd": "사이트 추가", + "sitesTableViewPublicResources": "공용 리소스 보기", + "sitesTableViewPrivateResources": "개인 리소스 보기", "siteInstallNewt": "Newt 설치", "siteInstallNewtDescription": "시스템에서 Newt 실행하기", "WgConfiguration": "WireGuard 구성", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "사이트가 업데이트되었습니다.", "siteGeneralDescription": "이 사이트에 대한 일반 설정을 구성하세요.", "siteSettingDescription": "사이트에서 설정을 구성하세요.", + "siteResourcesTab": "리소스", + "siteResourcesNoneOnSite": "이 사이트에는 아직 공용 또는 개인 리소스가 없습니다.", + "siteResourcesSectionPublic": "공용 리소스", + "siteResourcesSectionPrivate": "개인 리소스", + "siteResourcesSectionPublicDescription": "도메인이나 포트를 통해 외부에 노출되는 리소스.", + "siteResourcesSectionPrivateDescription": "사이트를 통해 개인 네트워크에서 사용할 수 있는 리소스.", + "siteResourcesViewAllPublic": "모든 리소스 보기", + "siteResourcesViewAllPrivate": "모든 리소스 보기", + "siteResourcesDialogDescription": "이 사이트와 연관된 공용 및 개인 리소스의 개요.", + "siteResourcesShowMore": "더 보기", + "siteResourcesPermissionDenied": "이 리소스를 나열할 권한이 없습니다.", + "siteResourcesEmptyPublic": "이 사이트에는 아직 대상 공용 리소스가 없습니다.", + "siteResourcesEmptyPrivate": "이 사이트와 연결된 개인 리소스가 아직 없습니다.", + "siteResourcesHowToAccess": "액세스 방법", + "siteResourcesTargetsOnSite": "이 사이트의 대상", "siteSetting": "{siteName} 설정", "siteNewtTunnel": "뉴트 사이트 (추천)", "siteNewtTunnelDescription": "네트워크의 진입점을 생성하는 가장 쉬운 방법입니다. 추가 설정이 필요 없습니다.", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "상태 확인 상태 변경", "alertingTriggerResourceHealthy": "리소스 정상", "alertingTriggerResourceUnhealthy": "리소스 비정상", + "alertingTriggerResourceDegraded": "리소스 열화", "alertingSearchHealthChecks": "상태 확인 검색…", "alertingHealthChecksEmpty": "사용 가능한 상태 확인이 없습니다.", "alertingTriggerResourceToggle": "리소스 상태 변경", @@ -1493,7 +1511,7 @@ "standaloneHcEditTitle": "상태 확인 편집", "standaloneHcDescription": "알림 규칙에 사용할 HTTP 또는 TCP 상태 확인을 구성하세요.", "standaloneHcNameLabel": "이름", - "standaloneHcNamePlaceholder": "My HTTP Monitor", + "standaloneHcNamePlaceholder": "나의 HTTP 모니터", "standaloneHcDeleteTitle": "상태 확인 삭제", "standaloneHcDeleteQuestion": "이 상태 확인을 삭제하겠습니까.", "standaloneHcDeleted": "상태 확인 삭제됨", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "초기 서버 관리자 계정을 생성하세요. 서버 관리자 계정은 하나만 존재할 수 있습니다. 이러한 자격 증명은 나중에 언제든지 변경할 수 있습니다.", "createAdminAccount": "관리자 계정 생성", "setupErrorCreateAdmin": "서버 관리자 계정을 생성하는 동안 오류가 발생했습니다.", - "certificateStatus": "인증서 상태", + "certificateStatus": "인증서", + "certificateStatusAutoRefreshHint": "상태가 자동으로 새로 고쳐집니다.", "loading": "로딩 중", "loadingAnalytics": "분석 로딩 중", "restart": "재시작", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "상태 확인 설정", "configureHealthCheckDescription": "{target}에 대한 상태 모니터링 설정", "enableHealthChecks": "상태 확인 활성화", + "healthCheckDisabledStateDescription": "비활성화되면 이 사이트가 상태 확인을 수행하지 않으며 상태가 알 수 없는 것으로 간주됩니다.", "enableHealthChecksDescription": "이 대상을 모니터링하여 건강 상태를 확인하세요. 필요에 따라 대상과 다른 엔드포인트를 모니터링할 수 있습니다.", "healthScheme": "방법", "healthSelectScheme": "방법 선택", @@ -1947,6 +1967,8 @@ "httpMethod": "HTTP 메소드", "selectHttpMethod": "HTTP 메소드 선택", "domainPickerSubdomainLabel": "서브도메인", + "domainPickerWildcard": "와일드카드", + "domainPickerWildcardPaidOnly": "와일드카드 서브도메인은 유료 기능입니다. 이 기능에 액세스하려면 업그레이드하세요.", "domainPickerBaseDomainLabel": "기본 도메인", "domainPickerSearchDomains": "도메인 검색...", "domainPickerNoDomainsFound": "찾을 수 없는 도메인이 없습니다", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "이 주소는 조직의 유틸리티 서브넷의 일부로, 내부 DNS 해석을 사용하여 별칭 레코드를 해석하는 데 사용됩니다.", "resourcesTableClients": "클라이언트", "resourcesTableAndOnlyAccessibleInternally": "클라이언트와 연결되었을 때만 내부적으로 접근 가능합니다.", - "resourcesTableNoTargets": "대상 없음", "resourcesTableHealthy": "정상", "resourcesTableDegraded": "저하됨", - "resourcesTableOffline": "오프라인", + "resourcesTableUnhealthy": "비정상", "resourcesTableUnknown": "알 수 없음", "resourcesTableNotMonitored": "모니터링되지 않음", + "resourcesTableNoTargets": "대상 없음", "editInternalResourceDialogEditClientResource": "비공개 리소스 수정", "editInternalResourceDialogUpdateResourceProperties": "{resourceName}의 리소스 속성과 대상 구성을 업데이트하세요", "editInternalResourceDialogResourceProperties": "리소스 속성", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "검증됨", "domainPickerUnverified": "검증되지 않음", "domainPickerManual": "수동", - "domainPickerInvalidSubdomainStructure": "이 하위 도메인은 잘못된 문자 또는 구조를 포함하고 있습니다. 저장 시 자동으로 정리됩니다.", + "domainPickerInvalidSubdomainStructure": "잘못된 문자는 저장 시 새니타이즈됩니다.", "domainPickerError": "오류", "domainPickerErrorLoadDomains": "조직 도메인 로드 실패", "domainPickerErrorCheckAvailability": "도메인 가용성 확인 실패", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "클라이언트 추가", "editInternalResourceDialogDestinationLabel": "대상지", "editInternalResourceDialogDestinationDescription": "내부 리소스의 목적지 주소를 지정하세요. 선택한 모드에 따라 이 주소는 호스트명, IP 주소, 또는 CIDR 범위가 될 수 있습니다. 더욱 쉽게 식별할 수 있도록 내부 DNS 별칭을 설정할 수 있습니다.", + "internalResourceFormMultiSiteRoutingHelp": "다중 사이트를 선택하면 높은 가용성을 위해 회복력 있는 라우팅 및 페일오버가 가능해집니다.", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "자세히 알아보기", "editInternalResourceDialogPortRestrictionsDescription": "특정 TCP/UDP 포트에 대한 접근을 제한하거나 모든 포트를 허용/차단하십시오.", "createInternalResourceDialogHttpConfiguration": "HTTP 구성", "createInternalResourceDialogHttpConfigurationDescription": "이 리소스에 HTTP 또는 HTTPS로 도달하기 위한 도메인을 선택하세요.", @@ -2908,6 +2932,7 @@ "maintenancePageTimeTitle": "예상 완료 시간(선택 사항)", "privateMaintenanceScreenTitle": "프라이빗 플레이스홀더 화면", "privateMaintenanceScreenMessage": "이 도메인은 개인 리소스에서 사용 중입니다. Pangolin 클라이언트를 사용하여 이 리소스에 액세스하세요.", + "privateMaintenanceScreenSteps": "연결된 후에도 이 메시지가 보이면 브라우저의 DNS 캐시가 여전히 이전 주소를 가리킬 수 있습니다. 이를 해결하려면 이 탭이나 브라우저를 완전히 닫고 다시 열고 이 페이지로 돌아가세요.", "maintenanceTime": "예: 2시간, 11월 1일 오후 5시", "maintenanceEstimatedTimeDescription": "유지보수가 완료될 것으로 예상되는 시간", "editDomain": "도메인 수정", @@ -3142,5 +3167,39 @@ "idpDeleteAllOrgsMenu": "삭제", "publicIpEndpoint": "엔드포인트", "lastTriggeredAt": "마지막 트리거", - "reject": "거부" + "reject": "거부", + "uptimeDaysAgo": "{count}일 전", + "uptimeToday": "오늘", + "uptimeNoDataAvailable": "데이터가 없습니다", + "uptimeSuffix": "가동 시간", + "uptimeDowntimeSuffix": "다운타임", + "uptimeTooltipUptimeLabel": "가동 시간", + "uptimeTooltipDowntimeLabel": "다운타임", + "uptimeOngoing": "진행 중", + "uptimeNoMonitoringData": "모니터링 데이터 없음", + "uptimeNoData": "데이터 없음", + "uptimeMiniBarDown": "중단됨", + "uptimeSectionTitle": "가동 시간", + "uptimeSectionDescription": "지난 {days}일 동안의 가용성", + "uptimeAddAlert": "알림 추가", + "uptimeViewAlerts": "알림 보기", + "uptimeCreateEmailAlert": "이메일 알림 생성", + "uptimeAlertDescriptionSite": "이 사이트가 오프라인 되거나 다시 온라인 될 때 이메일로 알림을 받습니다.", + "uptimeAlertDescriptionResource": "이 리소스가 오프라인 되거나 다시 온라인 될 때 이메일로 알림을 받습니다.", + "uptimeAlertNamePlaceholder": "알림 이름", + "uptimeAdditionalEmails": "추가 이메일", + "uptimeCreateAlert": "알림 생성", + "uptimeAlertNoRecipients": "수신자 없음", + "uptimeAlertNoRecipientsDescription": "통지를 받을 사용자, 역할 또는 이메일을 최소 한 개 추가하세요.", + "uptimeAlertCreated": "알림 생성됨", + "uptimeAlertCreatedDescription": "상태가 변경되면 통지를 받습니다.", + "uptimeAlertCreateFailed": "알림 생성 실패", + "webhookUrlLabel": "URL", + "webhookHeaderKeyPlaceholder": "키", + "webhookHeaderValuePlaceholder": "값", + "alertLabel": "알림", + "domainPickerWildcardSubdomainNotAllowed": "와일드카드 서브도메인은 허용되지 않습니다.", + "domainPickerWildcardCertWarning": "와일드카드 리소스는 올바르게 작동하려면 추가 구성이 필요할 수 있습니다.", + "domainPickerWildcardCertWarningLink": "자세히 알아보기", + "health": "건강" } diff --git a/messages/nb-NO.json b/messages/nb-NO.json index 4cf5159d8..d6c674801 100644 --- a/messages/nb-NO.json +++ b/messages/nb-NO.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "Jeg har kopiert konfigurasjonen", "searchSitesProgress": "Søker i områder...", "siteAdd": "Legg til område", + "sitesTableViewPublicResources": "Vis offentlige ressurser", + "sitesTableViewPrivateResources": "Vis private ressurser", "siteInstallNewt": "Installer Newt", "siteInstallNewtDescription": "Få Newt til å kjøre på systemet ditt", "WgConfiguration": "WireGuard Konfigurasjon", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "Området har blitt oppdatert.", "siteGeneralDescription": "Konfigurer de generelle innstillingene for dette området", "siteSettingDescription": "Konfigurere innstillingene på nettstedet", + "siteResourcesTab": "Ressurser", + "siteResourcesNoneOnSite": "Dette nettstedet har ingen offentlige eller private ressurser enda.", + "siteResourcesSectionPublic": "Offentlige ressurser", + "siteResourcesSectionPrivate": "Private ressurser", + "siteResourcesSectionPublicDescription": "Ressurser eksponert eksternt gjennom domener eller porter.", + "siteResourcesSectionPrivateDescription": "Ressurser tilgjengelig på ditt private nettverk gjennom nettstedet.", + "siteResourcesViewAllPublic": "Vis alle ressurser", + "siteResourcesViewAllPrivate": "Vis alle ressurser", + "siteResourcesDialogDescription": "Oversikt over offentlige og private ressurser assosiert med dette nettstedet.", + "siteResourcesShowMore": "Vis mer", + "siteResourcesPermissionDenied": "Du har ikke tillatelse til å liste opp disse ressursene.", + "siteResourcesEmptyPublic": "Ingen offentlige ressurser retter seg mot dette nettstedet enda.", + "siteResourcesEmptyPrivate": "Ingen private ressurser er assosiert med dette nettstedet enda.", + "siteResourcesHowToAccess": "Hvordan få tilgang", + "siteResourcesTargetsOnSite": "Mål på dette nettstedet", "siteSetting": "{siteName} Innstillinger", "siteNewtTunnel": "Nyhetsnettsted (anbefalt)", "siteNewtTunnelDescription": "Lekkeste måte å lage et inngangspunkt til ethvert nettverk. Ingen ekstra oppsett på.", @@ -1404,7 +1421,7 @@ "alertingSpecificResourcesDescription": "Velg spesifikke ressurser for overvåking", "alertingSelectResources": "Velg ressurser…", "alertingResourcesSelected": "{count} ressurser valgt", - "alertingResourcesEmpty": "No resources with targets in the first 10 results.", + "alertingResourcesEmpty": "Ingen ressurser med mål i de første 10 resultatene.", "alertingSectionTrigger": "Utløser", "alertingTrigger": "Når skal det varsles", "alertingTriggerSiteOnline": "Nettsted er online", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "Endringer i helsekontrollstatus", "alertingTriggerResourceHealthy": "Ressurs sunn", "alertingTriggerResourceUnhealthy": "Ressurs usunn", + "alertingTriggerResourceDegraded": "Ressurs forringet", "alertingSearchHealthChecks": "Søk i helsekontroller…", "alertingHealthChecksEmpty": "Ingen tilgjengelige helsekontroller.", "alertingTriggerResourceToggle": "Endringer i ressursstatus", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "Opprett den første serveradministratorkontoen. Det kan bare finnes én serveradministrator. Du kan alltid endre denne påloggingsinformasjonen senere.", "createAdminAccount": "Opprett administratorkonto", "setupErrorCreateAdmin": "En feil oppstod under opprettelsen av serveradministratorkontoen.", - "certificateStatus": "Sertifikatstatus", + "certificateStatus": "Sertifikat", + "certificateStatusAutoRefreshHint": "Status oppdateres automatisk.", "loading": "Laster inn", "loadingAnalytics": "Laster inn analyser", "restart": "Start på nytt", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "Konfigurer Helsekontroll", "configureHealthCheckDescription": "Sett opp helsekontroll for {target}", "enableHealthChecks": "Aktiver Helsekontroller", + "healthCheckDisabledStateDescription": "Når deaktivert, vil ikke nettstedet utføre helsekontroller, og tilstanden vil anses som ukjent.", "enableHealthChecksDescription": "Overvåk helsen til dette målet. Du kan overvåke et annet endepunkt enn målet hvis nødvendig.", "healthScheme": "Metode", "healthSelectScheme": "Velg metode", @@ -1947,6 +1967,8 @@ "httpMethod": "HTTP-metode", "selectHttpMethod": "Velg HTTP-metode", "domainPickerSubdomainLabel": "Underdomene", + "domainPickerWildcard": "Jokertegn", + "domainPickerWildcardPaidOnly": "Jokertegnsubdomener er en betalt funksjon. Vennligst oppgrader for å få tilgang til denne funksjonen.", "domainPickerBaseDomainLabel": "Grunndomene", "domainPickerSearchDomains": "Søk i domener...", "domainPickerNoDomainsFound": "Ingen domener funnet", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "Denne adressen er en del av organisasjonens undernettverk. Den brukes til å løse aliasposter ved hjelp av intern DNS-oppløsning.", "resourcesTableClients": "Klienter", "resourcesTableAndOnlyAccessibleInternally": "og er kun tilgjengelig internt når de er koblet til med en klient.", - "resourcesTableNoTargets": "Ingen mål", "resourcesTableHealthy": "Frisk", "resourcesTableDegraded": "Nedgradert", - "resourcesTableOffline": "Frakoblet", + "resourcesTableUnhealthy": "Usunn", "resourcesTableUnknown": "Ukjent", "resourcesTableNotMonitored": "Ikke overvåket", + "resourcesTableNoTargets": "Ingen mål", "editInternalResourceDialogEditClientResource": "Rediger Private Ressurser", "editInternalResourceDialogUpdateResourceProperties": "Oppdater ressurskonfigurasjonen og få tilgangskontroller for {resourceName}", "editInternalResourceDialogResourceProperties": "Ressursegenskaper", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "Bekreftet", "domainPickerUnverified": "Uverifisert", "domainPickerManual": "Manuell", - "domainPickerInvalidSubdomainStructure": "Dette underdomenet inneholder ugyldige tegn eller struktur. Det vil automatisk bli utsatt når du lagrer.", + "domainPickerInvalidSubdomainStructure": "Ugyldige tegn vil bli sanitert når de er lagret.", "domainPickerError": "Feil", "domainPickerErrorLoadDomains": "Kan ikke laste organisasjonens domener", "domainPickerErrorCheckAvailability": "Kunne ikke kontrollere domenetilgjengelighet", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "Legg til klienter", "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.", + "internalResourceFormMultiSiteRoutingHelp": "Valg av flere nettsteder muliggjør motstandskraftig ruting og failover for høy tilgjengelighet.", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "Lær mer", "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.", @@ -2908,6 +2932,7 @@ "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.", + "privateMaintenanceScreenSteps": "Når du er koblet til, hvis du fortsatt ser denne meldingen, peker kanskje DNS-cachen til nettleseren din fortsatt til den gamle adressen. For å rette på dette: lukk og åpne denne fanen eller nettleseren på nytt, og naviger deretter tilbake til denne siden.", "maintenanceTime": "f.eks. 2 timer, 1. november kl. 17:00", "maintenanceEstimatedTimeDescription": "Når du forventer at vedlikeholdet er ferdigstilt", "editDomain": "Rediger domene", @@ -3142,5 +3167,39 @@ "idpDeleteAllOrgsMenu": "Slett", "publicIpEndpoint": "Endepunkt", "lastTriggeredAt": "Siste utløste", - "reject": "Avvis" + "reject": "Avvis", + "uptimeDaysAgo": "{count} days ago", + "uptimeToday": "I dag", + "uptimeNoDataAvailable": "Ingen data tilgjengelig", + "uptimeSuffix": "oppetid", + "uptimeDowntimeSuffix": "nedetid", + "uptimeTooltipUptimeLabel": "Oppetid", + "uptimeTooltipDowntimeLabel": "Nedetid", + "uptimeOngoing": "pågående", + "uptimeNoMonitoringData": "Ingen overvåkingsdata", + "uptimeNoData": "Ingen data", + "uptimeMiniBarDown": "Nede", + "uptimeSectionTitle": "Oppetid", + "uptimeSectionDescription": "Tilgjengelighet de siste {days} dagene", + "uptimeAddAlert": "Legg til varsling", + "uptimeViewAlerts": "Vis varsler", + "uptimeCreateEmailAlert": "Opprett e-postvarsel", + "uptimeAlertDescriptionSite": "Få beskjed på e-post når dette nettstedet går offline eller kommer tilbake online.", + "uptimeAlertDescriptionResource": "Få beskjed på e-post når denne ressursen går offline eller kommer tilbake online.", + "uptimeAlertNamePlaceholder": "Varslingsnavn", + "uptimeAdditionalEmails": "Flere e-poster", + "uptimeCreateAlert": "Opprett varsling", + "uptimeAlertNoRecipients": "Ingen mottakere", + "uptimeAlertNoRecipientsDescription": "Vennligst legg til minst én bruker, rolle, eller e-post for å varsle.", + "uptimeAlertCreated": "Varsel opprettet", + "uptimeAlertCreatedDescription": "Du vil bli varslet når dette endrer status.", + "uptimeAlertCreateFailed": "Kunne ikke opprette varsel", + "webhookUrlLabel": "URL", + "webhookHeaderKeyPlaceholder": "Nøkkel", + "webhookHeaderValuePlaceholder": "Verdi", + "alertLabel": "Varsel", + "domainPickerWildcardSubdomainNotAllowed": "Jokertegnsubdomener er ikke tillatt.", + "domainPickerWildcardCertWarning": "Jokertegnressurser kan kreve ekstra konfigurasjon for å fungere skikkelig.", + "domainPickerWildcardCertWarningLink": "Lær mer", + "health": "Helse" } diff --git a/messages/nl-NL.json b/messages/nl-NL.json index 855ae603d..09096c424 100644 --- a/messages/nl-NL.json +++ b/messages/nl-NL.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "Ik heb de configuratie gekopieerd", "searchSitesProgress": "Sites zoeken...", "siteAdd": "Site toevoegen", + "sitesTableViewPublicResources": "Openbare bronnen bekijken", + "sitesTableViewPrivateResources": "Privébronnen bekijken", "siteInstallNewt": "Installeer Newt", "siteInstallNewtDescription": "Laat Newt draaien op uw systeem", "WgConfiguration": "WireGuard Configuratie", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "De site is bijgewerkt.", "siteGeneralDescription": "Algemene instellingen voor deze site configureren", "siteSettingDescription": "Configureer de instellingen van de site", + "siteResourcesTab": "Bronnen", + "siteResourcesNoneOnSite": "Deze site heeft nog geen openbare of privébronnen.", + "siteResourcesSectionPublic": "Openbare bronnen", + "siteResourcesSectionPrivate": "Privébronnen", + "siteResourcesSectionPublicDescription": "Bronnen extern blootgesteld via domeinen of poorten.", + "siteResourcesSectionPrivateDescription": "Bronnen beschikbaar op uw privénetwerk via de site.", + "siteResourcesViewAllPublic": "Bekijk alle bronnen", + "siteResourcesViewAllPrivate": "Bekijk alle bronnen", + "siteResourcesDialogDescription": "Overzicht van openbare en privébronnen die geassocieerd zijn met deze site.", + "siteResourcesShowMore": "Meer weergeven", + "siteResourcesPermissionDenied": "U heeft geen toestemming om deze bronnen te vermelden.", + "siteResourcesEmptyPublic": "Geen openbare bronnen richten zich nog op deze site.", + "siteResourcesEmptyPrivate": "Er zijn nog geen privébronnen gekoppeld aan deze site.", + "siteResourcesHowToAccess": "Hoe te openen", + "siteResourcesTargetsOnSite": "Doelen op deze site", "siteSetting": "{siteName} instellingen", "siteNewtTunnel": "Nieuwste site (Aanbevolen)", "siteNewtTunnelDescription": "Makkelijkste manier om een ingangspunt in een netwerk te maken. Geen extra opzet.", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "Gezondheidscontrole status verandert", "alertingTriggerResourceHealthy": "Bron gezond", "alertingTriggerResourceUnhealthy": "Bron ongezond", + "alertingTriggerResourceDegraded": "Bron gedegradeerd", "alertingSearchHealthChecks": "Zoek gezondheidscontroles…", "alertingHealthChecksEmpty": "Geen gezondheidscontroles beschikbaar.", "alertingTriggerResourceToggle": "Bronstatus wijzigt", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "Maak het eerste serverbeheeraccount aan. Er kan slechts één serverbeheerder bestaan. U kunt deze inloggegevens later altijd wijzigen.", "createAdminAccount": "Maak een beheeraccount aan", "setupErrorCreateAdmin": "Er is een fout opgetreden bij het maken van het serverbeheerdersaccount.", - "certificateStatus": "Certificaatstatus", + "certificateStatus": "Certificaat", + "certificateStatusAutoRefreshHint": "Status ververst automatisch.", "loading": "Bezig met laden", "loadingAnalytics": "Laden van Analytics", "restart": "Herstarten", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "Configureer Gezondheidscontrole", "configureHealthCheckDescription": "Stel gezondheid monitor voor {target} in", "enableHealthChecks": "Inschakelen Gezondheidscontroles", + "healthCheckDisabledStateDescription": "Wanneer uitgeschakeld, zal de site geen gezondheidscontroles uitvoeren en wordt de staat als onbekend beschouwd.", "enableHealthChecksDescription": "Controleer de gezondheid van dit doel. U kunt een ander eindpunt monitoren dan het doel indien vereist.", "healthScheme": "Methode", "healthSelectScheme": "Selecteer methode", @@ -1947,6 +1967,8 @@ "httpMethod": "HTTP-methode", "selectHttpMethod": "Selecteer HTTP-methode", "domainPickerSubdomainLabel": "Subdomein", + "domainPickerWildcard": "Wildcard", + "domainPickerWildcardPaidOnly": "Wildcard-subdomeinen zijn een betaalde functie. Upgrade om deze functie te gebruiken.", "domainPickerBaseDomainLabel": "Basisdomein", "domainPickerSearchDomains": "Zoek domeinen...", "domainPickerNoDomainsFound": "Geen domeinen gevonden", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "Dit adres is onderdeel van het hulpprogramma subnet van de organisatie. Het wordt gebruikt om aliasrecords op te lossen met behulp van interne DNS-resolutie.", "resourcesTableClients": "Clienten", "resourcesTableAndOnlyAccessibleInternally": "en zijn alleen intern toegankelijk wanneer verbonden met een client.", - "resourcesTableNoTargets": "Geen doelen", "resourcesTableHealthy": "Gezond", "resourcesTableDegraded": "Verminderde", - "resourcesTableOffline": "Offline", + "resourcesTableUnhealthy": "Ongezond", "resourcesTableUnknown": "onbekend", "resourcesTableNotMonitored": "Niet gecontroleerd", + "resourcesTableNoTargets": "Geen doelen", "editInternalResourceDialogEditClientResource": "Privépagina bewerken", "editInternalResourceDialogUpdateResourceProperties": "Update de resource configuratie en access control voor {resourceName}", "editInternalResourceDialogResourceProperties": "Bron eigenschappen", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "Geverifieerd", "domainPickerUnverified": "Ongeverifieerd", "domainPickerManual": "Handleiding", - "domainPickerInvalidSubdomainStructure": "Dit subdomein bevat ongeldige tekens of structuur. Het zal automatisch worden gesaneerd wanneer u opslaat.", + "domainPickerInvalidSubdomainStructure": "Ongeldige tekens worden gesaneerd bij het opslaan.", "domainPickerError": "Foutmelding", "domainPickerErrorLoadDomains": "Fout bij het laden van organisatiedomeinen", "domainPickerErrorCheckAvailability": "Kan domein beschikbaarheid niet controleren", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "Clienten toevoegen", "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.", + "internalResourceFormMultiSiteRoutingHelp": "Selecteren van meerdere sites maakt veerkrachtige routing en failover mogelijk voor hoge beschikbaarheid.", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "Meer informatie", "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.", @@ -2908,6 +2932,7 @@ "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.", + "privateMaintenanceScreenSteps": "Eenmaal verbonden, als u dit bericht nog steeds ziet, kan het DNS-cache van uw browser nog steeds naar het oude adres wijzen. Om dit te corrigeren: sluit en heropen dit tabblad, of uw browser, dan navigeer weer naar deze pagina.", "maintenanceTime": "bijv. 2 uur, 1 nov om 17:00", "maintenanceEstimatedTimeDescription": "Wanneer u verwacht dat het onderhoud voltooid is", "editDomain": "Domein bewerken", @@ -3142,5 +3167,39 @@ "idpDeleteAllOrgsMenu": "Verwijderen", "publicIpEndpoint": "Eindpunt", "lastTriggeredAt": "Laatste Trigger", - "reject": "Afwijzen" + "reject": "Afwijzen", + "uptimeDaysAgo": "{count} days ago", + "uptimeToday": "Vandaag", + "uptimeNoDataAvailable": "Geen gegevens beschikbaar", + "uptimeSuffix": "werktijd", + "uptimeDowntimeSuffix": "uitvaltijd", + "uptimeTooltipUptimeLabel": "Werktijd", + "uptimeTooltipDowntimeLabel": "Uitvaltijd", + "uptimeOngoing": "lopend", + "uptimeNoMonitoringData": "Geen monitoringgegevens", + "uptimeNoData": "Geen gegevens", + "uptimeMiniBarDown": "Onder", + "uptimeSectionTitle": "Werktijd", + "uptimeSectionDescription": "Beschikbaarheid over de laatste {days} dagen", + "uptimeAddAlert": "Alarm toevoegen", + "uptimeViewAlerts": "Meldingen bekijken", + "uptimeCreateEmailAlert": "E-mailalert aanmaken", + "uptimeAlertDescriptionSite": "Ontvang een e-mailbericht wanneer deze site offline gaat of weer online komt.", + "uptimeAlertDescriptionResource": "Ontvang een e-mailbericht wanneer deze bron offline gaat of weer online komt.", + "uptimeAlertNamePlaceholder": "Waarschuwingsnaam", + "uptimeAdditionalEmails": "Extra e-mails", + "uptimeCreateAlert": "Alarm aanmaken", + "uptimeAlertNoRecipients": "Geen ontvangers", + "uptimeAlertNoRecipientsDescription": "Voeg ten minste één gebruiker, rol of e-mail toe om te melden.", + "uptimeAlertCreated": "Alarm aangemaakt", + "uptimeAlertCreatedDescription": "U wordt op de hoogte gebracht wanneer dit van status verandert.", + "uptimeAlertCreateFailed": "Kon alarm niet aanmaken", + "webhookUrlLabel": "URL", + "webhookHeaderKeyPlaceholder": "Sleutel", + "webhookHeaderValuePlaceholder": "Waarde", + "alertLabel": "Waarschuwing", + "domainPickerWildcardSubdomainNotAllowed": "Wildcard-subdomeinen zijn niet toegestaan.", + "domainPickerWildcardCertWarning": "Wildcard-bronnen hebben mogelijk extra configuratie nodig om correct te werken.", + "domainPickerWildcardCertWarningLink": "Meer informatie", + "health": "Gezondheid" } diff --git a/messages/pl-PL.json b/messages/pl-PL.json index 1fc66fadb..38bbea59a 100644 --- a/messages/pl-PL.json +++ b/messages/pl-PL.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "Skopiowałem konfigurację", "searchSitesProgress": "Szukaj witryn...", "siteAdd": "Dodaj witrynę", + "sitesTableViewPublicResources": "Zobacz zasoby publiczne", + "sitesTableViewPrivateResources": "Zobacz zasoby prywatne", "siteInstallNewt": "Zainstaluj Newt", "siteInstallNewtDescription": "Uruchom Newt w swoim systemie", "WgConfiguration": "Konfiguracja WireGuard", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "Strona została zaktualizowana.", "siteGeneralDescription": "Skonfiguruj ustawienia ogólne dla tej witryny", "siteSettingDescription": "Skonfiguruj ustawienia na stronie", + "siteResourcesTab": "Zasoby", + "siteResourcesNoneOnSite": "Ta strona nie ma jeszcze żadnych zasobów publicznych ani prywatnych.", + "siteResourcesSectionPublic": "Zasoby publiczne", + "siteResourcesSectionPrivate": "Zasoby prywatne", + "siteResourcesSectionPublicDescription": "Zasoby eksponowane zewnętrznie przez domeny lub porty.", + "siteResourcesSectionPrivateDescription": "Zasoby dostępne w twojej prywatnej sieci przez stronę.", + "siteResourcesViewAllPublic": "Zobacz wszystkie zasoby", + "siteResourcesViewAllPrivate": "Zobacz wszystkie zasoby", + "siteResourcesDialogDescription": "Przegląd zasobów publicznych i prywatnych związanych z tą stroną.", + "siteResourcesShowMore": "Pokaż więcej", + "siteResourcesPermissionDenied": "Nie masz uprawnień do wyświetlania tych zasobów.", + "siteResourcesEmptyPublic": "Brak publicznych zasobów powiązanych z tą stroną.", + "siteResourcesEmptyPrivate": "Brak prywatnych zasobów powiązanych z tą stroną.", + "siteResourcesHowToAccess": "Jak uzyskać dostęp", + "siteResourcesTargetsOnSite": "Cele na tej stronie", "siteSetting": "Ustawienia {siteName}", "siteNewtTunnel": "Newt Site (Rekomendowane)", "siteNewtTunnelDescription": "Najprostszy sposób na stworzenie punktu wejścia w sieci. Nie ma dodatkowej konfiguracji.", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "Status kontroli zdrowia zmienia się", "alertingTriggerResourceHealthy": "Zasób zdrowy", "alertingTriggerResourceUnhealthy": "Zasób niezdrowy", + "alertingTriggerResourceDegraded": "Zasób pogorszony", "alertingSearchHealthChecks": "Szukaj kontroli zdrowia…", "alertingHealthChecksEmpty": "Brak dostępnych kontroli zdrowia.", "alertingTriggerResourceToggle": "Zmiany statusu zasobu", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "Utwórz początkowe konto administratora serwera. Może istnieć tylko jeden administrator serwera. Zawsze można zmienić te dane uwierzytelniające.", "createAdminAccount": "Utwórz konto administratora", "setupErrorCreateAdmin": "Wystąpił błąd podczas tworzenia konta administratora serwera.", - "certificateStatus": "Status certyfikatu", + "certificateStatus": "Certyfikat", + "certificateStatusAutoRefreshHint": "Status odświeża się automatycznie.", "loading": "Ładowanie", "loadingAnalytics": "Ładowanie Analityki", "restart": "Uruchom ponownie", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "Skonfiguruj Kontrolę Zdrowia", "configureHealthCheckDescription": "Skonfiguruj monitorowanie zdrowia dla {target}", "enableHealthChecks": "Włącz Kontrole Zdrowia", + "healthCheckDisabledStateDescription": "Gdy wyłączone, strona nie będzie wykonywać kontroli zdrowia, a stan zostanie uznany za nieznany.", "enableHealthChecksDescription": "Monitoruj zdrowie tego celu. Możesz monitorować inny punkt końcowy niż docelowy w razie potrzeby.", "healthScheme": "Metoda", "healthSelectScheme": "Wybierz metodę", @@ -1947,6 +1967,8 @@ "httpMethod": "Metoda HTTP", "selectHttpMethod": "Wybierz metodę HTTP", "domainPickerSubdomainLabel": "Poddomena", + "domainPickerWildcard": "Uniwersalny", + "domainPickerWildcardPaidOnly": "Uniwersalne subdomeny są płatną funkcją. Proszę dokonać aktualizacji, aby uzyskać dostęp do tej funkcji.", "domainPickerBaseDomainLabel": "Domen bazowa", "domainPickerSearchDomains": "Szukaj domen...", "domainPickerNoDomainsFound": "Nie znaleziono domen", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "Ten adres jest częścią podsieci użyteczności organizacji. Jest używany do rozwiązywania rekordów aliasu przy użyciu wewnętrznej rozdzielczości DNS.", "resourcesTableClients": "Klientami", "resourcesTableAndOnlyAccessibleInternally": "i są dostępne tylko wewnętrznie po połączeniu z klientem.", - "resourcesTableNoTargets": "Brak celów", "resourcesTableHealthy": "Zdrowe", "resourcesTableDegraded": "Degradacja", - "resourcesTableOffline": "Offline", + "resourcesTableUnhealthy": "Niezdrowy", "resourcesTableUnknown": "Nieznane", "resourcesTableNotMonitored": "Nie monitorowano", + "resourcesTableNoTargets": "Brak celów", "editInternalResourceDialogEditClientResource": "Edytuj Zasoby Prywatne", "editInternalResourceDialogUpdateResourceProperties": "Aktualizuj konfigurację zasobów i kontrolę dostępu dla {resourceName}", "editInternalResourceDialogResourceProperties": "Właściwości zasobów", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "Zweryfikowano", "domainPickerUnverified": "Niezweryfikowane", "domainPickerManual": "Podręcznik", - "domainPickerInvalidSubdomainStructure": "Ta subdomena zawiera nieprawidłowe znaki lub strukturę. Zostanie ona automatycznie oczyszczona po zapisaniu.", + "domainPickerInvalidSubdomainStructure": "Nieprawidłowe znaki zostaną zsanitowane, gdy zostaną zapisane.", "domainPickerError": "Błąd", "domainPickerErrorLoadDomains": "Nie udało się załadować domen organizacji", "domainPickerErrorCheckAvailability": "Nie udało się sprawdzić dostępności domeny", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "Dodaj klientów", "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.", + "internalResourceFormMultiSiteRoutingHelp": "Wybór wielu stron umożliwia odporne trasowanie i awarię dla wysokiej dostępności.", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "Dowiedz się więcej", "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.", @@ -2908,6 +2932,7 @@ "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.", + "privateMaintenanceScreenSteps": "Po połączeniu, jeśli nadal widzisz tę wiadomość, pamięć podręczna DNS przeglądarki może nadal wskazywać na stary adres. Aby to naprawić: zamknij i otwórz ponownie tę kartę lub przeglądarkę, a następnie przejdź z powrotem na tę stronę.", "maintenanceTime": "np. 2 godziny, 1 listopad o 17:00", "maintenanceEstimatedTimeDescription": "Kiedy oczekujesz zakończenia konserwacji", "editDomain": "Edytuj domenę", @@ -3142,5 +3167,39 @@ "idpDeleteAllOrgsMenu": "Usuń", "publicIpEndpoint": "Koniec punktu pracy", "lastTriggeredAt": "Ostatnie Wyzwolenie", - "reject": "Odrzuć" + "reject": "Odrzuć", + "uptimeDaysAgo": "{count} dni temu", + "uptimeToday": "Dzisiaj", + "uptimeNoDataAvailable": "Brak danych dostępnych", + "uptimeSuffix": "czas pracy", + "uptimeDowntimeSuffix": "czas przestoju", + "uptimeTooltipUptimeLabel": "Czas pracy", + "uptimeTooltipDowntimeLabel": "Czas przestoju", + "uptimeOngoing": "w toku", + "uptimeNoMonitoringData": "Brak danych monitorowania", + "uptimeNoData": "Brak danych", + "uptimeMiniBarDown": "Nieaktywny", + "uptimeSectionTitle": "Czas pracy", + "uptimeSectionDescription": "Dostępność za ostatnie {days} dni", + "uptimeAddAlert": "Dodaj Alert", + "uptimeViewAlerts": "Zobacz Alerty", + "uptimeCreateEmailAlert": "Utwórz Alert Email", + "uptimeAlertDescriptionSite": "Otrzymuj powiadomienia e-mail, gdy ta strona jest offline lub wraca online.", + "uptimeAlertDescriptionResource": "Otrzymuj powiadomienia e-mail, gdy to zasób jest offline lub wraca online.", + "uptimeAlertNamePlaceholder": "Nazwa alertu", + "uptimeAdditionalEmails": "Dodatkowe adresy e-mail", + "uptimeCreateAlert": "Utwórz Alert", + "uptimeAlertNoRecipients": "Brak odbiorców", + "uptimeAlertNoRecipientsDescription": "Proszę dodać przynajmniej jednego użytkownika, rolę lub adres email do powiadomienia.", + "uptimeAlertCreated": "Alert utworzony", + "uptimeAlertCreatedDescription": "Zostaniesz powiadomiony, gdy status się zmieni.", + "uptimeAlertCreateFailed": "Nie udało się utworzyć alertu", + "webhookUrlLabel": "URL", + "webhookHeaderKeyPlaceholder": "Klucz", + "webhookHeaderValuePlaceholder": "Wartość", + "alertLabel": "Alert", + "domainPickerWildcardSubdomainNotAllowed": "Uniwersalne subdomeny nie są dozwolone.", + "domainPickerWildcardCertWarning": "Uniwersalne zasoby mogą wymagać dodatkowej konfiguracji, aby działać poprawnie.", + "domainPickerWildcardCertWarningLink": "Dowiedz się więcej", + "health": "Zdrowie" } diff --git a/messages/pt-PT.json b/messages/pt-PT.json index 949f06ac6..2cd442720 100644 --- a/messages/pt-PT.json +++ b/messages/pt-PT.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "Eu copiei a configuração", "searchSitesProgress": "Procurar sites...", "siteAdd": "Adicionar Site", + "sitesTableViewPublicResources": "Visualizar Recursos Públicos", + "sitesTableViewPrivateResources": "Visualizar Recursos Privados", "siteInstallNewt": "Instalar Novo", "siteInstallNewtDescription": "Novo item em execução no seu sistema", "WgConfiguration": "Configuração do WireGuard", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "O site foi atualizado.", "siteGeneralDescription": "Configurar as configurações gerais para este site", "siteSettingDescription": "Configurar as configurações no site", + "siteResourcesTab": "Recursos", + "siteResourcesNoneOnSite": "Este site ainda não possui recursos públicos ou privados.", + "siteResourcesSectionPublic": "Recursos Públicos", + "siteResourcesSectionPrivate": "Recursos Privados", + "siteResourcesSectionPublicDescription": "Recursos expostos externamente por meio de domínios ou portas.", + "siteResourcesSectionPrivateDescription": "Recursos disponíveis na sua rede privada por meio do site.", + "siteResourcesViewAllPublic": "Ver todos os recursos", + "siteResourcesViewAllPrivate": "Ver todos os recursos", + "siteResourcesDialogDescription": "Visão geral dos recursos públicos e privados associados a este site.", + "siteResourcesShowMore": "Mostrar Mais", + "siteResourcesPermissionDenied": "Você não tem permissão para listar estes recursos.", + "siteResourcesEmptyPublic": "Ainda não há recursos públicos direcionados para este site.", + "siteResourcesEmptyPrivate": "Ainda não há recursos privados associados a este site.", + "siteResourcesHowToAccess": "Como acessar", + "siteResourcesTargetsOnSite": "Alvos neste site", "siteSetting": "Configurações do {siteName}", "siteNewtTunnel": "Novo Site (Recomendado)", "siteNewtTunnelDescription": "Maneira mais fácil de criar um ponto de entrada em qualquer rede. Nenhuma configuração extra.", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "Status da verificação de saúde muda", "alertingTriggerResourceHealthy": "Recurso saudável", "alertingTriggerResourceUnhealthy": "Recurso não saudável", + "alertingTriggerResourceDegraded": "Recurso degradado", "alertingSearchHealthChecks": "Pesquisar verificações de saúde…", "alertingHealthChecksEmpty": "Nenhuma verificação de saúde disponível.", "alertingTriggerResourceToggle": "Status do recurso muda", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "Crie a conta de administrador inicial do servidor. Apenas um administrador do servidor pode existir. Você sempre pode alterar essas credenciais posteriormente.", "createAdminAccount": "Criar Conta de Administrador", "setupErrorCreateAdmin": "Ocorreu um erro ao criar a conta de administrador do servidor.", - "certificateStatus": "Status do Certificado", + "certificateStatus": "Certificado", + "certificateStatusAutoRefreshHint": "Status atualiza automaticamente.", "loading": "Carregando", "loadingAnalytics": "Carregando Analytics", "restart": "Reiniciar", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "Configurar Verificação de Saúde", "configureHealthCheckDescription": "Configure a monitorização de saúde para {target}", "enableHealthChecks": "Ativar Verificações de Saúde", + "healthCheckDisabledStateDescription": "Quando desativado, o site não realizará verificações de saúde e o estado será considerado desconhecido.", "enableHealthChecksDescription": "Monitore a saúde deste alvo. Você pode monitorar um ponto de extremidade diferente do alvo, se necessário.", "healthScheme": "Método", "healthSelectScheme": "Selecione o Método", @@ -1947,6 +1967,8 @@ "httpMethod": "Método HTTP", "selectHttpMethod": "Selecionar método HTTP", "domainPickerSubdomainLabel": "Subdomínio", + "domainPickerWildcard": "Coringa", + "domainPickerWildcardPaidOnly": "Subdomínios curinga são um recurso pago. Por favor, atualize para acessar este recurso.", "domainPickerBaseDomainLabel": "Domínio Base", "domainPickerSearchDomains": "Buscar domínios...", "domainPickerNoDomainsFound": "Nenhum domínio encontrado", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "Este endereço faz parte da sub-rede de utilitários da organização. É usado para resolver registros de alias usando resolução de DNS interno.", "resourcesTableClients": "Clientes", "resourcesTableAndOnlyAccessibleInternally": "e são acessíveis apenas internamente quando conectados com um cliente.", - "resourcesTableNoTargets": "Nenhum alvo", "resourcesTableHealthy": "Saudável", "resourcesTableDegraded": "Degradado", - "resourcesTableOffline": "Desconectado", + "resourcesTableUnhealthy": "Não Saudável", "resourcesTableUnknown": "Desconhecido", "resourcesTableNotMonitored": "Não monitorado", + "resourcesTableNoTargets": "Sem alvos", "editInternalResourceDialogEditClientResource": "Editar Recurso Privado", "editInternalResourceDialogUpdateResourceProperties": "Atualizar as configurações de recursos e controles de acesso para {resourceName}", "editInternalResourceDialogResourceProperties": "Propriedades do Recurso", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "Verificada", "domainPickerUnverified": "Não verificado", "domainPickerManual": "Manual", - "domainPickerInvalidSubdomainStructure": "Este subdomínio contém caracteres ou estrutura inválidos. Ele será eliminado automaticamente quando você salvar.", + "domainPickerInvalidSubdomainStructure": "Caracteres inválidos serão sanitizados ao serem salvos.", "domainPickerError": "ERRO", "domainPickerErrorLoadDomains": "Falha ao carregar domínios da organização", "domainPickerErrorCheckAvailability": "Não foi possível verificar a disponibilidade do domínio", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "Adicionar Clientes", "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.", + "internalResourceFormMultiSiteRoutingHelp": "Selecionar múltiplos sites permite roteamento resiliente e failover para alta disponibilidade.", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "Saiba mais", "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.", @@ -2908,6 +2932,7 @@ "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.", + "privateMaintenanceScreenSteps": "Depois de conectado, se você ainda estiver vendo esta mensagem, o cache DNS do seu navegador pode ainda apontar para o antigo endereço. Para corrigir isso: feche completamente e reabra esta aba, ou o seu navegador, e então navegue de volta para esta página.", "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", @@ -3142,5 +3167,39 @@ "idpDeleteAllOrgsMenu": "Excluir", "publicIpEndpoint": "Endpoint", "lastTriggeredAt": "Último Gatilho", - "reject": "Rejeitar" + "reject": "Rejeitar", + "uptimeDaysAgo": "há {count} dias", + "uptimeToday": "Hoje", + "uptimeNoDataAvailable": "Sem dados disponíveis", + "uptimeSuffix": "tempo de atividade", + "uptimeDowntimeSuffix": "tempo de inatividade", + "uptimeTooltipUptimeLabel": "Tempo de Atividade", + "uptimeTooltipDowntimeLabel": "Tempo de Inatividade", + "uptimeOngoing": "em andamento", + "uptimeNoMonitoringData": "Sem dados de monitoramento", + "uptimeNoData": "Sem dados", + "uptimeMiniBarDown": "Inativo", + "uptimeSectionTitle": "Tempo de Atividade", + "uptimeSectionDescription": "Disponibilidade nos últimos {days} dias", + "uptimeAddAlert": "Adicionar Alerta", + "uptimeViewAlerts": "Visualizar Alertas", + "uptimeCreateEmailAlert": "Criar Alerta por Email", + "uptimeAlertDescriptionSite": "Seja notificado por email quando este site sair do ar ou voltar online.", + "uptimeAlertDescriptionResource": "Seja notificado por email quando este recurso sair do ar ou voltar online.", + "uptimeAlertNamePlaceholder": "Nome do alerta", + "uptimeAdditionalEmails": "Emails Adicionais", + "uptimeCreateAlert": "Criar Alerta", + "uptimeAlertNoRecipients": "Sem destinatários", + "uptimeAlertNoRecipientsDescription": "Por favor, adicione pelo menos um usuário, função ou email para notificar.", + "uptimeAlertCreated": "Alerta criado", + "uptimeAlertCreatedDescription": "Você será notificado quando isso mudar de status.", + "uptimeAlertCreateFailed": "Falha ao criar alerta", + "webhookUrlLabel": "URL", + "webhookHeaderKeyPlaceholder": "Chave", + "webhookHeaderValuePlaceholder": "Valor", + "alertLabel": "Alerta", + "domainPickerWildcardSubdomainNotAllowed": "Subdomínios curinga não são permitidos.", + "domainPickerWildcardCertWarning": "Recursos curinga podem exigir configurações adicionais para funcionarem corretamente.", + "domainPickerWildcardCertWarningLink": "Saiba mais", + "health": "Saúde" } diff --git a/messages/ru-RU.json b/messages/ru-RU.json index d5496e660..4899a3f97 100644 --- a/messages/ru-RU.json +++ b/messages/ru-RU.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "Я скопировал(а) конфигурацию", "searchSitesProgress": "Поиск сайтов...", "siteAdd": "Добавить сайт", + "sitesTableViewPublicResources": "Просмотр публичных ресурсов", + "sitesTableViewPrivateResources": "Просмотр частных ресурсов", "siteInstallNewt": "Установить Newt", "siteInstallNewtDescription": "Запустите Newt в вашей системе", "WgConfiguration": "Конфигурация WireGuard", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "Сайт был успешно обновлён.", "siteGeneralDescription": "Настройте общие параметры для этого сайта", "siteSettingDescription": "Настройка параметров на сайте", + "siteResourcesTab": "Ресурсы", + "siteResourcesNoneOnSite": "На этом сайте пока нет публичных или частных ресурсов.", + "siteResourcesSectionPublic": "Публичные ресурсы", + "siteResourcesSectionPrivate": "Частные ресурсы", + "siteResourcesSectionPublicDescription": "Ресурсы, доступные извне через домены или порты.", + "siteResourcesSectionPrivateDescription": "Ресурсы доступны на вашем частном сетевом ресурсе через сайт.", + "siteResourcesViewAllPublic": "Просмотреть все ресурсы", + "siteResourcesViewAllPrivate": "Просмотреть все ресурсы", + "siteResourcesDialogDescription": "Обзор публичных и частных ресурсов, связанных с этим сайтом.", + "siteResourcesShowMore": "Показать еще", + "siteResourcesPermissionDenied": "У вас нет разрешения на просмотр этих ресурсов.", + "siteResourcesEmptyPublic": "Ни один публичный ресурс еще не нацелен на этот сайт.", + "siteResourcesEmptyPrivate": "С этим сайтом еще не связано ни одного частного ресурса.", + "siteResourcesHowToAccess": "Как получить доступ", + "siteResourcesTargetsOnSite": "Цели на этом сайте", "siteSetting": "Настройки {siteName}", "siteNewtTunnel": "Новый сайт (рекомендуется)", "siteNewtTunnelDescription": "Самый простой способ создать точку входа в любую сеть. Дополнительная настройка не требуется.", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "Статус проверки здоровья изменяется", "alertingTriggerResourceHealthy": "Ресурс в нормальном состоянии", "alertingTriggerResourceUnhealthy": "Ресурс в ненормальном состоянии", + "alertingTriggerResourceDegraded": "Ресурс ухудшен", "alertingSearchHealthChecks": "Поиск проверок здоровья…", "alertingHealthChecksEmpty": "Нет доступных проверок здоровья.", "alertingTriggerResourceToggle": "Статус ресурса изменяется", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "Создайте первоначальную учётную запись администратора сервера. Может существовать только один администратор сервера. Вы всегда можете изменить эти учётные данные позже.", "createAdminAccount": "Создать учётную запись администратора", "setupErrorCreateAdmin": "Произошла ошибка при создании учётной записи администратора сервера.", - "certificateStatus": "Статус сертификата", + "certificateStatus": "Сертификат", + "certificateStatusAutoRefreshHint": "Статус обновляется автоматически.", "loading": "Загрузка", "loadingAnalytics": "Загрузка аналитики", "restart": "Перезагрузка", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "Настроить проверку здоровья", "configureHealthCheckDescription": "Настройте мониторинг состояния для {target}", "enableHealthChecks": "Включить проверки здоровья", + "healthCheckDisabledStateDescription": "Когда отключен, сайт не будет выполнять проверки состояния и состояние будет считаться неизвестным.", "enableHealthChecksDescription": "Мониторинг здоровья этой цели. При необходимости можно контролировать другую конечную точку.", "healthScheme": "Метод", "healthSelectScheme": "Выберите метод", @@ -1947,6 +1967,8 @@ "httpMethod": "HTTP метод", "selectHttpMethod": "Выберите HTTP метод", "domainPickerSubdomainLabel": "Поддомен", + "domainPickerWildcard": "Подстановочный знак", + "domainPickerWildcardPaidOnly": "Wildcard поддомены являются платной функцией. Пожалуйста, обновите подписку, чтобы воспользоваться этой функцией.", "domainPickerBaseDomainLabel": "Основной домен", "domainPickerSearchDomains": "Поиск доменов...", "domainPickerNoDomainsFound": "Доменов не найдено", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "Этот адрес является частью вспомогательной подсети организации. Он используется для разрешения псевдонимов с использованием внутреннего разрешения DNS.", "resourcesTableClients": "Клиенты", "resourcesTableAndOnlyAccessibleInternally": "и доступны только внутренне при подключении с клиентом.", - "resourcesTableNoTargets": "Нет ярлыков", "resourcesTableHealthy": "Здоровые", "resourcesTableDegraded": "Ухудшение", - "resourcesTableOffline": "Оффлайн", + "resourcesTableUnhealthy": "Проблемные", "resourcesTableUnknown": "Неизвестен", "resourcesTableNotMonitored": "Не отслеживается", + "resourcesTableNoTargets": "Нет целей", "editInternalResourceDialogEditClientResource": "Изменить приватный ресурс", "editInternalResourceDialogUpdateResourceProperties": "Обновить настройки ресурса и элементы управления доступом для {resourceName}", "editInternalResourceDialogResourceProperties": "Свойства ресурса", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "Подтверждено", "domainPickerUnverified": "Не подтверждено", "domainPickerManual": "Ручной", - "domainPickerInvalidSubdomainStructure": "Этот поддомен содержит недопустимые символы или структуру. Он будет очищен автоматически при сохранении.", + "domainPickerInvalidSubdomainStructure": "Недопустимые символы будут очищены при сохранении.", "domainPickerError": "Ошибка", "domainPickerErrorLoadDomains": "Не удалось загрузить домены организации", "domainPickerErrorCheckAvailability": "Не удалось проверить доступность домена", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "Добавить клиентов", "editInternalResourceDialogDestinationLabel": "Пункт назначения", "editInternalResourceDialogDestinationDescription": "Укажите адрес назначения для внутреннего ресурса. Это может быть имя хоста, IP-адрес или диапазон CIDR в зависимости от выбранного режима. При необходимости установите внутренний DNS-алиас для облегчения идентификации.", + "internalResourceFormMultiSiteRoutingHelp": "Выбор нескольких сайтов позволяет обеспечить отказоустойчивую маршрутизацию и фейловер для высокой доступности.", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "Узнать больше", "editInternalResourceDialogPortRestrictionsDescription": "Ограничьте доступ к определенным TCP/UDP-портам или разрешите/заблокируйте все порты.", "createInternalResourceDialogHttpConfiguration": "Конфигурация HTTP", "createInternalResourceDialogHttpConfigurationDescription": "Выберите домен, который клиенты будут использовать для доступа к этому ресурсу через HTTP или HTTPS.", @@ -2908,6 +2932,7 @@ "maintenancePageTimeTitle": "Предполагаемое время завершения (необязательно)", "privateMaintenanceScreenTitle": "Экраны частной заглушки", "privateMaintenanceScreenMessage": "Этот домен используется на частном ресурсе. Пожалуйста, подключитесь с помощью клиента Pangolin для доступа к этому ресурсу.", + "privateMaintenanceScreenSteps": "После подключения, если это сообщение по-прежнему отображается, кэш DNS вашего браузера может указывать на старый адрес. Чтобы исправить эту неисправность: полностью закройте и снова откройте эту вкладку или браузер, затем вернитесь на эту страницу.", "maintenanceTime": "например, 2 часа, 1 ноября в 5:00 вечера", "maintenanceEstimatedTimeDescription": "Когда вы ожидаете завершения обслуживания", "editDomain": "Редактировать домен", @@ -3142,5 +3167,39 @@ "idpDeleteAllOrgsMenu": "Удалить", "publicIpEndpoint": "Конечная точка", "lastTriggeredAt": "Последний триггер", - "reject": "Отклонить" + "reject": "Отклонить", + "uptimeDaysAgo": "{count} дней назад", + "uptimeToday": "Сегодня", + "uptimeNoDataAvailable": "Нет доступных данных", + "uptimeSuffix": "время работы", + "uptimeDowntimeSuffix": "время простоя", + "uptimeTooltipUptimeLabel": "Время работы", + "uptimeTooltipDowntimeLabel": "Время простоя", + "uptimeOngoing": "в процессе", + "uptimeNoMonitoringData": "Отсутствуют данные мониторинга", + "uptimeNoData": "Нет данных", + "uptimeMiniBarDown": "Не работает", + "uptimeSectionTitle": "Время работы", + "uptimeSectionDescription": "Доступность за последние {days} дней", + "uptimeAddAlert": "Добавить предупреждение", + "uptimeViewAlerts": "Просмотр предупреждений", + "uptimeCreateEmailAlert": "Создать оповещение по электронной почте", + "uptimeAlertDescriptionSite": "Получайте уведомления по электронной почте, когда этот сайт выходит из сети или снова подключается.", + "uptimeAlertDescriptionResource": "Получайте уведомления по электронной почте, когда этот ресурс выходит из сети или снова подключается.", + "uptimeAlertNamePlaceholder": "Название предупреждения", + "uptimeAdditionalEmails": "Дополнительные адреса электронной почты", + "uptimeCreateAlert": "Создать предупреждение", + "uptimeAlertNoRecipients": "Нет получателей", + "uptimeAlertNoRecipientsDescription": "Пожалуйста, добавьте хотя бы одного пользователя, роль или email для уведомления.", + "uptimeAlertCreated": "Предупреждение создано", + "uptimeAlertCreatedDescription": "Вы будете уведомлены, когда статус изменится.", + "uptimeAlertCreateFailed": "Не удалось создать предупреждение", + "webhookUrlLabel": "URL", + "webhookHeaderKeyPlaceholder": "Ключ", + "webhookHeaderValuePlaceholder": "Значение", + "alertLabel": "Предупреждение", + "domainPickerWildcardSubdomainNotAllowed": "Wildcard поддомены не допускаются.", + "domainPickerWildcardCertWarning": "Wildcard ресурсы могут потребовать дополнительной настройки для правильной работы.", + "domainPickerWildcardCertWarningLink": "Узнать больше", + "health": "Состояние" } diff --git a/messages/tr-TR.json b/messages/tr-TR.json index b7b3c877c..4d36aebba 100644 --- a/messages/tr-TR.json +++ b/messages/tr-TR.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "Yapılandırmayı kopyaladım", "searchSitesProgress": "Siteleri ara...", "siteAdd": "Site Ekle", + "sitesTableViewPublicResources": "Genel Kaynakları Görüntüle", + "sitesTableViewPrivateResources": "Özel Kaynakları Görüntüle", "siteInstallNewt": "Newt Yükle", "siteInstallNewtDescription": "Newt'i sisteminizde çalıştırma", "WgConfiguration": "WireGuard Yapılandırması", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "Site güncellendi.", "siteGeneralDescription": "Bu site için genel ayarları yapılandırın", "siteSettingDescription": "Sitenizdeki ayarları yapılandırın", + "siteResourcesTab": "Kaynaklar", + "siteResourcesNoneOnSite": "Bu sitede henüz genel veya özel kaynak yok.", + "siteResourcesSectionPublic": "Genel Kaynaklar", + "siteResourcesSectionPrivate": "Özel Kaynaklar", + "siteResourcesSectionPublicDescription": "Alanlar veya portlar üzerinden dışarıdan açığa çıkan kaynaklar.", + "siteResourcesSectionPrivateDescription": "Site aracılığıyla özel ağınızda mevcut olan kaynaklar.", + "siteResourcesViewAllPublic": "Tüm kaynakları görüntüle", + "siteResourcesViewAllPrivate": "Tüm kaynakları görüntüle", + "siteResourcesDialogDescription": "Bu siteyle ilişkili genel ve özel kaynakların genel bakışı.", + "siteResourcesShowMore": "Daha fazla göster", + "siteResourcesPermissionDenied": "Bu kaynakları listeleme izniniz yok.", + "siteResourcesEmptyPublic": "Bu siteyi hedefleyen herhangi bir genel kaynak yok.", + "siteResourcesEmptyPrivate": "Bu siteyle ilişkilendirilmiş özel kaynak yok.", + "siteResourcesHowToAccess": "Nasıl erişilir", + "siteResourcesTargetsOnSite": "Bu sitedeki hedefler", "siteSetting": "{siteName} Ayarları", "siteNewtTunnel": "Newt Site (Önerilen)", "siteNewtTunnelDescription": "Ağınıza giriş noktası oluşturmanın en kolay yolu. Ekstra kurulum gerekmez.", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "Sağlık kontrolü durumu değişiyor", "alertingTriggerResourceHealthy": "Kaynak sağlıklı", "alertingTriggerResourceUnhealthy": "Kaynak sağlıksız", + "alertingTriggerResourceDegraded": "Kaynak bozuk", "alertingSearchHealthChecks": "Sağlık kontrollerini ara…", "alertingHealthChecksEmpty": "Mevcut sağlık kontrolü yok.", "alertingTriggerResourceToggle": "Kaynak durumu değişiyor", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "İlk sunucu yönetici hesabını oluşturun. Yalnızca bir sunucu yöneticisi olabilir. Bu kimlik bilgilerini daha sonra her zaman değiştirebilirsiniz.", "createAdminAccount": "Yönetici Hesabı Oluştur", "setupErrorCreateAdmin": "Sunucu yönetici hesabı oluşturulurken bir hata oluştu.", - "certificateStatus": "Sertifika Durumu", + "certificateStatus": "Sertifika", + "certificateStatusAutoRefreshHint": "Durum otomatik olarak yenilenir.", "loading": "Yükleniyor", "loadingAnalytics": "Analiz Yükleniyor", "restart": "Yeniden Başlat", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "Sağlık Kontrolünü Yapılandır", "configureHealthCheckDescription": "{hedef} için sağlık izleme kurun", "enableHealthChecks": "Sağlık Kontrollerini Etkinleştir", + "healthCheckDisabledStateDescription": "Devre dışı bırakıldığında, site sağlık kontrolleri yapmaz ve durum bilinmeyen olarak kabul edilecektir.", "enableHealthChecksDescription": "Bu hedefin sağlığını izleyin. Gerekirse hedef dışındaki bir son noktayı izleyebilirsiniz.", "healthScheme": "Yöntem", "healthSelectScheme": "Yöntem Seç", @@ -1947,6 +1967,8 @@ "httpMethod": "HTTP Yöntemi", "selectHttpMethod": "HTTP yöntemini seçin", "domainPickerSubdomainLabel": "Alt Alan Adı", + "domainPickerWildcard": "Genel karakter", + "domainPickerWildcardPaidOnly": "Genel alt alanlar ücretli bir özelliktir. Bu özelliğe erişmek için lütfen yükseltin.", "domainPickerBaseDomainLabel": "Temel Alan Adı", "domainPickerSearchDomains": "Alan adlarını ara...", "domainPickerNoDomainsFound": "Hiçbir alan adı bulunamadı", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "Bu adres, kuruluşun yardımcı ağ alt bantının bir parçasıdır. Alias kayıtlarını çözümlemek için dahili DNS çözümlemesi kullanılır.", "resourcesTableClients": "İstemciler", "resourcesTableAndOnlyAccessibleInternally": "veyalnızca bir istemci ile bağlandığında dahili olarak erişilebilir.", - "resourcesTableNoTargets": "Hedef yok", "resourcesTableHealthy": "Sağlıklı", "resourcesTableDegraded": "Düşük Performanslı", - "resourcesTableOffline": "Çevrimdışı", + "resourcesTableUnhealthy": "Sağlıksız", "resourcesTableUnknown": "Bilinmiyor", "resourcesTableNotMonitored": "İzlenmiyor", + "resourcesTableNoTargets": "Hedef yok", "editInternalResourceDialogEditClientResource": "Özel Kaynak Düzenleyin", "editInternalResourceDialogUpdateResourceProperties": "{resourceName} için kaynak ayarlarını ve erişim kontrollerini güncelleyin", "editInternalResourceDialogResourceProperties": "Kaynak Özellikleri", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "Doğrulandı", "domainPickerUnverified": "Doğrulanmadı", "domainPickerManual": "Manuel", - "domainPickerInvalidSubdomainStructure": "Bu alt alan adı geçersiz karakterler veya yapı içeriyor. Kaydettiğinizde otomatik olarak temizlenecektir.", + "domainPickerInvalidSubdomainStructure": "Geçersiz karakterler kaydedildiğinde temizlenecektir.", "domainPickerError": "Hata", "domainPickerErrorLoadDomains": "Organizasyon alan adları yüklenemedi", "domainPickerErrorCheckAvailability": "Alan adı kullanılabilirliği kontrol edilemedi", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "Müşteriler Ekle", "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.", + "internalResourceFormMultiSiteRoutingHelp": "Birden fazla site seçmek, yüksek kullanılabilirlik için dirençli yönlendirme ve yedeklik sağlar.", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "Daha fazla bilgi", "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.", @@ -2908,6 +2932,7 @@ "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.", + "privateMaintenanceScreenSteps": "Bağlanıldıktan sonra, hâlâ bu mesajı görüyorsanız tarayıcınızın DNS önbelleği eski adrese işaret ediyor olabilir. Bunu düzeltmek için: bu sekmeyi veya tarayıcınızı tamamen kapatıp tekrar açın, ardından bu sayfaya geri dönü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", @@ -3142,5 +3167,39 @@ "idpDeleteAllOrgsMenu": "Sil", "publicIpEndpoint": "Uç Nokta", "lastTriggeredAt": "Son Tetikleyici", - "reject": "Reddet" + "reject": "Reddet", + "uptimeDaysAgo": "{count} gün önce", + "uptimeToday": "Bugün", + "uptimeNoDataAvailable": "Veri yok", + "uptimeSuffix": "çalışma süresi", + "uptimeDowntimeSuffix": "çalışma dışı", + "uptimeTooltipUptimeLabel": "Çalışma süresi", + "uptimeTooltipDowntimeLabel": "Çalışma dışı", + "uptimeOngoing": "devam eden", + "uptimeNoMonitoringData": "İzleme verisi yok", + "uptimeNoData": "Veri yok", + "uptimeMiniBarDown": "Kapalı", + "uptimeSectionTitle": "Çalışma Süresi", + "uptimeSectionDescription": "Son {days} gün boyunca kullanılabilirlik", + "uptimeAddAlert": "Uyarı Ekle", + "uptimeViewAlerts": "Uyarıları Görüntüle", + "uptimeCreateEmailAlert": "E-posta Uyarısı Oluştur", + "uptimeAlertDescriptionSite": "Bu site çevrimdışıyken veya yeniden çevrimiçi olduğunda e-posta ile bildirim alın.", + "uptimeAlertDescriptionResource": "Bu kaynak çevrimdışıyken veya yeniden çevrimiçi olduğunda e-posta ile bildirim alın.", + "uptimeAlertNamePlaceholder": "Uyarı adı", + "uptimeAdditionalEmails": "Ek E-postalar", + "uptimeCreateAlert": "Uyarı Oluştur", + "uptimeAlertNoRecipients": "Alıcı yok", + "uptimeAlertNoRecipientsDescription": "Lütfen en az bir kullanıcı, rol veya e-posta ekleyin.", + "uptimeAlertCreated": "Uyarı oluşturuldu", + "uptimeAlertCreatedDescription": "Durum değiştiğinde haberdar edileceksiniz.", + "uptimeAlertCreateFailed": "Uyarı oluşturulamadı", + "webhookUrlLabel": "URL", + "webhookHeaderKeyPlaceholder": "Anahtar", + "webhookHeaderValuePlaceholder": "Değer", + "alertLabel": "Uyarı", + "domainPickerWildcardSubdomainNotAllowed": "Genel alt alanlara izin verilmiyor.", + "domainPickerWildcardCertWarning": "Genel kaynaklar düzgün çalışmak için ek yapılandırma gerektirebilir.", + "domainPickerWildcardCertWarningLink": "Daha fazla bilgi", + "health": "Sağlık" } diff --git a/messages/zh-CN.json b/messages/zh-CN.json index 1a79d3c35..aa7ad9ed0 100644 --- a/messages/zh-CN.json +++ b/messages/zh-CN.json @@ -93,6 +93,8 @@ "siteConfirmCopy": "我已经复制了配置信息", "searchSitesProgress": "搜索站点...", "siteAdd": "添加站点", + "sitesTableViewPublicResources": "查看公共资源", + "sitesTableViewPrivateResources": "查看私有资源", "siteInstallNewt": "安装 Newt", "siteInstallNewtDescription": "在您的系统中运行 Newt", "WgConfiguration": "WireGuard 配置", @@ -110,6 +112,21 @@ "siteUpdatedDescription": "网站已更新。", "siteGeneralDescription": "配置此站点的常规设置", "siteSettingDescription": "配置站点设置", + "siteResourcesTab": "资源", + "siteResourcesNoneOnSite": "此站点尚无公开或私人资源。", + "siteResourcesSectionPublic": "公共资源", + "siteResourcesSectionPrivate": "私有资源", + "siteResourcesSectionPublicDescription": "通过域名或端口公开的资源。", + "siteResourcesSectionPrivateDescription": "通过站点可在您的私有网络上访问的资源。", + "siteResourcesViewAllPublic": "查看所有资源", + "siteResourcesViewAllPrivate": "查看所有资源", + "siteResourcesDialogDescription": "此站点的公开和私有资源概览。", + "siteResourcesShowMore": "显示更多", + "siteResourcesPermissionDenied": "您无权列出这些资源。", + "siteResourcesEmptyPublic": "尚无针对该站点的公共资源。", + "siteResourcesEmptyPrivate": "尚无与此站点关联的私有资源。", + "siteResourcesHowToAccess": "如何访问", + "siteResourcesTargetsOnSite": "此站点上的目标", "siteSetting": "{siteName} 设置", "siteNewtTunnel": "新站点 (推荐)", "siteNewtTunnelDescription": "最简单的方式来创建任何网络的入口。没有额外的设置。", @@ -1415,6 +1432,7 @@ "alertingTriggerHcToggle": "健康检查状态变更", "alertingTriggerResourceHealthy": "资源正常", "alertingTriggerResourceUnhealthy": "资源不正常", + "alertingTriggerResourceDegraded": "资源降级", "alertingSearchHealthChecks": "搜索健康检查…", "alertingHealthChecksEmpty": "无可用健康检查。", "alertingTriggerResourceToggle": "资源状态变更", @@ -1578,7 +1596,8 @@ "initialSetupDescription": "创建初始服务器管理员帐户。 只能存在一个服务器管理员。 您可以随时更改这些凭据。", "createAdminAccount": "创建管理员帐户", "setupErrorCreateAdmin": "创建服务器管理员账户时发生错误。", - "certificateStatus": "证书状态", + "certificateStatus": "证书", + "certificateStatusAutoRefreshHint": "状态自动刷新。", "loading": "加载中", "loadingAnalytics": "加载分析", "restart": "重启", @@ -1886,6 +1905,7 @@ "configureHealthCheck": "配置健康检查", "configureHealthCheckDescription": "为 {target} 设置健康监控", "enableHealthChecks": "启用健康检查", + "healthCheckDisabledStateDescription": "禁用后,站点不会进行健康检查,状态将被视为未知。", "enableHealthChecksDescription": "监视此目标的健康状况。如果需要,您可以监视一个不同的终点。", "healthScheme": "方法", "healthSelectScheme": "选择方法", @@ -1947,6 +1967,8 @@ "httpMethod": "HTTP 方法", "selectHttpMethod": "选择 HTTP 方法", "domainPickerSubdomainLabel": "子域名", + "domainPickerWildcard": "通配符", + "domainPickerWildcardPaidOnly": "通配符子域是付费功能。请升级以使用此功能。", "domainPickerBaseDomainLabel": "根域名", "domainPickerSearchDomains": "搜索域名...", "domainPickerNoDomainsFound": "未找到域名", @@ -1972,12 +1994,12 @@ "resourcesTableAliasAddressInfo": "此地址是组织实用子网的一部分。它用来使用内部DNS解析来解析别名记录。", "resourcesTableClients": "客户端", "resourcesTableAndOnlyAccessibleInternally": "且仅在与客户端连接时可内部访问。", - "resourcesTableNoTargets": "没有目标", "resourcesTableHealthy": "健康的", "resourcesTableDegraded": "降级", - "resourcesTableOffline": "离线的", + "resourcesTableUnhealthy": "不健康", "resourcesTableUnknown": "未知的", "resourcesTableNotMonitored": "未监视的", + "resourcesTableNoTargets": "无目标", "editInternalResourceDialogEditClientResource": "编辑私有资源", "editInternalResourceDialogUpdateResourceProperties": "更新{resourceName}的资源配置和访问控制。", "editInternalResourceDialogResourceProperties": "资源属性", @@ -2318,7 +2340,7 @@ "domainPickerVerified": "已验证", "domainPickerUnverified": "未验证", "domainPickerManual": "手动", - "domainPickerInvalidSubdomainStructure": "此子域包含无效的字符或结构。当您保存时,它将被自动清除。", + "domainPickerInvalidSubdomainStructure": "保存时将清除无效字符。", "domainPickerError": "错误", "domainPickerErrorLoadDomains": "加载组织域名失败", "domainPickerErrorCheckAvailability": "检查域可用性失败", @@ -2863,6 +2885,8 @@ "editInternalResourceDialogAddClients": "添加客户端", "editInternalResourceDialogDestinationLabel": "目标", "editInternalResourceDialogDestinationDescription": "指定内部资源的目标地址。根据选择的模式,这可以是主机名、IP地址或CIDR范围。可选的,设置一个内部DNS别名以便于识别。", + "internalResourceFormMultiSiteRoutingHelp": "选择多个站点可以实现高可用性的弹性路由和故障转移。", + "internalResourceFormMultiSiteRoutingHelpLearnMore": "了解更多", "editInternalResourceDialogPortRestrictionsDescription": "限制访问特定的TCP/UDP端口或允许/阻止所有端口。", "createInternalResourceDialogHttpConfiguration": "HTTP 配置", "createInternalResourceDialogHttpConfigurationDescription": "选择客户将使用的域名通过 HTTP 或 HTTPS 访问此资源。", @@ -2908,6 +2932,7 @@ "maintenancePageTimeTitle": "预计完成时间(可选)", "privateMaintenanceScreenTitle": "私有占位符界面", "privateMaintenanceScreenMessage": "此域名正在私有资源上使用。请连接 Pangolin 客户端以访问此资源。", + "privateMaintenanceScreenSteps": "连接后,如果您仍然看到此消息,说明您的浏览器的DNS缓存可能仍指向旧地址。解决方法:完全关闭并重新打开此标签页或浏览器,然后返回此页面。", "maintenanceTime": "例如,2小时,11月1日下午5:00", "maintenanceEstimatedTimeDescription": "您期望维护完成的时间", "editDomain": "编辑域名", @@ -3142,5 +3167,39 @@ "idpDeleteAllOrgsMenu": "删除", "publicIpEndpoint": "终端", "lastTriggeredAt": "最后触发", - "reject": "拒绝" + "reject": "拒绝", + "uptimeDaysAgo": "{count} 天前", + "uptimeToday": "今天", + "uptimeNoDataAvailable": "暂无数据", + "uptimeSuffix": "正常运行时间", + "uptimeDowntimeSuffix": "停机时间", + "uptimeTooltipUptimeLabel": "正常运行", + "uptimeTooltipDowntimeLabel": "停机", + "uptimeOngoing": "正在进行", + "uptimeNoMonitoringData": "无监控数据", + "uptimeNoData": "无数据", + "uptimeMiniBarDown": "停机", + "uptimeSectionTitle": "正常运行时间", + "uptimeSectionDescription": "过去 {days} 天的可用性", + "uptimeAddAlert": "添加警报", + "uptimeViewAlerts": "查看警报", + "uptimeCreateEmailAlert": "创建电子邮件警报", + "uptimeAlertDescriptionSite": "当此站点下线或恢复上线时,将通过电子邮件通知您。", + "uptimeAlertDescriptionResource": "当此资源下线或恢复上线时,将通过电子邮件通知您。", + "uptimeAlertNamePlaceholder": "警报名称", + "uptimeAdditionalEmails": "附加电子邮件", + "uptimeCreateAlert": "创建警报", + "uptimeAlertNoRecipients": "无收件人", + "uptimeAlertNoRecipientsDescription": "请至少添加一个用户、角色或电子邮件进行通知。", + "uptimeAlertCreated": "警报已创建", + "uptimeAlertCreatedDescription": "状态变化时将通知您。", + "uptimeAlertCreateFailed": "创建警报失败", + "webhookUrlLabel": "URL", + "webhookHeaderKeyPlaceholder": "关键字", + "webhookHeaderValuePlaceholder": "值", + "alertLabel": "警报", + "domainPickerWildcardSubdomainNotAllowed": "不允许使用通配符子域。", + "domainPickerWildcardCertWarning": "通配符资源可能需要额外配置才能正常工作。", + "domainPickerWildcardCertWarningLink": "了解更多", + "health": "健康" } diff --git a/server/auth/actions.ts b/server/auth/actions.ts index 5ae98f965..9ba1b5bce 100644 --- a/server/auth/actions.ts +++ b/server/auth/actions.ts @@ -122,8 +122,6 @@ export enum ActionsEnum { createOrgDomain = "createOrgDomain", deleteOrgDomain = "deleteOrgDomain", restartOrgDomain = "restartOrgDomain", - sendUsageNotification = "sendUsageNotification", - sendTrialNotification = "sendTrialNotification", createRemoteExitNode = "createRemoteExitNode", updateRemoteExitNode = "updateRemoteExitNode", getRemoteExitNode = "getRemoteExitNode", @@ -154,10 +152,7 @@ export enum ActionsEnum { createHealthCheck = "createHealthCheck", updateHealthCheck = "updateHealthCheck", deleteHealthCheck = "deleteHealthCheck", - listHealthChecks = "listHealthChecks", - triggerSiteAlert = "triggerSiteAlert", - triggerResourceAlert = "triggerResourceAlert", - triggerHealthCheckAlert = "triggerHealthCheckAlert" + listHealthChecks = "listHealthChecks" } export async function checkUserActionPermission( diff --git a/server/db/pg/schema/privateSchema.ts b/server/db/pg/schema/privateSchema.ts index d930b69d0..0f1914fad 100644 --- a/server/db/pg/schema/privateSchema.ts +++ b/server/db/pg/schema/privateSchema.ts @@ -484,6 +484,7 @@ export const alertRules = pgTable("alertRules", { | "health_check_toggle" | "resource_healthy" | "resource_unhealthy" + | "resource_degraded" | "resource_toggle" >() .notNull(), @@ -565,6 +566,17 @@ export const alertWebhookActions = pgTable("alertWebhookActions", { lastSentAt: bigint("lastSentAt", { mode: "number" }) // nullable }); +export const trialNotifications = pgTable("trialNotifications", { + notificationId: serial("notificationId").primaryKey(), + subscriptionId: varchar("subscriptionId", { length: 255 }) + .notNull() + .references(() => subscriptions.subscriptionId, { + onDelete: "cascade" + }), + notificationType: varchar("notificationType", { length: 50 }).notNull(), // trial_ending_5d, trial_ending_24h, trial_ended + sentAt: bigint("sentAt", { mode: "number" }).notNull() +}); + export type Approval = InferSelectModel; export type Limit = InferSelectModel; export type Account = InferSelectModel; @@ -603,3 +615,12 @@ export type EventStreamingCursor = InferSelectModel< typeof eventStreamingCursors >; export type AlertResources = InferSelectModel; +export type AlertHealthChecks = InferSelectModel; +export type AlertSites = InferSelectModel; +export type AlertRules = InferSelectModel; +export type AlertEmailActions = InferSelectModel; +export type AlertEmailRecipients = InferSelectModel< + typeof alertEmailRecipients +>; +export type AlertWebhookActions = InferSelectModel; +export type TrialNotification = InferSelectModel; diff --git a/server/db/pg/schema/schema.ts b/server/db/pg/schema/schema.ts index 30dfef353..7fbcef621 100644 --- a/server/db/pg/schema/schema.ts +++ b/server/db/pg/schema/schema.ts @@ -158,7 +158,8 @@ export const resources = pgTable("resources", { maintenanceMessage: text("maintenanceMessage"), maintenanceEstimatedTime: text("maintenanceEstimatedTime"), postAuthPath: text("postAuthPath"), - health: varchar("health") // "healthy", "unhealthy" + health: varchar("health").default("unknown"), // "healthy", "unhealthy", "unknown" + wildcard: boolean("wildcard").notNull().default(false) }); export const targets = pgTable("targets", { diff --git a/server/db/queries/verifySessionQueries.ts b/server/db/queries/verifySessionQueries.ts index 989e111a7..46b45b1a0 100644 --- a/server/db/queries/verifySessionQueries.ts +++ b/server/db/queries/verifySessionQueries.ts @@ -25,7 +25,7 @@ import { ResourceHeaderAuthExtendedCompatibility, resourceHeaderAuthExtendedCompatibility } from "@server/db"; -import { and, eq, inArray } from "drizzle-orm"; +import { and, eq, inArray, or, sql } from "drizzle-orm"; export type ResourceWithAuth = { resource: Resource | null; @@ -47,7 +47,17 @@ export type UserSessionWithUser = { export async function getResourceByDomain( domain: string ): Promise { - const [result] = await db + // Build wildcard domain variants to match against. + // For a domain like "me.example.test.com", we want to match: + // - "*.example.test.com" (subdomain wildcard) + // - "*.test.com" (parent wildcard, i.e. just "*" subdomain on parent) + const parts = domain.split("."); + const wildcardCandidates: string[] = []; + for (let i = 1; i < parts.length; i++) { + wildcardCandidates.push(`*.${parts.slice(i).join(".")}`); + } + + const potentialResults = await db .select() .from(resources) .leftJoin( @@ -70,8 +80,29 @@ export async function getResourceByDomain( ) ) .innerJoin(orgs, eq(orgs.orgId, resources.orgId)) - .where(eq(resources.fullDomain, domain)) - .limit(1); + .where( + or( + // Exact match + eq(resources.fullDomain, domain), + // Wildcard match: resource fullDomain is one of the wildcard candidates + wildcardCandidates.length > 0 + ? and( + eq(resources.wildcard, true), + inArray(resources.fullDomain, wildcardCandidates) + ) + : sql`false` + ) + ); + + if (!potentialResults.length) { + return null; + } + + // Prefer exact match over wildcard match + const exactMatch = potentialResults.find( + (r) => r.resources?.fullDomain === domain + ); + const result = exactMatch ?? potentialResults[0]; if (!result) { return null; diff --git a/server/db/sqlite/schema/privateSchema.ts b/server/db/sqlite/schema/privateSchema.ts index 9a33e2049..05c917887 100644 --- a/server/db/sqlite/schema/privateSchema.ts +++ b/server/db/sqlite/schema/privateSchema.ts @@ -21,6 +21,9 @@ import { targetHealthCheck, users } from "./schema"; +import { serial, varchar } from "drizzle-orm/mysql-core"; +import { pgTable } from "drizzle-orm/pg-core"; +import { bigint } from "zod"; export const certificates = sqliteTable("certificates", { certId: integer("certId").primaryKey({ autoIncrement: true }), @@ -425,10 +428,18 @@ export const eventStreamingDestinations = sqliteTable( orgId: text("orgId") .notNull() .references(() => orgs.orgId, { onDelete: "cascade" }), - sendConnectionLogs: integer("sendConnectionLogs", { mode: "boolean" }).notNull().default(false), - sendRequestLogs: integer("sendRequestLogs", { mode: "boolean" }).notNull().default(false), - sendActionLogs: integer("sendActionLogs", { mode: "boolean" }).notNull().default(false), - sendAccessLogs: integer("sendAccessLogs", { mode: "boolean" }).notNull().default(false), + sendConnectionLogs: integer("sendConnectionLogs", { mode: "boolean" }) + .notNull() + .default(false), + sendRequestLogs: integer("sendRequestLogs", { mode: "boolean" }) + .notNull() + .default(false), + sendActionLogs: integer("sendActionLogs", { mode: "boolean" }) + .notNull() + .default(false), + sendAccessLogs: integer("sendAccessLogs", { mode: "boolean" }) + .notNull() + .default(false), type: text("type").notNull(), // e.g. "http", "kafka", etc. config: text("config").notNull(), // JSON string with the configuration for the destination enabled: integer("enabled", { mode: "boolean" }) @@ -476,14 +487,19 @@ export const alertRules = sqliteTable("alertRules", { | "health_check_toggle" | "resource_healthy" | "resource_unhealthy" + | "resource_degraded" | "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), + 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() @@ -531,23 +547,44 @@ 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" }), + .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 }), + 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) + config: text("config"), // encrypted JSON with auth config (authType, credentials) enabled: integer("enabled", { mode: "boolean" }).notNull().default(true), lastSentAt: integer("lastSentAt") }); +export const trialNotifications = sqliteTable("trialNotifications", { + notificationId: integer("notificationId").primaryKey({ + autoIncrement: true + }), + subscriptionId: text("subscriptionId") + .notNull() + .references(() => subscriptions.subscriptionId, { + onDelete: "cascade" + }), + notificationType: text("notificationType").notNull(), // trial_ending_5d, trial_ending_24h, trial_ended + sentAt: integer("sentAt").notNull() +}); + export type Approval = InferSelectModel; export type Limit = InferSelectModel; export type Account = InferSelectModel; @@ -580,3 +617,10 @@ export type EventStreamingCursor = InferSelectModel< typeof eventStreamingCursors >; export type AlertResources = InferSelectModel; +export type AlertHealthChecks = InferSelectModel; +export type AlertSites = InferSelectModel; +export type AlertRule = InferSelectModel; +export type AlertEmailAction = InferSelectModel; +export type AlertEmailRecipient = InferSelectModel; +export type AlertWebhookAction = InferSelectModel; +export type TrialNotification = InferSelectModel; diff --git a/server/db/sqlite/schema/schema.ts b/server/db/sqlite/schema/schema.ts index 0f0844d2f..423190420 100644 --- a/server/db/sqlite/schema/schema.ts +++ b/server/db/sqlite/schema/schema.ts @@ -179,7 +179,8 @@ export const resources = sqliteTable("resources", { maintenanceMessage: text("maintenanceMessage"), maintenanceEstimatedTime: text("maintenanceEstimatedTime"), postAuthPath: text("postAuthPath"), - health: text("health") // "healthy", "unhealthy" + health: text("health").default("unknown"), // "healthy", "unhealthy", "unknown" + wildcard: integer("wildcard", { mode: "boolean" }).notNull().default(false) }); export const targets = sqliteTable("targets", { diff --git a/server/emails/templates/AlertNotification.tsx b/server/emails/templates/AlertNotification.tsx index 5542384a9..ce30753da 100644 --- a/server/emails/templates/AlertNotification.tsx +++ b/server/emails/templates/AlertNotification.tsx @@ -23,6 +23,7 @@ export type AlertEventType = | "health_check_toggle" | "resource_healthy" | "resource_unhealthy" + | "resource_degraded" | "resource_toggle"; export type AlertNotificationProps = { @@ -114,6 +115,15 @@ function getEventMeta(eventType: AlertEventType): { statusLabel: "Unhealthy", statusColor: "#dc2626" }; + case "resource_degraded": + return { + heading: "Resource Degraded", + previewText: "A resource in your organization is degraded.", + summary: + "A resource in your organization is currently degraded.", + statusLabel: "Degraded", + statusColor: "#dc2626" + }; case "resource_toggle": return { heading: "Resource Status Changed", @@ -135,7 +145,10 @@ function getEventMeta(eventType: AlertEventType): { } } -function resolveToggleStatus(status: unknown): { label: string; color: string } { +function resolveToggleStatus(status: unknown): { + label: string; + color: string; +} { switch (String(status).toLowerCase()) { case "online": return { label: "Online", color: "#16a34a" }; @@ -145,6 +158,8 @@ function resolveToggleStatus(status: unknown): { label: string; color: string } return { label: "Healthy", color: "#16a34a" }; case "unhealthy": return { label: "Unhealthy", color: "#dc2626" }; + case "degraded": + return { label: "Degraded", color: "#dc2626" }; default: return { label: String(status ?? "Unknown"), color: "#f59e0b" }; } diff --git a/server/lib/alerts/events/healthCheckEvents.ts b/server/lib/alerts/events/healthCheckEvents.ts index ba79feb4b..00afa22f0 100644 --- a/server/lib/alerts/events/healthCheckEvents.ts +++ b/server/lib/alerts/events/healthCheckEvents.ts @@ -6,6 +6,7 @@ export async function fireHealthCheckHealthyAlert( healthCheckName?: string, healthCheckTargetId?: number | null, extra?: Record, + send: boolean = true, trx?: unknown ): Promise { return; @@ -17,7 +18,20 @@ export async function fireHealthCheckUnhealthyAlert( healthCheckName?: string, healthCheckTargetId?: number | null, extra?: Record, + send: boolean = true, trx?: unknown ): Promise { return; -} \ No newline at end of file +} + +export async function fireHealthCheckUnknownAlert( + orgId: string, + healthCheckId: number, + healthCheckName?: string | null, + healthCheckTargetId?: number | null, + extra?: Record, + send: boolean = true, + trx?: unknown +): Promise { + return; +} diff --git a/server/lib/alerts/events/resourceEvents.ts b/server/lib/alerts/events/resourceEvents.ts index 09dd7d8cf..e7a374b44 100644 --- a/server/lib/alerts/events/resourceEvents.ts +++ b/server/lib/alerts/events/resourceEvents.ts @@ -3,6 +3,7 @@ export async function fireResourceHealthyAlert( resourceId: number, resourceName?: string | null, extra?: Record, + send: boolean = true, trx?: unknown ): Promise {} @@ -11,6 +12,7 @@ export async function fireResourceUnhealthyAlert( resourceId: number, resourceName?: string | null, extra?: Record, + send: boolean = true, trx?: unknown ): Promise {} @@ -19,5 +21,6 @@ export async function fireResourceToggleAlert( resourceId: number, resourceName?: string | null, extra?: Record, + send: boolean = true, trx?: unknown -): Promise {} \ No newline at end of file +): Promise {} diff --git a/server/lib/billing/tierMatrix.ts b/server/lib/billing/tierMatrix.ts index 5ae57c8a7..f44cb8bf6 100644 --- a/server/lib/billing/tierMatrix.ts +++ b/server/lib/billing/tierMatrix.ts @@ -23,7 +23,8 @@ export enum TierFeature { HTTPPrivateResources = "httpPrivateResources", // handle downgrade by disabling HTTP private resources DomainNamespaces = "domainNamespaces", // handle downgrade by removing custom domain namespaces StandaloneHealthChecks = "standaloneHealthChecks", - AlertingRules = "alertingRules" + AlertingRules = "alertingRules", + WildcardSubdomain = "wildcardSubdomain" } export const tierMatrix: Record = { @@ -63,6 +64,7 @@ export const tierMatrix: Record = { [TierFeature.SIEM]: ["enterprise"], [TierFeature.HTTPPrivateResources]: ["tier3", "enterprise"], [TierFeature.DomainNamespaces]: ["tier1", "tier2", "tier3", "enterprise"], - [TierFeature.StandaloneHealthChecks]: ["tier2", "tier3", "enterprise"], - [TierFeature.AlertingRules]: ["tier2", "tier3", "enterprise"] + [TierFeature.StandaloneHealthChecks]: ["tier3", "enterprise"], + [TierFeature.AlertingRules]: ["tier3", "enterprise"], + [TierFeature.WildcardSubdomain]: ["tier1", "tier2", "tier3", "enterprise"] }; diff --git a/server/lib/blueprints/applyBlueprint.ts b/server/lib/blueprints/applyBlueprint.ts index fd189e6ca..8ca66971a 100644 --- a/server/lib/blueprints/applyBlueprint.ts +++ b/server/lib/blueprints/applyBlueprint.ts @@ -293,7 +293,7 @@ export async function applyBlueprint({ orgId, name: name ?? - `${faker.word.adjective()} ${faker.word.adjective()} ${faker.word.noun()}`, + `${faker.word.adjective()}-${faker.word.adjective()}-${faker.word.noun()}`, contents: stringifyYaml(configData), createdAt: Math.floor(Date.now() / 1000), succeeded: blueprintSucceeded, diff --git a/server/lib/blueprints/clientResources.ts b/server/lib/blueprints/clientResources.ts index df1fd0cfb..1b2ec2ef7 100644 --- a/server/lib/blueprints/clientResources.ts +++ b/server/lib/blueprints/clientResources.ts @@ -125,12 +125,12 @@ export async function updateClientResources( const existingSiteIds = existingResource?.networkId ? await trx - .select({ siteId: sites.siteId }) + .select({ siteId: siteNetworks.siteId }) .from(siteNetworks) .where(eq(siteNetworks.networkId, existingResource.networkId)) : []; - let allSites: { siteId: number }[] = []; + const allSites: { siteId: number }[] = []; if (resourceData.site) { let siteSingle; const resourceSiteId = resourceData.site; @@ -215,9 +215,17 @@ export async function updateClientResources( 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"], + disableIcmp: + resourceData["disable-icmp"] || + (resourceData.mode == "http" ? true : false), // default to true for http resources, otherwise false + tcpPortRangeString: + resourceData.mode == "http" + ? "443,80" + : resourceData["tcp-ports"], + udpPortRangeString: + resourceData.mode == "http" + ? "" + : resourceData["udp-ports"], fullDomain: resourceData["full-domain"] || null, subdomain: domainInfo ? domainInfo.subdomain : null, domainId: domainInfo ? domainInfo.domainId : null @@ -397,9 +405,17 @@ export async function updateClientResources( // enabled: resourceData.enabled ?? true, alias: resourceData.alias || null, aliasAddress: aliasAddress, - disableIcmp: resourceData["disable-icmp"], - tcpPortRangeString: resourceData["tcp-ports"], - udpPortRangeString: resourceData["udp-ports"], + disableIcmp: + resourceData["disable-icmp"] || + (resourceData.mode == "http" ? true : false), // default to true for http resources, otherwise false + tcpPortRangeString: + resourceData.mode == "http" + ? "443,80" + : resourceData["tcp-ports"], + udpPortRangeString: + resourceData.mode == "http" + ? "" + : resourceData["udp-ports"], fullDomain: resourceData["full-domain"] || null, subdomain: domainInfo ? domainInfo.subdomain : null, domainId: domainInfo ? domainInfo.domainId : null diff --git a/server/lib/blueprints/proxyResources.ts b/server/lib/blueprints/proxyResources.ts index 175c8c79f..ba93bc46a 100644 --- a/server/lib/blueprints/proxyResources.ts +++ b/server/lib/blueprints/proxyResources.ts @@ -1,5 +1,6 @@ import { domains, + domainNamespaces, orgDomains, Resource, resourceHeaderAuth, @@ -33,6 +34,7 @@ import { hashPassword } from "@server/auth/password"; import { isValidCIDR, isValidIP, isValidUrlGlobPattern } from "../validators"; import { isValidRegionId } from "@server/db/regions"; import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed"; +import { fireHealthCheckUnknownAlert } from "#dynamic/lib/alerts"; import { tierMatrix } from "../billing/tierMatrix"; export type ProxyResourcesResults = { @@ -168,6 +170,19 @@ export async function updateProxyResources( .returning(); healthchecksToUpdate.push(newHealthcheck); + + // Insert unknown status history when HC is created in disabled state + if (!healthcheckData?.enabled) { + await fireHealthCheckUnknownAlert( + orgId, + newHealthcheck.targetHealthCheckId, + newHealthcheck.name, + newHealthcheck.targetId, + undefined, + true, + trx + ); + } } // Find existing resource by niceId and orgId @@ -236,6 +251,7 @@ export async function updateProxyResources( fullDomain: http ? resourceData["full-domain"] : null, subdomain: domain ? domain.subdomain : null, domainId: domain ? domain.domainId : null, + wildcard: domain ? domain.wildcard : false, enabled: resourceEnabled, sso: resourceData.auth?.["sso-enabled"] || false, skipToIdpId: @@ -555,6 +571,21 @@ export async function updateProxyResources( targetsToUpdate.push(updatedTarget); } } + + // Insert unknown status history when HC is disabled + const isDisablingHc = + !healthcheckData?.enabled && oldHealthcheck?.hcEnabled; + if (isDisablingHc) { + await fireHealthCheckUnknownAlert( + orgId, + newHealthcheck.targetHealthCheckId, + newHealthcheck.name, + newHealthcheck.targetId, + undefined, + true, + trx + ); + } } else { await createTarget(existingResource.resourceId, targetData); } @@ -683,6 +714,7 @@ export async function updateProxyResources( fullDomain: http ? resourceData["full-domain"] : null, subdomain: domain ? domain.subdomain : null, domainId: domain ? domain.domainId : null, + wildcard: domain ? domain.wildcard : false, enabled: resourceEnabled, sso: resourceData.auth?.["sso-enabled"] || false, skipToIdpId: resourceData.auth?.["auto-login-idp"] || null, @@ -1152,7 +1184,9 @@ async function getDomainId( orgId: string, fullDomain: string, trx: Transaction -): Promise<{ subdomain: string | null; domainId: string } | null> { +): Promise<{ subdomain: string | null; domainId: string; wildcard: boolean } | null> { + const isWildcardFullDomain = fullDomain.startsWith("*."); + const possibleDomains = await trx .select() .from(domains) @@ -1165,6 +1199,11 @@ async function getDomainId( } const validDomains = possibleDomains.filter((domain) => { + // Wildcard full-domains are not allowed on CNAME domains + if (isWildcardFullDomain && domain.domains.type === "cname") { + return false; + } + if (domain.domains.type == "ns" || domain.domains.type == "wildcard") { return ( fullDomain === domain.domains.baseDomain || @@ -1182,6 +1221,21 @@ async function getDomainId( const domainSelection = validDomains[0].domains; const baseDomain = domainSelection.baseDomain; + // Wildcard full-domains are not allowed on namespace (provided/free) domains + if (isWildcardFullDomain) { + const [namespaceDomain] = await trx + .select() + .from(domainNamespaces) + .where(eq(domainNamespaces.domainId, domainSelection.domainId)) + .limit(1); + + if (namespaceDomain) { + throw new Error( + `Wildcard full-domains are not supported for provided or free domains: ${fullDomain}` + ); + } + } + // remove the base domain of the domain let subdomain = null; if (fullDomain != baseDomain) { @@ -1191,6 +1245,7 @@ async function getDomainId( // Return the first valid domain return { subdomain: subdomain, - domainId: domainSelection.domainId + domainId: domainSelection.domainId, + wildcard: isWildcardFullDomain }; } diff --git a/server/lib/blueprints/types.ts b/server/lib/blueprints/types.ts index e017a16d1..13f4caa8f 100644 --- a/server/lib/blueprints/types.ts +++ b/server/lib/blueprints/types.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import { portRangeStringSchema } from "@server/lib/ip"; import { MaintenanceSchema } from "#dynamic/lib/blueprints/MaintenanceSchema"; import { isValidRegionId } from "@server/db/regions"; +import { wildcardSubdomainSchema } from "@server/lib/schemas"; export const SiteSchema = z.object({ name: z.string().min(1).max(100), @@ -319,6 +320,34 @@ export const ResourceSchema = z message: "Rules have conflicting or invalid priorities (must be unique, including auto-assigned ones)" } + ) + .refine( + (resource) => { + const fullDomain = resource["full-domain"]; + if (!fullDomain || !fullDomain.includes("*")) return true; + + // A wildcard full-domain must be of the form *.labels.basedomain + // Extract the leftmost label(s) before the first non-wildcard segment. + // e.g. "*.level1.example.com" → subdomain candidate is "*.level1" + // We do this by finding the base domain: everything after the first + // real (non-wildcard) dot-separated segment pair. + // + // Simple rule: split on ".", first token must be "*", rest must be + // valid hostname labels, and there must be at least 2 remaining labels + // (so the full domain has a real base domain). + const parts = fullDomain.split("."); + if (parts[0] !== "*") return false; // * must be the very first label + if (parts.includes("*", 1)) return false; // no further wildcards + if (parts.length < 3) return false; // need at least *.label.tld + + const labelRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$|^[a-zA-Z0-9]$/; + return parts.slice(1).every((label) => labelRegex.test(label)); + }, + { + path: ["full-domain"], + message: + 'Wildcard full-domain must have "*" as the leftmost label only, followed by at least two valid hostname labels (e.g. "*.example.com" or "*.level1.example.com"). Patterns like "*example.com" or "level2.*.example.com" are not supported.' + } ); export function isTargetsOnlyResource(resource: any): boolean { diff --git a/server/lib/domainUtils.ts b/server/lib/domainUtils.ts index 3562df683..138ffc74f 100644 --- a/server/lib/domainUtils.ts +++ b/server/lib/domainUtils.ts @@ -1,14 +1,16 @@ import { db } from "@server/db"; -import { domains, orgDomains } from "@server/db"; -import { eq, and } from "drizzle-orm"; -import { subdomainSchema } from "@server/lib/schemas"; +import { domains, orgDomains, domainNamespaces, resources } from "@server/db"; +import { eq, and, like, not } from "drizzle-orm"; +import { subdomainSchema, wildcardSubdomainSchema } from "@server/lib/schemas"; import { fromError } from "zod-validation-error"; +import config from "./config"; export type DomainValidationResult = | { success: true; fullDomain: string; subdomain: string | null; + wildcard: boolean; } | { success: false; @@ -66,6 +68,62 @@ export async function validateAndConstructDomain( }; } + // Detect wildcard subdomain request + const isWildcard = + subdomain !== undefined && + subdomain !== null && + subdomain.includes("*") && + domainRes.domains.type !== "cname"; + + // Wildcard subdomains are not allowed on CNAME domains + if (isWildcard && domainRes.domains.type === "cname") { + return { + success: false, + error: "Wildcard subdomains are not supported for CNAME domains. CNAME domains must use a specific hostname." + }; + } + + // Wildcard subdomains are not allowed on namespace (provided/free) domains + if (isWildcard) { + const [namespaceDomain] = await db + .select() + .from(domainNamespaces) + .where(eq(domainNamespaces.domainId, domainId)) + .limit(1); + + if (namespaceDomain) { + return { + success: false, + error: "Wildcard subdomains are not supported for provided or free domains. Use a specific subdomain instead." + }; + } + } + + if ( + isWildcard && + domainRes.domains.type == "wildcard" && + !( + domainRes.domains.preferWildcardCert || + config.getRawConfig().traefik.prefer_wildcard_cert + ) + ) { + return { + success: false, + error: "Wildcard domains are not supported without configuring certificate resolver for wildcard certs and marking it as prefered." + }; + } + + // Validate wildcard subdomain format + if (isWildcard) { + const parsedWildcard = wildcardSubdomainSchema.safeParse(subdomain); + if (!parsedWildcard.success) { + return { + success: false, + error: fromError(parsedWildcard.error).toString() + }; + } + } + // Construct full domain based on domain type let fullDomain = ""; let finalSubdomain = subdomain; @@ -81,13 +139,16 @@ export async function validateAndConstructDomain( finalSubdomain = null; // CNAME domains don't use subdomains } else if (domainRes.domains.type === "wildcard") { if (subdomain !== undefined && subdomain !== null) { - // Validate subdomain format for wildcard domains - const parsedSubdomain = subdomainSchema.safeParse(subdomain); - if (!parsedSubdomain.success) { - return { - success: false, - error: fromError(parsedSubdomain.error).toString() - }; + if (!isWildcard) { + // Validate regular subdomain format for wildcard domains + const parsedSubdomain = + subdomainSchema.safeParse(subdomain); + if (!parsedSubdomain.success) { + return { + success: false, + error: fromError(parsedSubdomain.error).toString() + }; + } } fullDomain = `${subdomain}.${domainRes.domains.baseDomain}`; } else { @@ -100,13 +161,14 @@ export async function validateAndConstructDomain( finalSubdomain = null; } - // Convert to lowercase + // Convert to lowercase (preserve * as-is) fullDomain = fullDomain.toLowerCase(); return { success: true, fullDomain, - subdomain: finalSubdomain ?? null + subdomain: finalSubdomain ?? null, + wildcard: isWildcard }; } catch (error) { return { @@ -115,3 +177,81 @@ export async function validateAndConstructDomain( }; } } + +/** + * Checks whether a given fullDomain conflicts with any existing wildcard resources, + * or (if the fullDomain is itself a wildcard) whether any existing resources would + * be matched by it. + * + * @param fullDomain - The fully-constructed domain to check (may contain a leading `*`) + * @param excludeResourceId - Optional resource ID to exclude from the check (for updates) + * @returns An object with `conflict: true` and a human-readable `message`, or `conflict: false` + */ +export async function checkWildcardDomainConflict( + fullDomain: string, + excludeResourceId?: number +): Promise<{ conflict: false } | { conflict: true; message: string }> { + const isWildcard = fullDomain.startsWith("*."); + + if (isWildcard) { + // e.g. fullDomain = "*.example.com" → suffix = ".example.com" + const suffix = fullDomain.slice(1); // ".example.com" + + // Find any existing non-wildcard resource whose fullDomain ends with this suffix + // e.g. "test.example.com" or "foo.example.com" + const conflicting = await db + .select({ + resourceId: resources.resourceId, + fullDomain: resources.fullDomain + }) + .from(resources) + .where(like(resources.fullDomain, `%${suffix}`)); + + const matches = conflicting.filter( + (r) => + !r.fullDomain!.startsWith("*.") && + r.fullDomain!.endsWith(suffix) && + (excludeResourceId === undefined || + r.resourceId !== excludeResourceId) + ); + + if (matches.length > 0) { + return { + conflict: true, + message: `Wildcard domain ${fullDomain} conflicts with existing resource(s): ${matches.map((r) => r.fullDomain).join(", ")}` + }; + } + } else { + // Specific domain — check if any existing wildcard would match it. + // e.g. fullDomain = "test.example.com" + // We look for a wildcard "*.example.com" which means fullDomain ends with ".example.com" + const dotIndex = fullDomain.indexOf("."); + if (dotIndex !== -1) { + const suffix = fullDomain.slice(dotIndex); // ".example.com" + const wildcardPattern = `*.${fullDomain.slice(dotIndex + 1)}`; // "*.example.com" + + const conflicting = await db + .select({ + resourceId: resources.resourceId, + fullDomain: resources.fullDomain + }) + .from(resources) + .where(eq(resources.fullDomain, wildcardPattern)); + + const matches = conflicting.filter( + (r) => + excludeResourceId === undefined || + r.resourceId !== excludeResourceId + ); + + if (matches.length > 0) { + return { + conflict: true, + message: `Domain ${fullDomain} conflicts with existing wildcard resource(s): ${matches.map((r) => r.fullDomain).join(", ")}` + }; + } + } + } + + return { conflict: false }; +} diff --git a/server/lib/ip.ts b/server/lib/ip.ts index 3e57e8c94..929399f7b 100644 --- a/server/lib/ip.ts +++ b/server/lib/ip.ts @@ -700,7 +700,6 @@ export async function generateSubnetProxyTargetV2( targets.push({ sourcePrefixes: [], destPrefix: `${siteResource.aliasAddress}/32`, - rewriteTo: destination, portRange, disableIcmp, resourceId: siteResource.siteResourceId, diff --git a/server/lib/rebuildClientAssociations.ts b/server/lib/rebuildClientAssociations.ts index 40c5a5bf7..a5c9a9321 100644 --- a/server/lib/rebuildClientAssociations.ts +++ b/server/lib/rebuildClientAssociations.ts @@ -180,36 +180,41 @@ export async function rebuildClientAssociationsFromSiteResource( /////////// process the client-siteResource associations /////////// - // 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 + // get all of the clients associated with other site resources that share + // any of the same sites as this site resource (via siteNetworks). We can't + // simply filter by networkId since each site resource has its own network; + // two site resources serving the same site typically belong to different + // networks that both happen to include the site through siteNetworks. + const sitesListSiteIds = sitesList.map((s) => s.siteId); + const allUpdatedClientsFromOtherResourcesOnThisSite = + sitesListSiteIds.length > 0 + ? 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( + inArray(siteNetworks.siteId, sitesListSiteIds), + ne( + siteResources.siteResourceId, + siteResource.siteResourceId + ) + ) + ) + : []; // Build a per-site map so the loop below can check by siteId rather than // across the entire network. diff --git a/server/lib/schemas.ts b/server/lib/schemas.ts index 5e2bd400b..813849d52 100644 --- a/server/lib/schemas.ts +++ b/server/lib/schemas.ts @@ -1,5 +1,41 @@ import { z } from "zod"; +/** + * Validates a wildcard subdomain passed as the leftmost component of a full domain. + * + * The value represents everything to the left of the base domain, so when combined + * with e.g. "example.com" it must produce a valid SSL-style wildcard hostname. + * + * Valid: + * "*" → *.example.com + * "*.level1" → *.level1.example.com + * + * Invalid: + * "*example" → *example.com (no dot after *) + * "level2.*.level1" → wildcard not in leftmost position + * "*.level1.*" → multiple wildcards + */ +export const wildcardSubdomainSchema = z + .string() + .refine( + (val) => { + // Must start with "*."; the remainder (if any) must be valid hostname labels. + // A bare "*" is also valid (becomes *.baseDomain directly). + if (val === "*") return true; + if (!val.startsWith("*.")) return false; + const rest = val.slice(2); // everything after "*." + // rest must not be empty, must not contain another "*", + // and every label must be a valid hostname label. + if (!rest || rest.includes("*")) return false; + const labelRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/; + return rest.split(".").every((label) => labelRegex.test(label)); + }, + { + message: + 'Invalid wildcard subdomain. The wildcard "*" must be the leftmost label followed by a dot and valid hostname labels (e.g. "*" or "*.level1"). Patterns like "*example", "level2.*.level1", or multiple wildcards are not supported.' + } + ); + export const subdomainSchema = z .string() .regex( diff --git a/server/lib/statusHistory.ts b/server/lib/statusHistory.ts index 001a0b93b..3a9b1f6ef 100644 --- a/server/lib/statusHistory.ts +++ b/server/lib/statusHistory.ts @@ -1,15 +1,84 @@ import { z } from "zod"; +import { db, logsDb, statusHistory } from "@server/db"; +import { and, eq, gte, asc } from "drizzle-orm"; +import cache from "@server/lib/cache"; + +const STATUS_HISTORY_CACHE_TTL = 60; // seconds + +function statusHistoryCacheKey( + entityType: string, + entityId: number, + days: number +): string { + return `statusHistory:${entityType}:${entityId}:${days}`; +} + +export async function getCachedStatusHistory( + entityType: string, + entityId: number, + days: number +): Promise { + const cacheKey = statusHistoryCacheKey(entityType, entityId, days); + const cached = await cache.get(cacheKey); + if (cached !== undefined) { + return cached; + } + + const nowSec = Math.floor(Date.now() / 1000); + const startSec = nowSec - days * 86400; + + const events = await logsDb + .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; + + const result: StatusHistoryResponse = { + entityType, + entityId, + days: buckets, + overallUptimePercent: Math.round(overallUptime * 100) / 100, + totalDowntimeSeconds: totalDowntime + }; + + await cache.set(cacheKey, result, STATUS_HISTORY_CACHE_TTL); + return result; +} + +export async function invalidateStatusHistoryCache( + entityType: string, + entityId: number +): Promise { + const prefix = `statusHistory:${entityType}:${entityId}:`; + const keys = cache.keys().filter((k) => k.startsWith(prefix)); + if (keys.length > 0) { + await cache.del(keys); + } +} export const statusHistoryQuerySchema = z .object({ days: z .string() .optional() - .transform((v) => (v ? parseInt(v, 10) : 90)), + .transform((v) => (v ? parseInt(v, 10) : 90)) }) .pipe( z.object({ - days: z.number().int().min(1).max(365), + days: z.number().int().min(1).max(365) }) ); @@ -18,7 +87,7 @@ export interface StatusHistoryDayBucket { uptimePercent: number; // 0-100 totalDowntimeSeconds: number; downtimeWindows: { start: number; end: number | null; status: string }[]; - status: "good" | "degraded" | "bad" | "no_data"; + status: "good" | "degraded" | "bad" | "no_data" | "unknown"; } export interface StatusHistoryResponse { @@ -30,7 +99,14 @@ export interface StatusHistoryResponse { } export function computeBuckets( - events: { entityType: string; entityId: number; orgId: string; status: string; timestamp: number; id: number }[], + 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); @@ -52,8 +128,10 @@ export function computeBuckets( const currentStatus = lastBeforeDay?.status ?? null; - const windows: { start: number; end: number | null; status: string }[] = []; + const windows: { start: number; end: number | null; status: string }[] = + []; let dayDowntime = 0; + let dayDegradedTime = 0; let windowStart = dayStartSec; let windowStatus = currentStatus; @@ -62,15 +140,21 @@ export function computeBuckets( if (windowStatus !== null && windowStatus !== evt.status) { const windowEnd = evt.timestamp; const isDown = - windowStatus === "offline" || - windowStatus === "unhealthy" || - windowStatus === "unknown"; + windowStatus === "offline" || windowStatus === "unhealthy"; + const isDegraded = windowStatus === "degraded"; if (isDown) { dayDowntime += windowEnd - windowStart; windows.push({ start: windowStart, end: windowEnd, - status: windowStatus, + status: windowStatus + }); + } else if (isDegraded) { + dayDegradedTime += windowEnd - windowStart; + windows.push({ + start: windowStart, + end: windowEnd, + status: windowStatus }); } } @@ -82,15 +166,21 @@ export function computeBuckets( if (windowStatus !== null) { const finalEnd = Math.min(dayEndSec, nowSec); const isDown = - windowStatus === "offline" || - windowStatus === "unhealthy" || - windowStatus === "unknown"; + windowStatus === "offline" || windowStatus === "unhealthy"; + const isDegraded = windowStatus === "degraded"; if (isDown && finalEnd > windowStart) { dayDowntime += finalEnd - windowStart; windows.push({ start: windowStart, end: finalEnd, - status: windowStatus, + status: windowStatus + }); + } else if (isDegraded && finalEnd > windowStart) { + dayDegradedTime += finalEnd - windowStart; + windows.push({ + start: windowStart, + end: finalEnd, + status: windowStatus }); } } @@ -105,7 +195,7 @@ export function computeBuckets( effectiveDayLength > 0 ? Math.max( 0, - ((effectiveDayLength - dayDowntime) / + ((effectiveDayLength - dayDowntime - dayDegradedTime) / effectiveDayLength) * 100 ) @@ -113,11 +203,27 @@ export function computeBuckets( const dateStr = new Date(dayStartSec * 1000).toISOString().slice(0, 10); + const hasAnyData = currentStatus !== null || dayEvents.length > 0; + + // The whole observable window is "unknown" if every status we have seen is unknown + const allStatuses = [ + ...(currentStatus !== null ? [currentStatus] : []), + ...dayEvents.map((e) => e.status) + ]; + const onlyUnknownData = + hasAnyData && allStatuses.every((s) => s === "unknown"); + 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"; + if (hasAnyData) { + if (onlyUnknownData) { + status = "unknown"; + } else if (dayDowntime > 0 && uptimePct < 50) { + status = "bad"; + } else if (dayDowntime > 0 || dayDegradedTime > 0) { + status = "degraded"; + } else { + status = "good"; + } } buckets.push({ @@ -125,7 +231,7 @@ export function computeBuckets( uptimePercent: Math.round(uptimePct * 100) / 100, totalDowntimeSeconds: dayDowntime, downtimeWindows: windows, - status, + status }); } diff --git a/server/private/lib/acmeCertSync.ts b/server/private/lib/acmeCertSync.ts index 24d612661..06b427955 100644 --- a/server/private/lib/acmeCertSync.ts +++ b/server/private/lib/acmeCertSync.ts @@ -50,7 +50,7 @@ interface AcmeJson { }; } -async function pushCertUpdateToAffectedNewts( +export async function pushCertUpdateToAffectedNewts( domain: string, domainId: string | null, oldCertPem: string | null, @@ -250,10 +250,31 @@ function extractFirstCert(pemBundle: string): string | null { return match ? match[0] : null; } -async function syncAcmeCerts( - acmeJsonPath: string, - resolver: string -): Promise { +/** + * Determine whether an ACME cert entry represents a wildcard cert by checking + * both the primary domain (`main`) and the SANs. Some ACME clients (notably + * Traefik) store the bare apex in `main` and only put the wildcard form in + * `sans` (e.g. main="access.example.com", sans=["*.access.example.com"]). + */ +function detectWildcard( + main: string, + sans: string[] | undefined +): { wildcard: boolean; wildcardSan: string | null } { + if (main.startsWith("*.")) { + return { wildcard: true, wildcardSan: null }; + } + if (Array.isArray(sans)) { + for (const san of sans) { + if (typeof san !== "string") continue; + if (san === `*.${main}` || san.startsWith("*.")) { + return { wildcard: true, wildcardSan: san }; + } + } + } + return { wildcard: false, wildcardSan: null }; +} + +async function syncAcmeCerts(acmeJsonPath: string): Promise { let raw: string; try { raw = fs.readFileSync(acmeJsonPath, "utf8"); @@ -270,23 +291,41 @@ async function syncAcmeCerts( return; } - const resolverData = acmeJson[resolver]; - if (!resolverData || !Array.isArray(resolverData.Certificates)) { - logger.debug( - `acmeCertSync: no certificates found for resolver "${resolver}"` - ); + const resolvers = Object.keys(acmeJson || {}); + if (resolvers.length === 0) { + logger.debug(`acmeCertSync: no resolvers found in acme.json`); return; } - for (const cert of resolverData.Certificates) { - const domain = cert.domain?.main; - const wildcard = domain.startsWith("*."); + // Collect certificates from every resolver. If the same domain appears in + // multiple resolvers, the last one wins (resolvers iterated in object order). + const allCerts: AcmeCert[] = []; + for (const resolver of resolvers) { + const resolverData = acmeJson[resolver]; + if (!resolverData || !Array.isArray(resolverData.Certificates)) { + logger.debug( + `acmeCertSync: no certificates found for resolver "${resolver}"` + ); + continue; + } + logger.debug( + `acmeCertSync: found ${resolverData.Certificates.length} certificate(s) for resolver "${resolver}"` + ); + for (const cert of resolverData.Certificates) { + allCerts.push(cert); + } + } - if (!domain) { + for (const cert of allCerts) { + const domain = cert?.domain?.main; + + if (!domain || typeof domain !== "string") { logger.debug(`acmeCertSync: skipping cert with missing domain`); continue; } + const { wildcard } = detectWildcard(domain, cert.domain?.sans); + if (!cert.certificate || !cert.key) { logger.debug( `acmeCertSync: skipping cert for ${domain} - empty certificate or key field` @@ -294,10 +333,17 @@ async function syncAcmeCerts( continue; } - const certPem = Buffer.from(cert.certificate, "base64").toString( - "utf8" - ); - const keyPem = Buffer.from(cert.key, "base64").toString("utf8"); + let certPem: string; + let keyPem: string; + try { + certPem = Buffer.from(cert.certificate, "base64").toString("utf8"); + keyPem = Buffer.from(cert.key, "base64").toString("utf8"); + } catch (err) { + logger.debug( + `acmeCertSync: skipping cert for ${domain} - failed to base64-decode cert/key: ${err}` + ); + continue; + } if (!certPem.trim() || !keyPem.trim()) { logger.debug( @@ -306,14 +352,46 @@ async function syncAcmeCerts( continue; } + // Validate that the decoded data actually parses as a real X.509 cert + // before we touch the database. This prevents importing partially-written + // or corrupted entries from acme.json. + const firstCertPemForValidation = extractFirstCert(certPem); + if (!firstCertPemForValidation) { + logger.debug( + `acmeCertSync: skipping cert for ${domain} - no PEM certificate block found` + ); + continue; + } + + let validatedX509: crypto.X509Certificate; + try { + validatedX509 = new crypto.X509Certificate( + firstCertPemForValidation + ); + } catch (err) { + logger.debug( + `acmeCertSync: skipping cert for ${domain} - invalid X.509 certificate: ${err}` + ); + continue; + } + + // Sanity-check the private key parses too + try { + crypto.createPrivateKey(keyPem); + } catch (err) { + logger.debug( + `acmeCertSync: skipping cert for ${domain} - invalid private key: ${err}` + ); + continue; + } + // Check if cert already exists in DB const existing = await db .select() .from(certificates) .where( and( - eq(certificates.domain, domain), - eq(certificates.wildcard, wildcard) + eq(certificates.domain, domain) ) ) .limit(1); @@ -327,10 +405,11 @@ async function syncAcmeCerts( existing[0].certFile, config.getRawConfig().server.secret! ); - if (storedCertPem === certPem) { - logger.debug( - `acmeCertSync: cert for ${domain} is unchanged, skipping` - ); + const wildcardUnchanged = existing[0].wildcard === wildcard; + if (storedCertPem === certPem && wildcardUnchanged) { + // logger.debug( + // `acmeCertSync: cert for ${domain} is unchanged, skipping` + // ); continue; } // Cert has changed; capture old values so we can send a correct @@ -356,18 +435,16 @@ async function syncAcmeCerts( } } - // Parse cert expiry from the first cert in the PEM bundle + // Parse cert expiry from the validated X.509 certificate 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}` - ); - } + try { + expiresAt = Math.floor( + new Date(validatedX509.validTo).getTime() / 1000 + ); + } catch (err) { + logger.debug( + `acmeCertSync: could not parse cert expiry for ${domain}: ${err}` + ); } const encryptedCert = encrypt( @@ -392,6 +469,9 @@ async function syncAcmeCerts( } if (existing.length > 0) { + logger.debug( + `acmeCertSync: updating existing certificate for ${domain} (expires ${expiresAt ? new Date(expiresAt * 1000).toISOString() : "unknown"})` + ); await db .update(certificates) .set({ @@ -416,6 +496,9 @@ async function syncAcmeCerts( oldKeyPem ); } else { + logger.debug( + `acmeCertSync: inserting new certificate for ${domain} (expires ${expiresAt ? new Date(expiresAt * 1000).toISOString() : "unknown"})` + ); await db.insert(certificates).values({ domain, domainId, @@ -463,20 +546,19 @@ export function initAcmeCertSync(): void { 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` + `acmeCertSync: starting ACME cert sync from "${acmeJsonPath}" across all resolvers every ${intervalMs}ms` ); // Run immediately on init, then on the configured interval - syncAcmeCerts(acmeJsonPath, resolver).catch((err) => { + syncAcmeCerts(acmeJsonPath).catch((err) => { logger.error(`acmeCertSync: error during initial sync: ${err}`); }); setInterval(() => { - syncAcmeCerts(acmeJsonPath, resolver).catch((err) => { + syncAcmeCerts(acmeJsonPath).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 index 4851f08c4..ae9f1f05b 100644 --- a/server/private/lib/alerts/events/healthCheckEvents.ts +++ b/server/private/lib/alerts/events/healthCheckEvents.ts @@ -19,12 +19,16 @@ import { targetHealthCheck, targets, resources, - Transaction + Transaction, + logsDb } from "@server/db"; import { eq } from "drizzle-orm"; +import { invalidateStatusHistoryCache } from "@server/lib/statusHistory"; import { + fireResourceDegradedAlert, fireResourceHealthyAlert, - fireResourceUnhealthyAlert + fireResourceUnhealthyAlert, + fireResourceUnknownAlert } from "./resourceEvents"; // --------------------------------------------------------------------------- @@ -48,18 +52,24 @@ export async function fireHealthCheckHealthyAlert( healthCheckName?: string | null, healthCheckTargetId?: number | null, extra?: Record, + send: boolean = true, trx: Transaction | typeof db = db ): Promise { try { - await trx.insert(statusHistory).values({ + await logsDb.insert(statusHistory).values({ entityType: "health_check", entityId: healthCheckId, orgId: orgId, status: "healthy", timestamp: Math.floor(Date.now() / 1000) }); + await invalidateStatusHistoryCache("health_check", healthCheckId); - await handleResource(orgId, healthCheckTargetId, trx); + await handleResource(orgId, healthCheckTargetId, send, trx); + + if (!send) { + return; + } await processAlerts({ eventType: "health_check_healthy", @@ -106,18 +116,24 @@ export async function fireHealthCheckUnhealthyAlert( healthCheckName?: string | null, healthCheckTargetId?: number | null, extra?: Record, + send: boolean = true, trx: Transaction | typeof db = db ): Promise { try { - await trx.insert(statusHistory).values({ + await logsDb.insert(statusHistory).values({ entityType: "health_check", entityId: healthCheckId, orgId: orgId, status: "unhealthy", timestamp: Math.floor(Date.now() / 1000) }); + await invalidateStatusHistoryCache("health_check", healthCheckId); - await handleResource(orgId, healthCheckTargetId, trx); + await handleResource(orgId, healthCheckTargetId, send, trx); + + if (!send) { + return; + } await processAlerts({ eventType: "health_check_unhealthy", @@ -147,11 +163,48 @@ export async function fireHealthCheckUnhealthyAlert( } } -async function handleResource(orgId: string, healthCheckTargetId?: number | null, trx: Transaction | typeof db = db) { +export async function fireHealthCheckUnknownAlert( + orgId: string, + healthCheckId: number, + healthCheckName?: string | null, + healthCheckTargetId?: number | null, + extra?: Record, + send: boolean = true, + trx: Transaction | typeof db = db +): Promise { + try { + await logsDb.insert(statusHistory).values({ + entityType: "health_check", + entityId: healthCheckId, + orgId: orgId, + status: "unknown", + timestamp: Math.floor(Date.now() / 1000) + }); + await invalidateStatusHistoryCache("health_check", healthCheckId); + + await handleResource(orgId, healthCheckTargetId, send, trx); + + if (!send) { + return; + } + } catch (err) { + logger.error( + `fireHealthCheckUnknownAlert: unexpected error for healthCheckId ${healthCheckId}`, + err + ); + } +} + +async function handleResource( + orgId: string, + healthCheckTargetId?: number | null, + send: boolean = true, + trx: Transaction | typeof db = db +) { if (!healthCheckTargetId) { return; } - // we have resources lets get them + // we have targets lets get them const [target] = await trx .select() .from(targets) @@ -161,6 +214,7 @@ async function handleResource(orgId: string, healthCheckTargetId?: number | null if (!target) { return; } + const [resource] = await trx .select() .from(resources) @@ -170,18 +224,38 @@ async function handleResource(orgId: string, healthCheckTargetId?: number | null if (!resource) { return; } + const otherTargets = await trx .select({ hcHealth: targetHealthCheck.hcHealth }) .from(targets) + .innerJoin( + targetHealthCheck, + eq(targetHealthCheck.targetId, targets.targetId) + ) .where(eq(targets.resourceId, resource.resourceId)); let health = "healthy"; + const allUnknown = otherTargets.every((t) => t.hcHealth === "unknown"); const allHealthy = otherTargets.every((t) => t.hcHealth === "healthy"); - if (!allHealthy) { + const allUnhealthy = otherTargets.every((t) => t.hcHealth === "unhealthy"); + + if (allUnknown) { logger.debug( - `Not marking resource ${resource.resourceId} as healthy because not all targets are healthy` + `Marking resource ${resource.resourceId} as unknown because all health checks are disabled` + ); + health = "unknown"; + } else if (allHealthy) { + health = "healthy"; + } else if (allUnhealthy) { + logger.debug( + `Marking resource ${resource.resourceId} as unhealthy because all targets are unhealthy` ); health = "unhealthy"; + } else { + logger.debug( + `Marking resource ${resource.resourceId} as degraded because some targets are unhealthy` + ); + health = "degraded"; } if (health != resource.health) { @@ -191,12 +265,22 @@ async function handleResource(orgId: string, healthCheckTargetId?: number | null .set({ health }) .where(eq(resources.resourceId, resource.resourceId)); - if (health === "unhealthy") { + if (health === "unknown") { + await fireResourceUnknownAlert( + orgId, + resource.resourceId, + resource.name, + undefined, + send, + trx + ); + } else if (health === "unhealthy") { await fireResourceUnhealthyAlert( orgId, resource.resourceId, resource.name, undefined, + send, trx ); } else if (health === "healthy") { @@ -205,6 +289,16 @@ async function handleResource(orgId: string, healthCheckTargetId?: number | null resource.resourceId, resource.name, undefined, + send, + trx + ); + } else if (health === "degraded") { + await fireResourceDegradedAlert( + orgId, + resource.resourceId, + resource.name, + undefined, + send, trx ); } diff --git a/server/private/lib/alerts/events/resourceEvents.ts b/server/private/lib/alerts/events/resourceEvents.ts index 8c20bc5a1..54b40b80d 100644 --- a/server/private/lib/alerts/events/resourceEvents.ts +++ b/server/private/lib/alerts/events/resourceEvents.ts @@ -13,7 +13,8 @@ import logger from "@server/logger"; import { processAlerts } from "../processAlerts"; -import { db, statusHistory, Transaction } from "@server/db"; +import { db, logsDb, statusHistory, Transaction } from "@server/db"; +import { invalidateStatusHistoryCache } from "@server/lib/statusHistory"; // --------------------------------------------------------------------------- // Public API @@ -35,16 +36,22 @@ export async function fireResourceHealthyAlert( resourceId: number, resourceName?: string | null, extra?: Record, + send: boolean = true, trx: Transaction | typeof db = db ): Promise { try { - await trx.insert(statusHistory).values({ + await logsDb.insert(statusHistory).values({ entityType: "resource", entityId: resourceId, orgId: orgId, status: "healthy", timestamp: Math.floor(Date.now() / 1000) }); + await invalidateStatusHistoryCache("resource", resourceId); + + if (!send) { + return; + } await processAlerts({ eventType: "resource_healthy", @@ -90,16 +97,22 @@ export async function fireResourceUnhealthyAlert( resourceId: number, resourceName?: string | null, extra?: Record, + send: boolean = true, trx: Transaction | typeof db = db ): Promise { try { - await trx.insert(statusHistory).values({ + await logsDb.insert(statusHistory).values({ entityType: "resource", entityId: resourceId, orgId: orgId, status: "unhealthy", timestamp: Math.floor(Date.now() / 1000) }); + await invalidateStatusHistoryCache("resource", resourceId); + + if (!send) { + return; + } await processAlerts({ eventType: "resource_unhealthy", @@ -130,9 +143,9 @@ export async function fireResourceUnhealthyAlert( } /** - * Fire a `resource_toggle` alert for the given resource. + * Fire a `resource_degraded` alert for the given resource. * - * Call this when a resource's enabled/disabled status is toggled so that any + * Call this after a resource has been detected as degraded so that any * matching `alertRules` can dispatch their email and webhook actions. * * @param orgId - Organisation that owns the resource. @@ -140,16 +153,30 @@ export async function fireResourceUnhealthyAlert( * @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( +export async function fireResourceDegradedAlert( orgId: string, resourceId: number, resourceName?: string | null, extra?: Record, + send: boolean = true, trx: Transaction | typeof db = db ): Promise { try { + await logsDb.insert(statusHistory).values({ + entityType: "resource", + entityId: resourceId, + orgId: orgId, + status: "degraded", + timestamp: Math.floor(Date.now() / 1000) + }); + await invalidateStatusHistoryCache("resource", resourceId); + + if (!send) { + return; + } + await processAlerts({ - eventType: "resource_toggle", + eventType: "resource_degraded", orgId, resourceId, data: { @@ -157,9 +184,72 @@ export async function fireResourceToggleAlert( ...extra } }); + await processAlerts({ + eventType: "resource_toggle", + orgId, + resourceId, + data: { + resourceId, + status: "degraded", + ...(resourceName != null ? { resourceName } : {}), + ...extra + } + }); } catch (err) { logger.error( - `fireResourceToggleAlert: unexpected error for resourceId ${resourceId}`, + `fireResourceDegradedAlert: unexpected error for resourceId ${resourceId}`, + err + ); + } +} + +/** + * Fire a `resource_unknown` alert for the given resource. + * + * Call this when all health checks on a resource are disabled so that the + * resource status transitions to unknown. + * + * @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 fireResourceUnknownAlert( + orgId: string, + resourceId: number, + resourceName?: string | null, + extra?: Record, + send: boolean = true, + trx: Transaction | typeof db = db +): Promise { + try { + await logsDb.insert(statusHistory).values({ + entityType: "resource", + entityId: resourceId, + orgId: orgId, + status: "unknown", + timestamp: Math.floor(Date.now() / 1000) + }); + await invalidateStatusHistoryCache("resource", resourceId); + + if (!send) { + return; + } + + await processAlerts({ + eventType: "resource_toggle", + orgId, + resourceId, + data: { + resourceId, + status: "unknown", + ...(resourceName != null ? { resourceName } : {}), + ...extra + } + }); + } catch (err) { + logger.error( + `fireResourceUnknownAlert: unexpected error for resourceId ${resourceId}`, err ); } diff --git a/server/private/lib/alerts/events/siteEvents.ts b/server/private/lib/alerts/events/siteEvents.ts index 562accc18..e1871dc85 100644 --- a/server/private/lib/alerts/events/siteEvents.ts +++ b/server/private/lib/alerts/events/siteEvents.ts @@ -13,7 +13,14 @@ import logger from "@server/logger"; import { processAlerts } from "../processAlerts"; -import { db, sites, statusHistory, targetHealthCheck, Transaction } from "@server/db"; +import { + db, + logsDb, + statusHistory, + targetHealthCheck, + Transaction +} from "@server/db"; +import { invalidateStatusHistoryCache } from "@server/lib/statusHistory"; import { and, eq, inArray } from "drizzle-orm"; import { fireHealthCheckUnhealthyAlert } from "./healthCheckEvents"; @@ -40,13 +47,14 @@ export async function fireSiteOnlineAlert( trx: Transaction | typeof db = db ): Promise { try { - await trx.insert(statusHistory).values({ + await logsDb.insert(statusHistory).values({ entityType: "site", entityId: siteId, orgId: orgId, status: "online", timestamp: Math.floor(Date.now() / 1000) }); + await invalidateStatusHistoryCache("site", siteId); await processAlerts({ eventType: "site_online", @@ -95,13 +103,14 @@ export async function fireSiteOfflineAlert( trx: Transaction | typeof db = db ): Promise { try { - await trx.insert(statusHistory).values({ + await logsDb.insert(statusHistory).values({ entityType: "site", entityId: siteId, orgId: orgId, status: "offline", timestamp: Math.floor(Date.now() / 1000) }); + await invalidateStatusHistoryCache("site", siteId); const unhealthyHealthChecks = await trx .update(targetHealthCheck) @@ -109,7 +118,8 @@ export async function fireSiteOfflineAlert( .where( and( eq(targetHealthCheck.orgId, orgId), - eq(targetHealthCheck.siteId, siteId) + eq(targetHealthCheck.siteId, siteId), + eq(targetHealthCheck.hcEnabled, true) // only effect the ones that are enabled ) ) .returning(); @@ -123,8 +133,9 @@ export async function fireSiteOfflineAlert( healthCheck.orgId, healthCheck.targetHealthCheckId, healthCheck.name, + healthCheck.targetId, // for the resource if we have one undefined, - undefined, + true, trx ); } diff --git a/server/private/lib/alerts/sendAlertEmail.ts b/server/private/lib/alerts/sendAlertEmail.ts index 598262e38..6f99b102c 100644 --- a/server/private/lib/alerts/sendAlertEmail.ts +++ b/server/private/lib/alerts/sendAlertEmail.ts @@ -88,6 +88,8 @@ function buildSubject(context: AlertContext): string { return "[Alert] Resource Healthy"; case "resource_unhealthy": return "[Alert] Resource Unhealthy"; + case "resource_degraded": + return "[Alert] Resource Degraded"; case "resource_toggle": return "[Alert] Resource Status Changed"; default: { diff --git a/server/private/lib/alerts/sendAlertWebhook.ts b/server/private/lib/alerts/sendAlertWebhook.ts index 2dd0eb600..3975eb09f 100644 --- a/server/private/lib/alerts/sendAlertWebhook.ts +++ b/server/private/lib/alerts/sendAlertWebhook.ts @@ -12,7 +12,10 @@ */ import logger from "@server/logger"; -import { AlertContext, WebhookAlertConfig } from "@server/routers/alertRule/types"; +import { + AlertContext, + WebhookAlertConfig +} from "@server/routers/alertRule/types"; const REQUEST_TIMEOUT_MS = 15_000; const MAX_RETRIES = 3; @@ -56,7 +59,10 @@ export async function sendAlertWebhook( for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) { const controller = new AbortController(); - const timeoutHandle = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); + const timeoutHandle = setTimeout( + () => controller.abort(), + REQUEST_TIMEOUT_MS + ); let response: Response; try { @@ -75,7 +81,9 @@ export async function sendAlertWebhook( ); } else { const msg = err instanceof Error ? err.message : String(err); - lastError = new Error(`Alert webhook: request to "${url}" failed – ${msg}`); + lastError = new Error( + `Alert webhook: request to "${url}" failed – ${msg}` + ); } if (attempt < MAX_RETRIES) { const delay = RETRY_BASE_DELAY_MS * 2 ** (attempt - 1); @@ -111,11 +119,18 @@ export async function sendAlertWebhook( continue; } - logger.debug(`Alert webhook sent successfully to "${url}" for event "${context.eventType}" (attempt ${attempt}/${MAX_RETRIES})`); + logger.debug( + `Alert webhook sent successfully to "${url}" for event "${context.eventType}" (attempt ${attempt}/${MAX_RETRIES})` + ); return; } - throw lastError ?? new Error(`Alert webhook: all ${MAX_RETRIES} attempts failed for "${url}"`); + throw ( + lastError ?? + new Error( + `Alert webhook: all ${MAX_RETRIES} attempts failed for "${url}"` + ) + ); } // --------------------------------------------------------------------------- @@ -139,6 +154,8 @@ function deriveStatus( case "health_check_unhealthy": case "resource_unhealthy": return "unhealthy"; + case "resource_degraded": + return "degraded"; case "health_check_toggle": case "resource_toggle": return String(data.status ?? "unknown"); @@ -154,7 +171,9 @@ function deriveStatus( // Header construction (mirrors HttpLogDestination.buildHeaders) // --------------------------------------------------------------------------- -function buildHeaders(webhookConfig: WebhookAlertConfig): Record { +function buildHeaders( + webhookConfig: WebhookAlertConfig +): Record { const headers: Record = { "Content-Type": "application/json" }; diff --git a/server/private/lib/alerts/types.ts b/server/private/lib/alerts/types.ts new file mode 100644 index 000000000..e79db2ef5 --- /dev/null +++ b/server/private/lib/alerts/types.ts @@ -0,0 +1,63 @@ +/* + * 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" + | "health_check_healthy" + | "health_check_not_healthy"; + +// --------------------------------------------------------------------------- +// 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; + /** Human-readable context data included in emails and webhook payloads */ + data: Record; +} \ No newline at end of file diff --git a/server/private/lib/readConfigFile.ts b/server/private/lib/readConfigFile.ts index c9cb1535a..056624159 100644 --- a/server/private/lib/readConfigFile.ts +++ b/server/private/lib/readConfigFile.ts @@ -102,7 +102,6 @@ export const privateConfigSchema = z.object({ .string() .optional() .default("config/letsencrypt/acme.json"), - resolver: z.string().optional().default("letsencrypt"), sync_interval_ms: z.number().optional().default(5000) }) .optional(), diff --git a/server/private/lib/traefik/getTraefikConfig.ts b/server/private/lib/traefik/getTraefikConfig.ts index fb6e176b8..481192fb5 100644 --- a/server/private/lib/traefik/getTraefikConfig.ts +++ b/server/private/lib/traefik/getTraefikConfig.ts @@ -33,7 +33,15 @@ import { } from "drizzle-orm"; import logger from "@server/logger"; import config from "@server/lib/config"; -import { orgs, resources, sites, siteNetworks, siteResources, Target, targets } from "@server/db"; +import { + orgs, + resources, + sites, + siteNetworks, + siteResources, + Target, + targets +} from "@server/db"; import { sanitize, encodePath, @@ -100,6 +108,7 @@ export async function getTraefikConfig( headers: resources.headers, proxyProtocol: resources.proxyProtocol, proxyProtocolVersion: resources.proxyProtocolVersion, + wildcard: resources.wildcard, maintenanceModeEnabled: resources.maintenanceModeEnabled, maintenanceModeType: resources.maintenanceModeType, @@ -238,6 +247,7 @@ export async function getTraefikConfig( priority: priority, // may be null, we fallback later domainCertResolver: row.domainCertResolver, preferWildcardCert: row.preferWildcardCert, + wildcard: row.wildcard, maintenanceModeEnabled: row.maintenanceModeEnabled, maintenanceModeType: row.maintenanceModeType, @@ -267,34 +277,37 @@ 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 siteResourcesWithFullDomain: { + siteResourceId: number; + fullDomain: string | null; + mode: "http" | "host" | "cidr"; + }[] = []; + if (build == "enterprise") { + // we dont want to do this on the cloud + // Query siteResources in HTTP mode with SSL enabled and aliases - cert generation / HTTPS edge + 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), + eq(sites.exitNodeId, exitNodeId), + inArray(sites.type, siteTypes) + ) + ); + } let validCerts: CertificateResult[] = []; if (privateConfig.getRawPrivateConfig().flags.use_pangolin_dns) { @@ -376,7 +389,16 @@ export async function getTraefikConfig( ...additionalMiddlewares ]; - let rule = `Host(\`${fullDomain}\`)`; + let rule: string; + if (resource.wildcard && fullDomain.startsWith("*.")) { + // Convert *.foo.bar.com -> HostRegexp(`^[^.]+\.foo\.bar\.com$`) + const escaped = fullDomain + .slice(2) // remove leading "*." + .replace(/\./g, "\\."); + rule = `HostRegexp(\`^[^.]+\\.${escaped}$\`)`; + } else { + rule = `Host(\`${fullDomain}\`)`; + } // priority logic let priority: number; @@ -419,7 +441,8 @@ export async function getTraefikConfig( config.getRawConfig().traefik.prefer_wildcard_cert; const domainCertResolver = resource.domainCertResolver; - const preferWildcardCert = resource.preferWildcardCert; + const preferWildcardCert = + resource.preferWildcardCert || resource.wildcard; let resolverName: string | undefined; let preferWildcard: boolean | undefined; @@ -566,7 +589,7 @@ export async function getTraefikConfig( resource.ssl ? entrypointHttps : entrypointHttp ], service: maintenanceServiceName, - rule: `Host(\`${fullDomain}\`) && (PathPrefix(\`/_next\`) || PathRegexp(\`^/__nextjs*\`))`, + rule: `${rule} && (PathPrefix(\`/_next\`) || PathRegexp(\`^/__nextjs*\`))`, priority: 2001, ...(resource.ssl ? { tls } : {}) }; @@ -953,22 +976,17 @@ export async function getTraefikConfig( }; // Middleware that rewrites any path to /maintenance-screen - config_output.http.middlewares[ - siteResourceRewriteMiddlewareName - ] = { - replacePathRegex: { - regex: "^/(.*)", - replacement: "/private-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 - ], + config_output.http.routers[`${siteResourceRouterName}-redirect`] = { + entryPoints: [config.getRawConfig().traefik.http_entrypoint], middlewares: [redirectHttpsMiddlewareName], service: siteResourceServiceName, rule: `Host(\`${fullDomain}\`)`, @@ -977,9 +995,7 @@ export async function getTraefikConfig( // Determine TLS / cert-resolver configuration let tls: any = {}; - if ( - !privateConfig.getRawPrivateConfig().flags.use_pangolin_dns - ) { + if (!privateConfig.getRawPrivateConfig().flags.use_pangolin_dns) { const domainParts = fullDomain.split("."); const wildCard = domainParts.length <= 2 @@ -1012,9 +1028,7 @@ export async function getTraefikConfig( // HTTPS router - presence of this entry triggers cert generation config_output.http.routers[siteResourceRouterName] = { - entryPoints: [ - config.getRawConfig().traefik.https_entrypoint - ], + entryPoints: [config.getRawConfig().traefik.https_entrypoint], service: siteResourceServiceName, middlewares: [siteResourceRewriteMiddlewareName], rule: `Host(\`${fullDomain}\`)`, @@ -1024,9 +1038,7 @@ export async function getTraefikConfig( // Assets bypass router - lets Next.js static files load without rewrite config_output.http.routers[`${siteResourceRouterName}-assets`] = { - entryPoints: [ - config.getRawConfig().traefik.https_entrypoint - ], + entryPoints: [config.getRawConfig().traefik.https_entrypoint], service: siteResourceServiceName, rule: `Host(\`${fullDomain}\`) && (PathPrefix(\`/_next\`) || PathRegexp(\`^/__nextjs*\`))`, priority: 101, diff --git a/server/private/routers/alertEvents/triggerHealthCheckAlert.ts b/server/private/routers/alertEvents/triggerHealthCheckAlert.ts index 0590c2bcd..530557463 100644 --- a/server/private/routers/alertEvents/triggerHealthCheckAlert.ts +++ b/server/private/routers/alertEvents/triggerHealthCheckAlert.ts @@ -14,7 +14,7 @@ import { Request, Response, NextFunction } from "express"; import { z } from "zod"; import { db } from "@server/db"; -import { targetHealthCheck, statusHistory } from "@server/db"; +import { targetHealthCheck } from "@server/db"; import response from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; import createHttpError from "http-errors"; diff --git a/server/private/routers/alertEvents/triggerResourceAlert.ts b/server/private/routers/alertEvents/triggerResourceAlert.ts index 42e63b288..afda63e9a 100644 --- a/server/private/routers/alertEvents/triggerResourceAlert.ts +++ b/server/private/routers/alertEvents/triggerResourceAlert.ts @@ -14,7 +14,7 @@ import { Request, Response, NextFunction } from "express"; import { z } from "zod"; import { db } from "@server/db"; -import { resources, statusHistory } from "@server/db"; +import { resources } from "@server/db"; import response from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; import createHttpError from "http-errors"; @@ -24,7 +24,7 @@ import { eq, and } from "drizzle-orm"; import { fireResourceHealthyAlert, fireResourceUnhealthyAlert, - fireResourceToggleAlert + fireResourceDegradedAlert } from "#private/lib/alerts/events/resourceEvents"; const paramsSchema = z.strictObject({ @@ -33,7 +33,12 @@ const paramsSchema = z.strictObject({ }); const bodySchema = z.strictObject({ - eventType: z.enum(["resource_healthy", "resource_unhealthy", "resource_toggle"]) + eventType: z.enum([ + "resource_healthy", + "resource_unhealthy", + "resource_degraded", + "resource_toggle" + ]) }); export type TriggerResourceAlertResponse = { @@ -101,8 +106,8 @@ export async function triggerResourceAlert( resourceId, resource.name ?? undefined ); - } else { - await fireResourceToggleAlert( + } else if (eventType === "resource_degraded") { + await fireResourceDegradedAlert( orgId, resourceId, resource.name ?? undefined diff --git a/server/private/routers/alertEvents/triggerSiteAlert.ts b/server/private/routers/alertEvents/triggerSiteAlert.ts index a7fa0cafc..25b14acb9 100644 --- a/server/private/routers/alertEvents/triggerSiteAlert.ts +++ b/server/private/routers/alertEvents/triggerSiteAlert.ts @@ -14,7 +14,7 @@ import { Request, Response, NextFunction } from "express"; import { z } from "zod"; import { db } from "@server/db"; -import { sites, statusHistory } from "@server/db"; +import { sites } from "@server/db"; import response from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; import createHttpError from "http-errors"; diff --git a/server/private/routers/alertRule/createAlertRule.ts b/server/private/routers/alertRule/createAlertRule.ts index ceaacf73c..f9b84ebab 100644 --- a/server/private/routers/alertRule/createAlertRule.ts +++ b/server/private/routers/alertRule/createAlertRule.ts @@ -33,7 +33,11 @@ import { encrypt } from "@server/lib/crypto"; import config from "@server/lib/config"; import { CreateAlertRuleResponse } from "@server/routers/alertRule/types"; -export const SITE_EVENT_TYPES = ["site_online", "site_offline", "site_toggle"] as const; +export const SITE_EVENT_TYPES = [ + "site_online", + "site_offline", + "site_toggle" +] as const; export const HC_EVENT_TYPES = [ "health_check_healthy", "health_check_unhealthy", @@ -42,6 +46,7 @@ export const HC_EVENT_TYPES = [ export const RESOURCE_EVENT_TYPES = [ "resource_healthy", "resource_unhealthy", + "resource_degraded", "resource_toggle" ] as const; @@ -92,19 +97,24 @@ const bodySchema = z const isHcEvent = (HC_EVENT_TYPES as readonly string[]).includes( val.eventType ); - const isResourceEvent = (RESOURCE_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", + 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) { + if ( + isHcEvent && + !val.allHealthChecks && + val.healthCheckIds.length === 0 + ) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: @@ -129,10 +139,15 @@ const bodySchema = z }); } - if (isResourceEvent && !val.allResources && val.resourceIds.length === 0) { + 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", + message: + "At least one resourceId is required for resource event types when allResources is false", path: ["resourceIds"] }); } @@ -148,7 +163,8 @@ const bodySchema = z if (isResourceEvent && val.healthCheckIds.length > 0) { ctx.addIssue({ code: z.ZodIssueCode.custom, - message: "healthCheckIds must not be set for resource event types", + message: + "healthCheckIds must not be set for resource event types", path: ["healthCheckIds"] }); } @@ -164,7 +180,8 @@ const bodySchema = z if (isHcEvent && val.resourceIds.length > 0) { ctx.addIssue({ code: z.ZodIssueCode.custom, - message: "resourceIds must not be set for health check event types", + message: + "resourceIds must not be set for health check event types", path: ["resourceIds"] }); } @@ -284,9 +301,7 @@ export async function createAlertRule( // 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; + userIds.length > 0 || roleIds.length > 0 || emails.length > 0; if (hasRecipients) { const [emailActionRow] = await db diff --git a/server/private/routers/alertRule/listAlertRules.ts b/server/private/routers/alertRule/listAlertRules.ts index a31a4d119..9684b88a4 100644 --- a/server/private/routers/alertRule/listAlertRules.ts +++ b/server/private/routers/alertRule/listAlertRules.ts @@ -76,6 +76,7 @@ const SITE_ALERT_EVENT_TYPES = [ const RESOURCE_ALERT_EVENT_TYPES = [ "resource_healthy", "resource_unhealthy", + "resource_degraded", "resource_toggle" ] as const; diff --git a/server/private/routers/billing/featureLifecycle.ts b/server/private/routers/billing/featureLifecycle.ts index bc37271c0..6cb98ba5d 100644 --- a/server/private/routers/billing/featureLifecycle.ts +++ b/server/private/routers/billing/featureLifecycle.ts @@ -30,8 +30,10 @@ import { userOrgRoles, siteProvisioningKeyOrg, siteProvisioningKeys, + alertRules, + targetHealthCheck } from "@server/db"; -import { and, eq } from "drizzle-orm"; +import { and, eq, isNull } from "drizzle-orm"; /** * Get the maximum allowed retention days for a given tier @@ -318,6 +320,14 @@ async function disableFeature( await disableSiteProvisioningKeys(orgId); break; + case TierFeature.AlertingRules: + await disableAlertingRules(orgId); + break; + + case TierFeature.StandaloneHealthChecks: + await disableStandaloneHealthChecks(orgId); + break; + default: logger.warn( `Unknown feature ${feature} for org ${orgId}, skipping` @@ -360,8 +370,7 @@ async function disableFullRbac(orgId: string): Promise { async function disableSiteProvisioningKeys(orgId: string): Promise { const rows = await db .select({ - siteProvisioningKeyId: - siteProvisioningKeyOrg.siteProvisioningKeyId + siteProvisioningKeyId: siteProvisioningKeyOrg.siteProvisioningKeyId }) .from(siteProvisioningKeyOrg) .where(eq(siteProvisioningKeyOrg.orgId, orgId)); @@ -525,6 +534,29 @@ async function disablePasswordExpirationPolicies(orgId: string): Promise { logger.info(`Disabled password expiration policies for org ${orgId}`); } +async function disableAlertingRules(orgId: string): Promise { + await db + .update(alertRules) + .set({ enabled: false }) + .where(eq(alertRules.orgId, orgId)); + + logger.info(`Disabled all alert rules for org ${orgId}`); +} + +async function disableStandaloneHealthChecks(orgId: string): Promise { + await db + .update(targetHealthCheck) + .set({ hcEnabled: false }) + .where( + and( + eq(targetHealthCheck.orgId, orgId), + isNull(targetHealthCheck.targetId) + ) + ); + + logger.info(`Disabled standalone health checks for org ${orgId}`); +} + async function disableAutoProvisioning(orgId: string): Promise { // Get all IDP IDs for this org through the idpOrg join table const orgIdps = await db diff --git a/server/private/routers/billing/hooks/handleSubscriptionCreated.ts b/server/private/routers/billing/hooks/handleSubscriptionCreated.ts index c7a47d1b7..947f28c14 100644 --- a/server/private/routers/billing/hooks/handleSubscriptionCreated.ts +++ b/server/private/routers/billing/hooks/handleSubscriptionCreated.ts @@ -174,6 +174,19 @@ export async function handleSubscriptionCreated( // TODO: update user in Sendy } } + + // delete the trial subscrition if we have one + await db + .delete(subscriptions) + .where( + and( + eq( + subscriptions.customerId, + subscription.customer as string + ), + eq(subscriptions.trial, true) + ) + ); } else if (type === "license") { logger.debug( `License subscription created for org ${customer.orgId}, no lifecycle handling needed.` diff --git a/server/private/routers/certificates/createCertificate.ts b/server/private/routers/certificates/createCertificate.ts index 4f7bb7fe8..60ca2072a 100644 --- a/server/private/routers/certificates/createCertificate.ts +++ b/server/private/routers/certificates/createCertificate.ts @@ -37,18 +37,25 @@ export async function createCertificate( } let existing: Certificate[] = []; - if (domainRecord.type == "ns") { + if (domainRecord.type == "ns" || domainRecord.type == "wildcard") { const domainLevelDown = domain.split(".").slice(1).join("."); + const wildcardPrefixed = `*.${domainLevelDown}`; + existing = await trx .select() .from(certificates) .where( and( eq(certificates.domainId, domainId), - eq(certificates.wildcard, true), // only NS domains can have wildcard certs or( eq(certificates.domain, domain), - eq(certificates.domain, domainLevelDown) + and( + eq(certificates.wildcard, true), + or( + eq(certificates.domain, domainLevelDown), + eq(certificates.domain, wildcardPrefixed) + ) + ) ) ) ); @@ -70,11 +77,28 @@ export async function createCertificate( return; } + let domainToWrite = domain; + if ( + domainRecord.type == "wildcard" && + domainRecord.preferWildcardCert && + !domain.startsWith("*.") + ) { + // in this case traefik is going to generate a domain one level down so we need to store it that way + const parts = domain.split("."); + if (parts.length > 2) { + domainToWrite = parts.slice(1).join("."); + domainToWrite = `*.${domainToWrite}`; + } + } + // No cert found, create a new one in pending state await trx.insert(certificates).values({ - domain, + domain: domainToWrite, domainId, - wildcard: domainRecord.type == "ns", // we can only create wildcard certs for NS domains + wildcard: + domainRecord.type == "ns" || + (domainRecord.type == "wildcard" && + domainRecord.preferWildcardCert), // we can only create wildcard certs for NS domains status: "pending", updatedAt: Math.floor(Date.now() / 1000), createdAt: Math.floor(Date.now() / 1000) diff --git a/server/private/routers/certificates/getCertificate.ts b/server/private/routers/certificates/getCertificate.ts index 9e434b3e0..fca53e9bb 100644 --- a/server/private/routers/certificates/getCertificate.ts +++ b/server/private/routers/certificates/getCertificate.ts @@ -40,8 +40,10 @@ async function query(domainId: string, domain: string) { throw new Error(`Domain with ID ${domainId} not found`); } + const domainType = domainRecord.type; + let existing: any[] = []; - if (domainRecord.type == "ns" || domainRecord.type == "wildcard") { // the manual "wildcard" domains can have wildcard certs + if (domainRecord.type == "ns" || domainRecord.type == "wildcard") { const domainLevelDown = domain.split(".").slice(1).join("."); const wildcardPrefixed = `*.${domainLevelDown}`; @@ -62,11 +64,15 @@ async function query(domainId: string, domain: string) { .where( and( eq(certificates.domainId, domainId), - eq(certificates.wildcard, true), // only NS domains can have wildcard certs or( eq(certificates.domain, domain), - eq(certificates.domain, domainLevelDown), - eq(certificates.domain, wildcardPrefixed) + and( + eq(certificates.wildcard, true), + or( + eq(certificates.domain, domainLevelDown), + eq(certificates.domain, wildcardPrefixed) + ) + ) ) ) ); @@ -94,7 +100,7 @@ async function query(domainId: string, domain: string) { ); } - return existing.length > 0 ? existing[0] : null; + return existing.length > 0 ? { ...existing[0], domainType } : null; } registry.registerPath({ diff --git a/server/private/routers/certificates/index.ts b/server/private/routers/certificates/index.ts index 1ced04c31..18b942d5c 100644 --- a/server/private/routers/certificates/index.ts +++ b/server/private/routers/certificates/index.ts @@ -13,3 +13,4 @@ export * from "./getCertificate"; export * from "./restartCertificate"; +export * from "./syncCertToNewts"; diff --git a/server/private/routers/certificates/syncCertToNewts.ts b/server/private/routers/certificates/syncCertToNewts.ts new file mode 100644 index 000000000..ac6089acb --- /dev/null +++ b/server/private/routers/certificates/syncCertToNewts.ts @@ -0,0 +1,68 @@ +/* + * 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 { pushCertUpdateToAffectedNewts } from "#private/lib/acmeCertSync"; +import logger from "@server/logger"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import { fromError } from "zod-validation-error"; + +const bodySchema = z.object({ + domain: z.string().min(1), + domainId: z.string().nullable().optional().default(null) +}); + +export async function syncCertToNewts( + req: Request, + res: Response, + next: NextFunction +): Promise { + const parsed = bodySchema.safeParse(req.body); + if (!parsed.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsed.error).toString() + ) + ); + } + + const { domain, domainId } = parsed.data; + + logger.debug( + `syncCertToNewts: received request to push cert update for domain "${domain}" (domainId: ${domainId ?? "none"})` + ); + + try { + await pushCertUpdateToAffectedNewts(domain, domainId, null, null); + + res.status(HttpCode.OK).json({ + data: null, + success: true, + error: false, + message: `Certificate update pushed to affected newts for domain "${domain}"` + }); + } catch (err) { + logger.error( + `syncCertToNewts: error pushing cert update for domain "${domain}": ${err}` + ); + return next( + createHttpError( + HttpCode.INTERNAL_SERVER_ERROR, + "Failed to push certificate update to affected newts" + ) + ); + } +} \ No newline at end of file diff --git a/server/private/routers/external.ts b/server/private/routers/external.ts index 159ee2449..a2667daa1 100644 --- a/server/private/routers/external.ts +++ b/server/private/routers/external.ts @@ -165,7 +165,6 @@ authenticated.get( authenticated.get( "/org/:orgId/certificate/:domainId/:domain", - verifyValidLicense, verifyOrgAccess, verifyCertificateAccess, verifyUserHasAction(ActionsEnum.getCertificate), diff --git a/server/private/routers/healthChecks/createHealthCheck.ts b/server/private/routers/healthChecks/createHealthCheck.ts index 374ec4ba4..ead58e996 100644 --- a/server/private/routers/healthChecks/createHealthCheck.ts +++ b/server/private/routers/healthChecks/createHealthCheck.ts @@ -22,6 +22,7 @@ import logger from "@server/logger"; import { fromError } from "zod-validation-error"; import { OpenAPITags, registry } from "@server/openApi"; import { addStandaloneHealthCheck } from "@server/routers/newt/targets"; +import { fireHealthCheckUnhealthyAlert } from "#private/lib/alerts"; const paramsSchema = z.strictObject({ orgId: z.string().nonempty() @@ -141,10 +142,20 @@ export async function createHealthCheck( hcStatus: hcStatus ?? null, hcTlsServerName: hcTlsServerName ?? null, hcHealthyThreshold, - hcUnhealthyThreshold + hcUnhealthyThreshold, + hcHealth: "unhealthy" }) .returning(); + await fireHealthCheckUnhealthyAlert( + record.orgId, + record.targetHealthCheckId, + record.name || "", + undefined, + undefined, + false // dont send the alert because we just want to create the alert, not notify users yet + ); + // Push health check to newt if the site is a newt site if (siteId) { const [site] = await db diff --git a/server/private/routers/healthChecks/getStatusHistory.ts b/server/private/routers/healthChecks/getStatusHistory.ts index 2fa596950..51a59e2e1 100644 --- a/server/private/routers/healthChecks/getStatusHistory.ts +++ b/server/private/routers/healthChecks/getStatusHistory.ts @@ -13,15 +13,13 @@ 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, + getCachedStatusHistory, statusHistoryQuerySchema, StatusHistoryResponse } from "@server/lib/statusHistory"; @@ -55,43 +53,14 @@ export async function getHealthCheckStatusHistory( ); } - const entityType = "healthCheck"; + const entityType = "health_check"; 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; + const data = await getCachedStatusHistory(entityType, entityId, days); return response(res, { - data: { - entityType, - entityId, - days: buckets, - overallUptimePercent: Math.round(overallUptime * 100) / 100, - totalDowntimeSeconds: totalDowntime - }, + data, success: true, error: false, message: "Status history retrieved successfully", @@ -103,4 +72,4 @@ export async function getHealthCheckStatusHistory( createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") ); } -} +} \ No newline at end of file diff --git a/server/private/routers/healthChecks/updateHealthCheck.ts b/server/private/routers/healthChecks/updateHealthCheck.ts index 713bf1e03..8afeca6a4 100644 --- a/server/private/routers/healthChecks/updateHealthCheck.ts +++ b/server/private/routers/healthChecks/updateHealthCheck.ts @@ -22,6 +22,7 @@ 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"; +import { fireHealthCheckUnhealthyAlert, fireHealthCheckUnknownAlert, fireHealthCheckHealthyAlert } from "#private/lib/alerts"; const paramsSchema = z .object({ @@ -166,6 +167,17 @@ export async function updateHealthCheck( const updateData: Record = {}; + const [existingHealthCheck] = await db + .select() + .from(targetHealthCheck) + .where( + and( + eq(targetHealthCheck.targetHealthCheckId, healthCheckId), + eq(targetHealthCheck.orgId, orgId) + ) + ) + .limit(1); + if (name !== undefined) updateData.name = name; if (siteId !== undefined) updateData.siteId = siteId; if (hcEnabled !== undefined) updateData.hcEnabled = hcEnabled; @@ -190,6 +202,26 @@ export async function updateHealthCheck( if (hcUnhealthyThreshold !== undefined) updateData.hcUnhealthyThreshold = hcUnhealthyThreshold; + const hcEnabledTurnedOn = + parsedBody.data.hcEnabled === true && + existingHealthCheck.hcEnabled === false; + + let hcHealthValue: "unknown" | "healthy" | "unhealthy" | undefined; + if ( + parsedBody.data.hcEnabled === false || + parsedBody.data.hcEnabled === null + ) { + hcHealthValue = "unknown"; + } else if (hcEnabledTurnedOn) { + hcHealthValue = "unhealthy"; + } else { + hcHealthValue = undefined; + } + + if (hcHealthValue) { + updateData.hcHealth = hcHealthValue; + } + const [updated] = await db .update(targetHealthCheck) .set(updateData) @@ -202,6 +234,37 @@ export async function updateHealthCheck( ) .returning(); + if (updated.hcHealth === "unhealthy" && existingHealthCheck.hcHealth !== "unhealthy") { + await fireHealthCheckUnhealthyAlert( + updated.orgId, + updated.targetHealthCheckId, + updated.name || "", + undefined, + undefined, + false // dont send the alert because we just want to create the alert, not notify users yet + ); + } else if (updated.hcHealth === "unknown" && existingHealthCheck.hcHealth !== "unknown") { + // if the health is unknown, we want to fire an alert to notify users to enable health checks + await fireHealthCheckUnknownAlert( + updated.orgId, + updated.targetHealthCheckId, + updated.name, + undefined, + undefined, + false // dont send the alert because we just want to create the alert, not notify users yet + ); + } else if (updated.hcHealth === "healthy" && existingHealthCheck.hcHealth !== "healthy") { + await fireHealthCheckHealthyAlert( + updated.orgId, + updated.targetHealthCheckId, + updated.name, + undefined, + undefined, + false // dont send the alert because we just want to create the alert, not notify users yet + ); + } + + // Push updated health check to newt if the site is a newt site const [newt] = await db .select() diff --git a/server/private/routers/hybrid.ts b/server/private/routers/hybrid.ts index b3ef792d9..98e7ff671 100644 --- a/server/private/routers/hybrid.ts +++ b/server/private/routers/hybrid.ts @@ -50,7 +50,7 @@ import { userOrgRoles, roles } from "@server/db"; -import { eq, and, inArray, isNotNull, ne } from "drizzle-orm"; +import { eq, and, inArray, isNotNull, ne, or, sql } from "drizzle-orm"; import { response } from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; import { NextFunction, Request, Response } from "express"; @@ -492,7 +492,15 @@ hybridRouter.get( ); } - const [result] = await db + // Build wildcard domain candidates for the requested domain. + // e.g. "me.example.test.com" -> ["*.example.test.com", "*.test.com"] + const domainParts = domain.split("."); + const wildcardCandidates: string[] = []; + for (let i = 1; i < domainParts.length; i++) { + wildcardCandidates.push(`*.${domainParts.slice(i).join(".")}`); + } + + const potentialResults = await db .select() .from(resources) .leftJoin( @@ -515,10 +523,28 @@ hybridRouter.get( ) ) .innerJoin(orgs, eq(orgs.orgId, resources.orgId)) - .where(eq(resources.fullDomain, domain)) - .limit(1); + .where( + or( + // Exact match + eq(resources.fullDomain, domain), + // Wildcard match + wildcardCandidates.length > 0 + ? and( + eq(resources.wildcard, true), + inArray(resources.fullDomain, wildcardCandidates) + ) + : sql`false` + ) + ); + + // Prefer exact match over wildcard match + const exactMatch = potentialResults.find( + (r) => r.resources?.fullDomain === domain + ); + const result = exactMatch ?? potentialResults[0]; if ( + result && await checkExitNodeOrg( remoteExitNode.exitNodeId, result.resources.orgId diff --git a/server/private/routers/integration.ts b/server/private/routers/integration.ts index ed97b3751..820a843f0 100644 --- a/server/private/routers/integration.ts +++ b/server/private/routers/integration.ts @@ -15,6 +15,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 * as certificates from "#private/routers/certificates"; import { verifyApiKeyHasAction, @@ -37,46 +38,48 @@ import { } from "@server/routers/integration"; import { logActionAudit } from "#private/middlewares"; import { tierMatrix } from "@server/lib/billing/tierMatrix"; +import { build } from "@server/build"; export const unauthenticated = ua; export const authenticated = a; -authenticated.post( - "/org/:orgId/site/:siteId/trigger-alert", - verifyApiKeyIsRoot, - verifyApiKeyHasAction(ActionsEnum.triggerSiteAlert), - alertEvents.triggerSiteAlert -); +if (build == "saas") { + authenticated.post( + "/org/:orgId/site/:siteId/trigger-alert", + verifyApiKeyIsRoot, + alertEvents.triggerSiteAlert + ); -authenticated.post( - "/org/:orgId/resource/:resourceId/trigger-alert", - verifyApiKeyIsRoot, - verifyApiKeyHasAction(ActionsEnum.triggerResourceAlert), - alertEvents.triggerResourceAlert -); + authenticated.post( + "/org/:orgId/resource/:resourceId/trigger-alert", + verifyApiKeyIsRoot, + alertEvents.triggerResourceAlert + ); -authenticated.post( - "/org/:orgId/health-check/:healthCheckId/trigger-alert", - verifyApiKeyIsRoot, - verifyApiKeyHasAction(ActionsEnum.triggerHealthCheckAlert), - alertEvents.triggerHealthCheckAlert -); + authenticated.post( + "/org/:orgId/health-check/:healthCheckId/trigger-alert", + verifyApiKeyIsRoot, + alertEvents.triggerHealthCheckAlert + ); -authenticated.post( - `/org/:orgId/send-usage-notification`, - verifyApiKeyIsRoot, // We are the only ones who can use root key so its fine - verifyApiKeyHasAction(ActionsEnum.sendUsageNotification), - logActionAudit(ActionsEnum.sendUsageNotification), - org.sendUsageNotification -); + authenticated.post( + "/cert/sync-to-newts", + verifyApiKeyIsRoot, + certificates.syncCertToNewts + ); -authenticated.post( - `/org/:orgId/send-trial-notification`, - verifyApiKeyIsRoot, - verifyApiKeyHasAction(ActionsEnum.sendTrialNotification), - logActionAudit(ActionsEnum.sendTrialNotification), - org.sendTrialNotification -); + authenticated.post( + `/org/:orgId/send-usage-notification`, + verifyApiKeyIsRoot, // We are the only ones who can use root key so its fine + org.sendUsageNotification + ); + + authenticated.post( + `/org/:orgId/send-trial-notification`, + verifyApiKeyIsRoot, + org.sendTrialNotification + ); +} authenticated.delete( "/idp/:idpId", diff --git a/server/private/routers/ssh/signSshKey.ts b/server/private/routers/ssh/signSshKey.ts index 82044c0ad..e29493a01 100644 --- a/server/private/routers/ssh/signSshKey.ts +++ b/server/private/routers/ssh/signSshKey.ts @@ -368,8 +368,8 @@ export async function signSshKey( const parsedSudoCommands: string[] = []; const parsedGroupsSet = new Set(); let homedir: boolean | null = null; - const sudoModeOrder = { none: 0, commands: 1, all: 2 }; - let sudoMode: "none" | "commands" | "all" = "none"; + const sudoModeOrder = { none: 0, commands: 1, full: 2 }; + let sudoMode: "none" | "commands" | "full" = "none"; for (const roleRow of roleRows) { try { const cmds = JSON.parse(roleRow?.sshSudoCommands ?? "[]"); @@ -386,7 +386,7 @@ export async function signSshKey( if (roleRow?.sshCreateHomeDir === true) homedir = true; const m = roleRow?.sshSudoMode ?? "none"; if (sudoModeOrder[m as keyof typeof sudoModeOrder] > sudoModeOrder[sudoMode]) { - sudoMode = m as "none" | "commands" | "all"; + sudoMode = m as "none" | "commands" | "full"; } } const parsedGroups = Array.from(parsedGroupsSet); diff --git a/server/routers/alertRule/types.ts b/server/routers/alertRule/types.ts index a9e66350e..e3f92591d 100644 --- a/server/routers/alertRule/types.ts +++ b/server/routers/alertRule/types.ts @@ -37,6 +37,7 @@ export type GetAlertRuleResponse = { | "health_check_toggle" | "resource_healthy" | "resource_unhealthy" + | "resource_degraded" | "resource_toggle"; enabled: boolean; cooldownSeconds: number; @@ -94,6 +95,7 @@ export type AlertEventType = | "health_check_toggle" | "resource_healthy" | "resource_unhealthy" + | "resource_degraded" | "resource_toggle"; // --------------------------------------------------------------------------- diff --git a/server/routers/badger/exchangeSession.ts b/server/routers/badger/exchangeSession.ts index bde5518b8..08987961d 100644 --- a/server/routers/badger/exchangeSession.ts +++ b/server/routers/badger/exchangeSession.ts @@ -6,7 +6,7 @@ import { fromError } from "zod-validation-error"; import logger from "@server/logger"; import { resourceAccessToken, resources, sessions } from "@server/db"; import { db } from "@server/db"; -import { eq } from "drizzle-orm"; +import { and, eq, inArray, or, sql } from "drizzle-orm"; import { createResourceSession, serializeResourceSessionCookie, @@ -65,11 +65,31 @@ export async function exchangeSession( const clientIp = requestIp ? stripPortFromHost(requestIp) : undefined; - const [resource] = await db + const parts = cleanHost.split("."); + const wildcardCandidates: string[] = []; + for (let i = 1; i < parts.length; i++) { + wildcardCandidates.push(`*.${parts.slice(i).join(".")}`); + } + + const potentialResources = await db .select() .from(resources) - .where(eq(resources.fullDomain, cleanHost)) - .limit(1); + .where( + or( + eq(resources.fullDomain, cleanHost), + wildcardCandidates.length > 0 + ? and( + eq(resources.wildcard, true), + inArray(resources.fullDomain, wildcardCandidates) + ) + : sql`false` + ) + ); + + const exactMatch = potentialResources.find( + (r) => r.fullDomain === cleanHost + ); + const resource = exactMatch ?? potentialResources[0]; if (!resource) { return next( @@ -178,7 +198,7 @@ export async function exchangeSession( const cookieName = `${config.getRawConfig().server.session_cookie_name}`; const cookie = serializeResourceSessionCookie( cookieName, - resource.fullDomain!, + cleanHost, token, !resource.ssl, expiresAt ? new Date(expiresAt) : undefined diff --git a/server/routers/certificates/types.ts b/server/routers/certificates/types.ts index bca9412c4..e6aeecdf8 100644 --- a/server/routers/certificates/types.ts +++ b/server/routers/certificates/types.ts @@ -3,6 +3,7 @@ export type GetCertificateResponse = { domain: string; domainId: string; wildcard: boolean; + domainType: string; status: string; // pending, requested, valid, expired, failed expiresAt: string | null; lastRenewalAttempt: Date | null; @@ -10,4 +11,4 @@ export type GetCertificateResponse = { updatedAt: number; errorMessage?: string | null; renewalCount: number; -}; +}; \ No newline at end of file diff --git a/server/routers/client/getClient.ts b/server/routers/client/getClient.ts index a05fdef42..c97612b07 100644 --- a/server/routers/client/getClient.ts +++ b/server/routers/client/getClient.ts @@ -1,8 +1,8 @@ import { Request, Response, NextFunction } from "express"; import { z } from "zod"; -import { db, olms, users } from "@server/db"; +import { db, idp, idpOidcConfig, olms, users } from "@server/db"; import { clients, currentFingerprint } from "@server/db"; -import { eq, and } from "drizzle-orm"; +import { and, eq } from "drizzle-orm"; import response from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; import createHttpError from "http-errors"; @@ -236,6 +236,9 @@ export type GetClientResponse = NonNullable< lastSeen: number | null; } | null; posture: PostureData | null; + userType: string | null; + idpName: string | null; + idpVariant: string | null; }; registry.registerPath({ @@ -337,6 +340,30 @@ export async function getClient( : maskPostureDataWithPlaceholder(rawPosture) : null; + let userType: string | null = null; + let idpName: string | null = null; + let idpVariant: string | null = null; + + if (client.clients.userId) { + const [idpRow] = await db + .select({ + userType: users.type, + idpName: idp.name, + idpVariant: idpOidcConfig.variant + }) + .from(users) + .leftJoin(idp, eq(users.idpId, idp.idpId)) + .leftJoin(idpOidcConfig, eq(idpOidcConfig.idpId, idp.idpId)) + .where(eq(users.userId, client.clients.userId)) + .limit(1); + + if (idpRow) { + userType = idpRow.userType; + idpName = idpRow.idpName; + idpVariant = idpRow.idpVariant; + } + } + const data: GetClientResponse = { ...client.clients, name: clientName, @@ -347,7 +374,10 @@ export async function getClient( userName: client.user?.name ?? null, userUsername: client.user?.username ?? null, fingerprint: fingerprintData, - posture: postureData + posture: postureData, + userType, + idpName, + idpVariant }; return response(res, { diff --git a/server/routers/client/listUserDevices.ts b/server/routers/client/listUserDevices.ts index d793faf09..567eb0d6b 100644 --- a/server/routers/client/listUserDevices.ts +++ b/server/routers/client/listUserDevices.ts @@ -3,6 +3,8 @@ import { clients, currentFingerprint, db, + idp, + idpOidcConfig, olms, orgs, roleClients, @@ -165,6 +167,9 @@ function queryUserDevicesBase() { userId: clients.userId, username: users.username, userEmail: users.email, + userType: users.type, + idpName: idp.name, + idpVariant: idpOidcConfig.variant, niceId: clients.niceId, agent: olms.agent, approvalState: clients.approvalState, @@ -184,6 +189,8 @@ function queryUserDevicesBase() { .leftJoin(orgs, eq(clients.orgId, orgs.orgId)) .leftJoin(olms, eq(clients.clientId, olms.clientId)) .leftJoin(users, eq(clients.userId, users.userId)) + .leftJoin(idp, eq(users.idpId, idp.idpId)) + .leftJoin(idpOidcConfig, eq(idpOidcConfig.idpId, idp.idpId)) .leftJoin(currentFingerprint, eq(olms.olmId, currentFingerprint.olmId)); } diff --git a/server/routers/newt/handleNewtDisconnectingMessage.ts b/server/routers/newt/handleNewtDisconnectingMessage.ts index 15c7d3662..a05d410c8 100644 --- a/server/routers/newt/handleNewtDisconnectingMessage.ts +++ b/server/routers/newt/handleNewtDisconnectingMessage.ts @@ -6,7 +6,7 @@ import { } from "@server/db"; import { eq } from "drizzle-orm"; import logger from "@server/logger"; -import { fireSiteOfflineAlert } from "@server/lib/alerts"; +import { fireSiteOfflineAlert } from "#dynamic/lib/alerts"; /** * Handles disconnecting messages from sites to show disconnected in the ui diff --git a/server/routers/newt/handleSocketMessages.ts b/server/routers/newt/handleSocketMessages.ts index 383ab5541..5d5497ee1 100644 --- a/server/routers/newt/handleSocketMessages.ts +++ b/server/routers/newt/handleSocketMessages.ts @@ -8,26 +8,26 @@ export const handleDockerStatusMessage: MessageHandler = async (context) => { const { message, client, sendToClient } = context; const newt = client as Newt; - logger.info("Handling Docker socket check response"); + logger.debug("Handling Docker socket check response"); if (!newt) { logger.warn("Newt not found"); return; } - logger.info(`Newt ID: ${newt.newtId}, Site ID: ${newt.siteId}`); + logger.debug(`Newt ID: ${newt.newtId}, Site ID: ${newt.siteId}`); const { available, socketPath } = message.data; - logger.info( + logger.debug( `Docker socket availability for Newt ${newt.newtId}: available=${available}, socketPath=${socketPath}` ); if (available) { - logger.info(`Newt ${newt.newtId} has Docker socket access`); + logger.debug(`Newt ${newt.newtId} has Docker socket access`); await cache.set(`${newt.newtId}:socketPath`, socketPath, 0); await cache.set(`${newt.newtId}:isAvailable`, available, 0); } else { - logger.warn(`Newt ${newt.newtId} does not have Docker socket access`); + logger.debug(`Newt ${newt.newtId} does not have Docker socket access`); } return; @@ -39,28 +39,28 @@ export const handleDockerContainersMessage: MessageHandler = async ( const { message, client, sendToClient } = context; const newt = client as Newt; - logger.info("Handling Docker containers response"); + logger.debug("Handling Docker containers response"); if (!newt) { logger.warn("Newt not found"); return; } - logger.info(`Newt ID: ${newt.newtId}, Site ID: ${newt.siteId}`); + logger.debug(`Newt ID: ${newt.newtId}, Site ID: ${newt.siteId}`); const { containers } = message.data; - logger.info( + logger.debug( `Docker containers for Newt ${newt.newtId}: ${containers ? containers.length : 0}` ); if (containers && containers.length > 0) { await cache.set(`${newt.newtId}:dockerContainers`, containers, 0); } else { - logger.warn(`Newt ${newt.newtId} does not have Docker containers`); + logger.debug(`Newt ${newt.newtId} does not have Docker containers`); } if (!newt.siteId) { - logger.warn("Newt has no site!"); + logger.debug("Newt has no site!"); return; } diff --git a/server/routers/newt/offlineChecker.ts b/server/routers/newt/offlineChecker.ts index 1dc51d5da..6ff43688a 100644 --- a/server/routers/newt/offlineChecker.ts +++ b/server/routers/newt/offlineChecker.ts @@ -1,10 +1,7 @@ import { db, newts, - sites, - targetHealthCheck, - targets, - statusHistory + sites } from "@server/db"; import { hasActiveConnections } from "#dynamic/routers/ws"; import { eq, lt, isNull, and, or, ne, not, inArray } from "drizzle-orm"; diff --git a/server/routers/newt/registerNewt.ts b/server/routers/newt/registerNewt.ts index cc53e48df..b79118b58 100644 --- a/server/routers/newt/registerNewt.ts +++ b/server/routers/newt/registerNewt.ts @@ -1,6 +1,6 @@ import { Request, Response, NextFunction } from "express"; import { z } from "zod"; -import { db } from "@server/db"; +import { db, logsDb, statusHistory } from "@server/db"; import { siteProvisioningKeys, siteProvisioningKeyOrg, @@ -84,7 +84,7 @@ export async function registerNewt( maxBatchSize: siteProvisioningKeys.maxBatchSize, numUsed: siteProvisioningKeys.numUsed, validUntil: siteProvisioningKeys.validUntil, - approveNewSites: siteProvisioningKeys.approveNewSites, + approveNewSites: siteProvisioningKeys.approveNewSites }) .from(siteProvisioningKeys) .innerJoin( @@ -125,7 +125,10 @@ export async function registerNewt( ); } - if (keyRecord.maxBatchSize && keyRecord.numUsed >= keyRecord.maxBatchSize) { + if ( + keyRecord.maxBatchSize && + keyRecord.numUsed >= keyRecord.maxBatchSize + ) { return next( createHttpError( HttpCode.UNAUTHORIZED, @@ -134,7 +137,10 @@ export async function registerNewt( ); } - if (keyRecord.validUntil && new Date(keyRecord.validUntil) < new Date()) { + if ( + keyRecord.validUntil && + new Date(keyRecord.validUntil) < new Date() + ) { return next( createHttpError( HttpCode.UNAUTHORIZED, @@ -154,7 +160,10 @@ export async function registerNewt( } if (!org.subnet) { return next( - createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "Organization subnet not found") + createHttpError( + HttpCode.INTERNAL_SERVER_ERROR, + "Organization subnet not found" + ) ); } @@ -195,7 +204,6 @@ export async function registerNewt( let newSiteId: number | undefined; await db.transaction(async (trx) => { - const newClientAddress = await getNextAvailableClientSubnet(orgId); if (!newClientAddress) { return next( @@ -219,10 +227,18 @@ export async function registerNewt( address: clientAddress, type: "newt", dockerSocketEnabled: true, - status: keyRecord.approveNewSites ? "approved" : "pending", + status: keyRecord.approveNewSites ? "approved" : "pending" }) .returning(); + await logsDb.insert(statusHistory).values({ + entityType: "site", + entityId: newSite.siteId, + orgId: orgId, + status: "offline", + timestamp: Math.floor(Date.now() / 1000) + }); + newSiteId = newSite.siteId; // Grant admin role access to the new site diff --git a/server/routers/newt/targets.ts b/server/routers/newt/targets.ts index 25b520854..ac25fb27d 100644 --- a/server/routers/newt/targets.ts +++ b/server/routers/newt/targets.ts @@ -17,47 +17,34 @@ export async function addTargets( }:${target.port}`; }); - await sendToClient( - newtId, - { - type: `newt/${protocol}/add`, - data: { - targets: payloadTargets + if (payloadTargets.length > 0) { + await sendToClient( + newtId, + { + type: `newt/${protocol}/add`, + data: { + targets: payloadTargets + } + }, + { + incrementConfigVersion: true, + compress: canCompress(version, "newt") } - }, - { incrementConfigVersion: true, compress: canCompress(version, "newt") } - ); - - // Create a map for quick lookup - const healthCheckMap = new Map(); - healthCheckData.forEach((hc) => { - if (hc.targetId !== null) { - healthCheckMap.set(hc.targetId, hc); - } - }); - - const healthCheckTargets = targets.map((target) => { - const hc = healthCheckMap.get(target.targetId); - - // If no health check data found, skip this target - if (!hc) { - logger.warn( - `No health check configuration found for target ${target.targetId}` - ); - return null; - } + ); + } + const healthCheckTargets = healthCheckData.map((hc) => { // Ensure all necessary fields are present 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` + `Skipping hc ${hc.targetHealthCheckId} due to 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` + `Skipping hc ${hc.targetHealthCheckId} due to missing HTTP health check fields` ); return null; } @@ -105,7 +92,7 @@ export async function addTargets( // Filter out any null values from health check targets const validHealthCheckTargets = healthCheckTargets.filter( - (target) => target !== null + (hc) => hc !== null ); await sendToClient( @@ -213,6 +200,7 @@ export async function removeStandaloneHealthCheck( export async function removeTargets( newtId: string, targets: Target[], + healthCheckData: TargetHealthCheck[], protocol: string, version?: string | null ) { @@ -223,19 +211,21 @@ export async function removeTargets( }:${target.port}`; }); - await sendToClient( - newtId, - { - type: `newt/${protocol}/remove`, - data: { - targets: payloadTargets - } - }, - { incrementConfigVersion: true } - ); + if (payloadTargets.length > 0) { + await sendToClient( + newtId, + { + type: `newt/${protocol}/remove`, + data: { + targets: payloadTargets + } + }, + { incrementConfigVersion: true } + ); + } - const healthCheckTargets = targets.map((target) => { - return target.targetId; + const healthCheckTargets = healthCheckData.map((hc) => { + return hc.targetHealthCheckId; }); await sendToClient( diff --git a/server/routers/resource/createResource.ts b/server/routers/resource/createResource.ts index f026166a6..f8b7551e9 100644 --- a/server/routers/resource/createResource.ts +++ b/server/routers/resource/createResource.ts @@ -17,14 +17,15 @@ import createHttpError from "http-errors"; import { eq, and } from "drizzle-orm"; import { fromError } from "zod-validation-error"; import logger from "@server/logger"; -import { subdomainSchema } from "@server/lib/schemas"; +import { subdomainSchema, wildcardSubdomainSchema } from "@server/lib/schemas"; import config from "@server/lib/config"; import { OpenAPITags, registry } from "@server/openApi"; import { build } from "@server/build"; import { createCertificate } from "#dynamic/routers/certificates/createCertificate"; import { getUniqueResourceName } from "@server/db/names"; -import { validateAndConstructDomain } from "@server/lib/domainUtils"; +import { validateAndConstructDomain, checkWildcardDomainConflict } from "@server/lib/domainUtils"; import { isSubscribed } from "#dynamic/lib/isSubscribed"; +import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed"; import { tierMatrix } from "@server/lib/billing/tierMatrix"; const createResourceParamsSchema = z.strictObject({ @@ -44,7 +45,10 @@ const createHttpResourceSchema = z .refine( (data) => { if (data.subdomain) { - return subdomainSchema.safeParse(data.subdomain).success; + return ( + subdomainSchema.safeParse(data.subdomain).success || + wildcardSubdomainSchema.safeParse(data.subdomain).success + ); } return true; }, @@ -198,6 +202,22 @@ async function createHttpResource( const subdomain = parsedBody.data.subdomain; const stickySession = parsedBody.data.stickySession; + // Wildcard subdomains are a paid feature + if (subdomain && subdomain.includes("*")) { + const isLicensed = await isLicensedOrSubscribed( + orgId, + tierMatrix.wildcardSubdomain + ); + if (!isLicensed) { + return next( + createHttpError( + HttpCode.FORBIDDEN, + "Wildcard subdomains are not supported on your current plan. Please upgrade to access this feature." + ) + ); + } + } + if (build == "saas" && !isSubscribed(orgId!, tierMatrix.domainNamespaces)) { // grandfather in existing users const lastAllowedDate = new Date("2026-04-13"); @@ -232,7 +252,7 @@ async function createHttpResource( return next(createHttpError(HttpCode.BAD_REQUEST, domainResult.error)); } - const { fullDomain, subdomain: finalSubdomain } = domainResult; + const { fullDomain, subdomain: finalSubdomain, wildcard } = domainResult; logger.debug(`Full domain: ${fullDomain}`); @@ -251,6 +271,13 @@ async function createHttpResource( ); } + const wildcardConflict = await checkWildcardDomainConflict(fullDomain); + if (wildcardConflict.conflict) { + return next( + createHttpError(HttpCode.CONFLICT, wildcardConflict.message) + ); + } + // Prevent creating resource with same domain as dashboard const dashboardUrl = config.getRawConfig().app.dashboard_url; if (dashboardUrl) { @@ -299,7 +326,9 @@ async function createHttpResource( protocol: "tcp", ssl: true, stickySession: stickySession, - postAuthPath: postAuthPath + postAuthPath: postAuthPath, + wildcard, + health: "unknown" }) .returning(); diff --git a/server/routers/resource/deleteResource.ts b/server/routers/resource/deleteResource.ts index e63301867..682fd6aa9 100644 --- a/server/routers/resource/deleteResource.ts +++ b/server/routers/resource/deleteResource.ts @@ -1,8 +1,8 @@ import { Request, Response, NextFunction } from "express"; import { z } from "zod"; -import { db } from "@server/db"; +import { db, targetHealthCheck } from "@server/db"; import { newts, resources, sites, targets } from "@server/db"; -import { eq } from "drizzle-orm"; +import { eq, inArray } from "drizzle-orm"; import response from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; import createHttpError from "http-errors"; @@ -52,6 +52,16 @@ export async function deleteResource( .from(targets) .where(eq(targets.resourceId, resourceId)); + const healthChecksToBeRemoved = await db + .select() + .from(targetHealthCheck) + .where( + inArray( + targetHealthCheck.targetId, + targetsToBeRemoved.map((t) => t.targetId) + ) + ); + const [deletedResource] = await db .delete(resources) .where(eq(resources.resourceId, resourceId)) @@ -66,44 +76,43 @@ export async function deleteResource( ); } - // const [site] = await db - // .select() - // .from(sites) - // .where(eq(sites.siteId, deletedResource.siteId!)) - // .limit(1); - // - // if (!site) { - // return next( - // createHttpError( - // HttpCode.NOT_FOUND, - // `Site with ID ${deletedResource.siteId} not found` - // ) - // ); - // } - // - // if (site.pubKey) { - // if (site.type == "wireguard") { - // await addPeer(site.exitNodeId!, { - // publicKey: site.pubKey, - // allowedIps: await getAllowedIps(site.siteId) - // }); - // } else if (site.type == "newt") { - // // get the newt on the site by querying the newt table for siteId - // const [newt] = await db - // .select() - // .from(newts) - // .where(eq(newts.siteId, site.siteId)) - // .limit(1); - // - // removeTargets( - // newt.newtId, - // targetsToBeRemoved, - // deletedResource.protocol, - // deletedResource.proxyPort - // ); - // } - // } - // + for (const target of targetsToBeRemoved) { + const [site] = await db + .select() + .from(sites) + .where(eq(sites.siteId, target.siteId)) + .limit(1); + + if (!site) { + return next( + createHttpError( + HttpCode.NOT_FOUND, + `Site with ID ${target.siteId} not found` + ) + ); + } + + if (site.pubKey) { + if (site.type == "newt") { + // get the newt on the site by querying the newt table for siteId + const [newt] = await db + .select() + .from(newts) + .where(eq(newts.siteId, site.siteId)) + .limit(1); + + await removeTargets( + newt.newtId, + // [target], + [], // deleting the target from newt causes issues because we cant unbind the port. this needs to be fixed in newt before we can do this + healthChecksToBeRemoved, + deletedResource.protocol, + newt.version + ); + } + } + } + return response(res, { data: null, success: true, diff --git a/server/routers/resource/getResourceAuthInfo.ts b/server/routers/resource/getResourceAuthInfo.ts index 7def75d5b..30ff4699a 100644 --- a/server/routers/resource/getResourceAuthInfo.ts +++ b/server/routers/resource/getResourceAuthInfo.ts @@ -32,6 +32,8 @@ export type GetResourceAuthInfoResponse = { sso: boolean; blockAccess: boolean; url: string; + wildcard: boolean; + fullDomain: string | null; whitelist: boolean; skipToIdpId: number | null; orgId: string; @@ -130,7 +132,9 @@ export async function getResourceAuthInfo( const headerAuthExtendedCompatibility = result?.resourceHeaderAuthExtendedCompatibility; - const url = `${resource.ssl ? "https" : "http"}://${resource.fullDomain}`; + const url = resource.fullDomain + ? `${resource.ssl ? "https" : "http"}://${resource.fullDomain}` + : null; return response(res, { data: { @@ -145,7 +149,9 @@ export async function getResourceAuthInfo( headerAuthExtendedCompatibility !== null, sso: resource.sso, blockAccess: resource.blockAccess, - url, + url: url ?? "", + wildcard: resource.wildcard ?? false, + fullDomain: resource.fullDomain, whitelist: resource.emailWhitelistEnabled, skipToIdpId: resource.skipToIdpId, orgId: resource.orgId, diff --git a/server/routers/resource/getStatusHistory.ts b/server/routers/resource/getStatusHistory.ts index 9aa548624..c3dcf6c88 100644 --- a/server/routers/resource/getStatusHistory.ts +++ b/server/routers/resource/getStatusHistory.ts @@ -1,14 +1,12 @@ 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, + getCachedStatusHistory, statusHistoryQuerySchema, StatusHistoryResponse } from "@server/lib/statusHistory"; @@ -46,39 +44,10 @@ export async function getResourceStatusHistory( 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; + const data = await getCachedStatusHistory(entityType, entityId, days); return response(res, { - data: { - entityType, - entityId, - days: buckets, - overallUptimePercent: Math.round(overallUptime * 100) / 100, - totalDowntimeSeconds: totalDowntime - }, + data, success: true, error: false, message: "Status history retrieved successfully", @@ -90,4 +59,4 @@ export async function getResourceStatusHistory( createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") ); } -} +} \ No newline at end of file diff --git a/server/routers/resource/getUserResources.ts b/server/routers/resource/getUserResources.ts index 1722a7993..c0f21a440 100644 --- a/server/routers/resource/getUserResources.ts +++ b/server/routers/resource/getUserResources.ts @@ -86,7 +86,12 @@ export async function getUserResources( .where(inArray(roleSiteResources.roleId, userRoleIds)) : Promise.resolve([]); - const [directResources, roleResourceResults, directSiteResourceResults, roleSiteResourceResults] = await Promise.all([ + const [ + directResources, + roleResourceResults, + directSiteResourceResults, + roleSiteResourceResults + ] = await Promise.all([ directResourcesQuery, roleResourcesQuery, directSiteResourcesQuery, @@ -118,24 +123,24 @@ export async function getUserResources( }> = []; if (accessibleResourceIds.length > 0) { resourcesData = await db - .select({ - resourceId: resources.resourceId, - name: resources.name, - fullDomain: resources.fullDomain, - ssl: resources.ssl, - enabled: resources.enabled, - sso: resources.sso, - protocol: resources.protocol, - emailWhitelistEnabled: resources.emailWhitelistEnabled - }) - .from(resources) - .where( - and( - inArray(resources.resourceId, accessibleResourceIds), - eq(resources.orgId, orgId), - eq(resources.enabled, true) - ) - ); + .select({ + resourceId: resources.resourceId, + name: resources.name, + fullDomain: resources.fullDomain, + ssl: resources.ssl, + enabled: resources.enabled, + sso: resources.sso, + protocol: resources.protocol, + emailWhitelistEnabled: resources.emailWhitelistEnabled + }) + .from(resources) + .where( + and( + inArray(resources.resourceId, accessibleResourceIds), + eq(resources.orgId, orgId), + eq(resources.enabled, true) + ) + ); } // Get site resource details for accessible site resources @@ -166,7 +171,10 @@ export async function getUserResources( .from(siteResources) .where( and( - inArray(siteResources.siteResourceId, accessibleSiteResourceIds), + inArray( + siteResources.siteResourceId, + accessibleSiteResourceIds + ), eq(siteResources.orgId, orgId), eq(siteResources.enabled, true) ) @@ -246,7 +254,7 @@ export async function getUserResources( enabled: siteResource.enabled, alias: siteResource.alias, aliasAddress: siteResource.aliasAddress, - type: 'site' as const + type: "site" as const }; }); diff --git a/server/routers/resource/listResources.ts b/server/routers/resource/listResources.ts index d1accfc9d..16a82e400 100644 --- a/server/routers/resource/listResources.ts +++ b/server/routers/resource/listResources.ts @@ -105,15 +105,20 @@ const listResourcesSchema = z.object({ "Filter resources based on authentication state. `protected` means the resource has at least one auth mechanism (password, pincode, header auth, SSO, or email whitelist). `not_protected` means the resource has no auth mechanisms. `none` means the resource is not protected by HTTP (i.e. it has no auth mechanisms and http is false)." }), healthStatus: z - .enum(["no_targets", "healthy", "degraded", "offline", "unknown"]) + .enum(["healthy", "degraded", "unhealthy", "unknown"]) .optional() .catch(undefined) .openapi({ type: "string", - enum: ["no_targets", "healthy", "degraded", "offline", "unknown"], + enum: ["healthy", "degraded", "offline", "unknown"], description: - "Filter resources based on health status of their targets. `healthy` means all targets are healthy. `degraded` means at least one target is unhealthy, but not all are unhealthy. `offline` means all targets are unhealthy. `unknown` means all targets have unknown health status. `no_targets` means the resource has no targets." - }) + "Filter resources based on health status of their targets. `healthy` means all targets are healthy. `degraded` means at least one target is unhealthy, but not all are unhealthy. `offline` means all targets are unhealthy. `unknown` means all targets have unknown health status." + }), + siteId: z.coerce.number().int().positive().optional().openapi({ + type: "integer", + description: + "When set, only resources that have at least one target on this site are returned" + }) }); // grouped by resource with targets[]) @@ -133,6 +138,8 @@ export type ResourceWithTargets = { domainId: string | null; niceId: string; headerAuthId: number | null; + wildcard: boolean; + health: string | null; targets: Array<{ targetId: number; ip: string; @@ -141,29 +148,14 @@ export type ResourceWithTargets = { healthStatus: "healthy" | "unhealthy" | "unknown" | null; siteName: string | null; }>; + sites: Array<{ + siteId: number; + siteName: string; + siteNiceId: string; + online?: boolean; // undefined for local sites + }>; }; -// Aggregate filters -const total_targets = count(targets.targetId); -const healthy_targets = sql`SUM( - CASE - WHEN ${targetHealthCheck.hcHealth} = 'healthy' THEN 1 - ELSE 0 - END - ) `; -const unknown_targets = sql`SUM( - CASE - WHEN ${targetHealthCheck.hcHealth} = 'unknown' THEN 1 - ELSE 0 - END - ) `; -const unhealthy_targets = sql`SUM( - CASE - WHEN ${targetHealthCheck.hcHealth} = 'unhealthy' THEN 1 - ELSE 0 - END - ) `; - function queryResourcesBase() { return db .select({ @@ -181,9 +173,11 @@ function queryResourcesBase() { enabled: resources.enabled, domainId: resources.domainId, niceId: resources.niceId, + wildcard: resources.wildcard, headerAuthId: resourceHeaderAuth.headerAuthId, headerAuthExtendedCompatibilityId: - resourceHeaderAuthExtendedCompatibility.headerAuthExtendedCompatibilityId + resourceHeaderAuthExtendedCompatibility.headerAuthExtendedCompatibilityId, + health: resources.health }) .from(resources) .leftJoin( @@ -260,7 +254,8 @@ export async function listResources( query, healthStatus, sort_by, - order + order, + siteId } = parsedQuery.data; const parsedParams = listResourcesParamsSchema.safeParse(req.params); @@ -380,44 +375,19 @@ export async function listResources( } } - let aggregateFilters: SQL | undefined = sql`1 = 1`; - if (typeof healthStatus !== "undefined") { - switch (healthStatus) { - case "healthy": - aggregateFilters = and( - sql`${total_targets} > 0`, - sql`${healthy_targets} = ${total_targets}` - ); - break; - case "degraded": - aggregateFilters = and( - sql`${total_targets} > 0`, - sql`${unhealthy_targets} > 0` - ); - break; - case "no_targets": - aggregateFilters = sql`${total_targets} = 0`; - break; - case "offline": - aggregateFilters = and( - sql`${total_targets} > 0`, - sql`${healthy_targets} = 0`, - sql`${unhealthy_targets} = ${total_targets}` - ); - break; - case "unknown": - aggregateFilters = and( - sql`${total_targets} > 0`, - sql`${unknown_targets} = ${total_targets}` - ); - break; - } + conditions.push(eq(resources.health, healthStatus)); + } + if (siteId != null) { + const resourcesWithSite = db + .select({ resourceId: targets.resourceId }) + .from(targets) + .innerJoin(sites, eq(targets.siteId, sites.siteId)) + .where(and(eq(sites.orgId, orgId), eq(sites.siteId, siteId))); + conditions.push(inArray(resources.resourceId, resourcesWithSite)); } - const baseQuery = queryResourcesBase() - .where(and(...conditions)) - .having(aggregateFilters); + const baseQuery = queryResourcesBase().where(and(...conditions)); // we need to add `as` so that drizzle filters the result as a subquery const countQuery = db.$count(baseQuery.as("filtered_resources")); @@ -444,12 +414,16 @@ export async function listResources( .select({ targetId: targets.targetId, resourceId: targets.resourceId, + siteId: targets.siteId, ip: targets.ip, port: targets.port, enabled: targets.enabled, healthStatus: targetHealthCheck.hcHealth, hcEnabled: targetHealthCheck.hcEnabled, - siteName: sites.name + siteName: sites.name, + siteNiceId: sites.niceId, + siteOnline: sites.online, + siteType: sites.type }) .from(targets) .where(inArray(targets.resourceId, resourceIdList)) @@ -478,10 +452,13 @@ export async function listResources( http: row.http, protocol: row.protocol, proxyPort: row.proxyPort, + wildcard: row.wildcard, enabled: row.enabled, domainId: row.domainId, headerAuthId: row.headerAuthId, - targets: [] + health: row.health ?? null, + targets: [], + sites: [] }; map.set(row.resourceId, entry); } @@ -491,6 +468,34 @@ export async function listResources( ); } + for (const entry of map.values()) { + const raw = allResourceTargets.filter( + (t) => t.resourceId === entry.resourceId + ); + const siteById = new Map< + number, + { + siteId: number; + siteName: string; + siteNiceId: string; + online?: boolean; + } + >(); + for (const t of raw) { + if (typeof t.siteId !== "number" || siteById.has(t.siteId)) { + continue; + } + const isLocal = t.siteType === "local"; + siteById.set(t.siteId, { + siteId: t.siteId, + siteName: t.siteName ?? "", + siteNiceId: t.siteNiceId ?? "", + online: isLocal ? undefined : Boolean(t.siteOnline) + }); + } + entry.sites = Array.from(siteById.values()); + } + const resourcesList: ResourceWithTargets[] = Array.from(map.values()); return response(res, { diff --git a/server/routers/resource/updateResource.ts b/server/routers/resource/updateResource.ts index 21a923704..0a7052dce 100644 --- a/server/routers/resource/updateResource.ts +++ b/server/routers/resource/updateResource.ts @@ -16,12 +16,15 @@ import createHttpError from "http-errors"; import logger from "@server/logger"; import { fromError } from "zod-validation-error"; import config from "@server/lib/config"; -import { tlsNameSchema } from "@server/lib/schemas"; -import { subdomainSchema } from "@server/lib/schemas"; +import { + tlsNameSchema, + subdomainSchema, + wildcardSubdomainSchema +} from "@server/lib/schemas"; import { registry } from "@server/openApi"; import { OpenAPITags } from "@server/openApi"; import { createCertificate } from "#dynamic/routers/certificates/createCertificate"; -import { validateAndConstructDomain } from "@server/lib/domainUtils"; +import { validateAndConstructDomain, checkWildcardDomainConflict } from "@server/lib/domainUtils"; import { build } from "@server/build"; import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed"; import { tierMatrix } from "@server/lib/billing/tierMatrix"; @@ -43,7 +46,7 @@ const updateHttpResourceBodySchema = z "niceId can only contain letters, numbers, and dashes" ) .optional(), - subdomain: subdomainSchema.nullable().optional(), + subdomain: z.string().nullable().optional(), ssl: z.boolean().optional(), sso: z.boolean().optional(), blockAccess: z.boolean().optional(), @@ -73,7 +76,10 @@ const updateHttpResourceBodySchema = z .refine( (data) => { if (data.subdomain) { - return subdomainSchema.safeParse(data.subdomain).success; + return ( + subdomainSchema.safeParse(data.subdomain).success || + wildcardSubdomainSchema.safeParse(data.subdomain).success + ); } return true; }, @@ -318,6 +324,22 @@ async function updateHttpResource( } } + // Wildcard subdomains are a paid feature + if (updateData.subdomain && updateData.subdomain.includes("*")) { + const isLicensed = await isLicensedOrSubscribed( + resource.orgId, + tierMatrix.wildcardSubdomain + ); + if (!isLicensed) { + return next( + createHttpError( + HttpCode.FORBIDDEN, + "Wildcard subdomains are not supported on your current plan. Please upgrade to access this feature." + ) + ); + } + } + if (updateData.domainId) { const domainId = updateData.domainId; @@ -362,7 +384,11 @@ async function updateHttpResource( ); } - const { fullDomain, subdomain: finalSubdomain } = domainResult; + const { + fullDomain, + subdomain: finalSubdomain, + wildcard + } = domainResult; logger.debug(`Full domain: ${fullDomain}`); @@ -384,6 +410,16 @@ async function updateHttpResource( ); } + const wildcardConflict = await checkWildcardDomainConflict( + fullDomain, + resource.resourceId + ); + if (wildcardConflict.conflict) { + return next( + createHttpError(HttpCode.CONFLICT, wildcardConflict.message) + ); + } + // Prevent updating resource with same domain as dashboard const dashboardUrl = config.getRawConfig().app.dashboard_url; if (dashboardUrl) { @@ -419,7 +455,7 @@ async function updateHttpResource( if (fullDomain && fullDomain !== resource.fullDomain) { await db .update(resources) - .set({ fullDomain }) + .set({ fullDomain, wildcard }) .where(eq(resources.resourceId, resource.resourceId)); } diff --git a/server/routers/site/createSite.ts b/server/routers/site/createSite.ts index f9b26799e..29eb4935d 100644 --- a/server/routers/site/createSite.ts +++ b/server/routers/site/createSite.ts @@ -1,6 +1,6 @@ import { Request, Response, NextFunction } from "express"; import { z } from "zod"; -import { clients, db, exitNodes } from "@server/db"; +import { clients, db, exitNodes, logsDb, statusHistory } from "@server/db"; import { roles, userSites, sites, roleSites, Site, orgs } from "@server/db"; import response from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; @@ -321,12 +321,7 @@ export async function createSite( const existingSite = await db .select() .from(sites) - .where( - and( - eq(sites.niceId, niceId), - eq(sites.orgId, orgId) - ) - ) + .where(and(eq(sites.niceId, niceId), eq(sites.orgId, orgId))) .limit(1); if (existingSite.length > 0) { @@ -344,7 +339,8 @@ export async function createSite( if (type == "newt") { [newSite] = await trx .insert(sites) - .values({ // NOTE: NO SUBNET OR EXIT NODE ID PASSED IN HERE BECAUSE ITS NOW CHOSEN ON CONNECT + .values({ + // NOTE: NO SUBNET OR EXIT NODE ID PASSED IN HERE BECAUSE ITS NOW CHOSEN ON CONNECT orgId, name, niceId: updatedNiceId!, @@ -354,6 +350,14 @@ export async function createSite( status: "approved" }) .returning(); + + await logsDb.insert(statusHistory).values({ + entityType: "site", + entityId: newSite.siteId, + orgId: orgId, + status: "offline", + timestamp: Math.floor(Date.now() / 1000) + }); } else if (type == "wireguard") { // we are creating a site with an exit node (tunneled) if (!subnet) { diff --git a/server/routers/site/deleteSite.ts b/server/routers/site/deleteSite.ts index 344f6b4e3..10ecbbf1e 100644 --- a/server/routers/site/deleteSite.ts +++ b/server/routers/site/deleteSite.ts @@ -2,7 +2,7 @@ import { Request, Response, NextFunction } from "express"; import { z } from "zod"; import { db, Site, siteNetworks, siteResources } from "@server/db"; import { newts, newtSessions, sites } from "@server/db"; -import { eq } from "drizzle-orm"; +import { eq, inArray } from "drizzle-orm"; import response from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; import createHttpError from "http-errors"; @@ -77,17 +77,20 @@ export async function deleteSite( .where(eq(siteNetworks.siteId, siteId)); // loop through them - 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 - ); - } + const updatedSiteResources = await trx + .select() + .from(siteResources) + .where( + inArray( + siteResources.networkId, + networks.map((n) => n.networkId) + ) + ); + for (const siteResource of updatedSiteResources) { + 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 index f1717c8a9..26f1dbbd2 100644 --- a/server/routers/site/getStatusHistory.ts +++ b/server/routers/site/getStatusHistory.ts @@ -1,14 +1,12 @@ 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, + getCachedStatusHistory, statusHistoryQuerySchema, StatusHistoryResponse } from "@server/lib/statusHistory"; @@ -46,39 +44,10 @@ export async function getSiteStatusHistory( 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; + const data = await getCachedStatusHistory(entityType, entityId, days); return response(res, { - data: { - entityType, - entityId, - days: buckets, - overallUptimePercent: Math.round(overallUptime * 100) / 100, - totalDowntimeSeconds: totalDowntime - }, + data, success: true, error: false, message: "Status history retrieved successfully", @@ -90,4 +59,4 @@ export async function getSiteStatusHistory( createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") ); } -} +} \ No newline at end of file diff --git a/server/routers/site/listSites.ts b/server/routers/site/listSites.ts index 88bb233ed..fc4ea5be1 100644 --- a/server/routers/site/listSites.ts +++ b/server/routers/site/listSites.ts @@ -5,6 +5,9 @@ import { orgs, remoteExitNodes, roleSites, + siteNetworks, + siteResources, + targets, sites, userSites } from "@server/db"; @@ -28,7 +31,9 @@ let staleNewtVersion: string | null = null; async function getLatestNewtVersion(): Promise { try { - const cachedVersion = await cache.get("cache:latestNewtVersion"); + const cachedVersion = await cache.get( + "cache:latestNewtVersion" + ); if (cachedVersion) { return cachedVersion; } @@ -199,6 +204,18 @@ function querySitesBase() { exitNodeName: exitNodes.name, exitNodeEndpoint: exitNodes.endpoint, remoteExitNodeId: remoteExitNodes.remoteExitNodeId, + resourceCount: sql`( + SELECT COUNT(DISTINCT ${targets.resourceId}) + FROM ${targets} + WHERE ${targets.siteId} = ${sites.siteId} + ) + ( + SELECT COUNT(DISTINCT ${siteResources.siteResourceId}) + FROM ${siteResources} + INNER JOIN ${siteNetworks} + ON ${siteResources.networkId} = ${siteNetworks.networkId} + WHERE ${siteNetworks.siteId} = ${sites.siteId} + AND ${siteResources.orgId} = ${sites.orgId} + )`, status: sites.status }) .from(sites) @@ -211,7 +228,10 @@ function querySitesBase() { ); } -type SiteWithUpdateAvailable = Awaited>[0] & { +type SiteRowBase = Awaited>[0]; + +type SiteWithUpdateAvailable = Omit & { + online?: SiteRowBase["online"]; // undefined for local sites newtUpdateAvailable?: boolean; }; @@ -319,12 +339,13 @@ export async function listSites( if (typeof status !== "undefined") { conditions.push(eq(sites.status, status)); } - const baseQuery = querySitesBase().where(and(...conditions)); // we need to add `as` so that drizzle filters the result as a subquery const countQuery = db.$count( - querySitesBase().where(and(...conditions)).as("filtered_sites") + querySitesBase() + .where(and(...conditions)) + .as("filtered_sites") ); const siteListQuery = baseQuery @@ -383,9 +404,13 @@ export async function listSites( ); } + const sitesPayload = sitesWithUpdates.map((site) => + site.type === "local" ? { ...site, online: undefined } : site + ); + return response(res, { data: { - sites: sitesWithUpdates, + sites: sitesPayload, pagination: { total: totalCount, pageSize, diff --git a/server/routers/siteResource/createSiteResource.ts b/server/routers/siteResource/createSiteResource.ts index 242bbf860..0da48d160 100644 --- a/server/routers/siteResource/createSiteResource.ts +++ b/server/routers/siteResource/createSiteResource.ts @@ -46,7 +46,8 @@ const createSiteResourceSchema = z 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()), + siteIds: z.array(z.int()).optional(), + siteId: z.number().int().positive().optional(), // DEPRECATED: for backward compatibility, we will convert this to siteIds array if provided // proxyPort: z.int().positive().optional(), destinationPort: z.int().positive().optional(), destination: z.string().min(1), @@ -132,6 +133,17 @@ const createSiteResourceSchema = z message: "HTTP mode requires scheme (http or https) and a valid destination port" } + ) + .refine( + (data) => { + return ( + (data.siteIds !== undefined && data.siteIds.length > 0) || + data.siteId !== undefined + ); + }, + { + message: "At least one of siteIds or siteId must be provided" + } ); export type CreateSiteResourceBody = z.infer; @@ -187,7 +199,8 @@ export async function createSiteResource( const { name, niceId, - siteIds, + siteIds: siteIdsInput = [], + siteId, mode, scheme, // proxyPort, @@ -208,6 +221,12 @@ export async function createSiteResource( subdomain } = parsedBody.data; + // Backward compatibility: merge deprecated siteId into siteIds array + const siteIds = [...siteIdsInput]; + if (siteId !== undefined && !siteIds.includes(siteId)) { + siteIds.push(siteId); + } + if (mode == "http") { const hasHttpFeature = await isLicensedOrSubscribed( orgId, @@ -389,9 +408,10 @@ export async function createSiteResource( enabled, alias: alias ? alias.trim() : null, aliasAddress, - tcpPortRangeString, - udpPortRangeString, - disableIcmp, + tcpPortRangeString: + mode == "http" ? "443,80" : tcpPortRangeString, + udpPortRangeString: mode == "http" ? "" : udpPortRangeString, + disableIcmp: disableIcmp || (mode == "http" ? true : false), // default to true for http resources, otherwise false domainId, subdomain: finalSubdomain, fullDomain @@ -496,7 +516,13 @@ export async function createSiteResource( `Created site resource ${newSiteResource.siteResourceId} for org ${orgId}` ); - if (ssl && mode === "http" && domainId && fullDomain && build != "oss") { + if ( + ssl && + mode === "http" && + domainId && + fullDomain && + build != "oss" + ) { await createCertificate(domainId, fullDomain, db); } diff --git a/server/routers/siteResource/deleteSiteResource.ts b/server/routers/siteResource/deleteSiteResource.ts index 8d08d545d..df43d5c25 100644 --- a/server/routers/siteResource/deleteSiteResource.ts +++ b/server/routers/siteResource/deleteSiteResource.ts @@ -67,22 +67,9 @@ export async function deleteSiteResource( // Delete the site resource const [removedSiteResource] = await trx .delete(siteResources) - .where(and(eq(siteResources.siteResourceId, siteResourceId))) + .where(eq(siteResources.siteResourceId, siteResourceId)) .returning(); - // 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") - // ); - // } - await rebuildClientAssociationsFromSiteResource( removedSiteResource, trx diff --git a/server/routers/siteResource/listAllSiteResourcesByOrg.ts b/server/routers/siteResource/listAllSiteResourcesByOrg.ts index 8750e7516..c7099de40 100644 --- a/server/routers/siteResource/listAllSiteResourcesByOrg.ts +++ b/server/routers/siteResource/listAllSiteResourcesByOrg.ts @@ -4,7 +4,7 @@ import logger from "@server/logger"; import { OpenAPITags, registry } from "@server/openApi"; import HttpCode from "@server/types/HttpCode"; import type { PaginatedResponse } from "@server/types/Pagination"; -import { and, asc, desc, eq, like, or, sql } from "drizzle-orm"; +import { and, asc, desc, eq, inArray, like, or, sql } from "drizzle-orm"; import { NextFunction, Request, Response } from "express"; import createHttpError from "http-errors"; import { z } from "zod"; @@ -68,6 +68,16 @@ const listAllSiteResourcesByOrgQuerySchema = z.object({ enum: ["asc", "desc"], default: "asc", description: "Sort order" + }), + siteId: z.coerce + .number() + .int() + .positive() + .optional() + .openapi({ + type: "integer", + description: + "When set, only site resources associated with this site (via network) are returned" }) }); @@ -88,9 +98,11 @@ export type ListAllSiteResourcesByOrgResponse = PaginatedResponse<{ */ function aggCol(column: any) { if (DB_TYPE === "sqlite") { + // json_group_array will include NULLs for left-joined missing rows; + // we filter them out in transformSiteResourceRow keeping arrays aligned. return sql`json_group_array(${column})`; } - return sql`array_agg(${column})`; + return sql`COALESCE(array_agg(${column}) FILTER (WHERE ${sites.siteId} IS NOT NULL), '{}')`; } /** @@ -102,16 +114,36 @@ function transformSiteResourceRow(row: any) { if (DB_TYPE !== "sqlite") { return row; } + const siteIdsRaw = JSON.parse(row.siteIds) as (number | null)[]; + const siteNamesRaw = JSON.parse(row.siteNames) as (string | null)[]; + const siteNiceIdsRaw = JSON.parse(row.siteNiceIds) as (string | null)[]; + const siteAddressesRaw = JSON.parse(row.siteAddresses) as (string | null)[]; + const siteOnlinesRaw = JSON.parse(row.siteOnlines) as (0 | 1 | null)[]; + + // When a site resource has no associated sites (left join produced no + // matches), the aggregated arrays will contain a single NULL entry. Strip + // those out, keeping the parallel arrays aligned by siteId presence. + const siteIds: number[] = []; + const siteNames: string[] = []; + const siteNiceIds: string[] = []; + const siteAddresses: (string | null)[] = []; + const siteOnlines: boolean[] = []; + for (let i = 0; i < siteIdsRaw.length; i++) { + if (siteIdsRaw[i] == null) continue; + siteIds.push(siteIdsRaw[i] as number); + siteNames.push((siteNamesRaw[i] ?? "") as string); + siteNiceIds.push((siteNiceIdsRaw[i] ?? "") as string); + siteAddresses.push(siteAddressesRaw[i] ?? null); + siteOnlines.push(siteOnlinesRaw[i] === 1); + } + 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[] + siteNames, + siteNiceIds, + siteIds, + siteAddresses, + siteOnlines }; } @@ -148,11 +180,11 @@ function querySiteResourcesBase() { siteOnlines: aggCol(sites.online) }) .from(siteResources) - .innerJoin( + .leftJoin( siteNetworks, eq(siteResources.networkId, siteNetworks.networkId) ) - .innerJoin(sites, eq(siteNetworks.siteId, sites.siteId)) + .leftJoin(sites, eq(siteNetworks.siteId, sites.siteId)) .groupBy(siteResources.siteResourceId); } @@ -199,10 +231,33 @@ export async function listAllSiteResourcesByOrg( } const { orgId } = parsedParams.data; - const { page, pageSize, query, mode, sort_by, order } = + const { page, pageSize, query, mode, sort_by, order, siteId } = parsedQuery.data; const conditions = [and(eq(siteResources.orgId, orgId))]; + + if (siteId != null) { + // Keep inner joins here: filtering by a specific site implies the + // resource must have at least one matching site. + const resourcesForSite = db + .select({ id: siteResources.siteResourceId }) + .from(siteResources) + .innerJoin( + siteNetworks, + eq(siteResources.networkId, siteNetworks.networkId) + ) + .innerJoin(sites, eq(siteNetworks.siteId, sites.siteId)) + .where( + and( + eq(siteResources.orgId, orgId), + eq(sites.orgId, orgId), + eq(sites.siteId, siteId) + ) + ); + conditions.push( + inArray(siteResources.siteResourceId, resourcesForSite) + ); + } if (query) { conditions.push( or( diff --git a/server/routers/siteResource/listSiteResources.ts b/server/routers/siteResource/listSiteResources.ts index 8a1469f76..61460c2d0 100644 --- a/server/routers/siteResource/listSiteResources.ts +++ b/server/routers/siteResource/listSiteResources.ts @@ -112,10 +112,7 @@ export async function listSiteResources( const siteResourcesList = await db .select() .from(siteNetworks) - .innerJoin( - networks, - eq(siteNetworks.networkId, networks.networkId) - ) + .innerJoin(networks, eq(siteNetworks.networkId, networks.networkId)) .innerJoin( siteResources, eq(siteResources.networkId, networks.networkId) @@ -136,7 +133,6 @@ 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 4335b55d3..d0efa0cf4 100644 --- a/server/routers/siteResource/updateSiteResource.ts +++ b/server/routers/siteResource/updateSiteResource.ts @@ -43,7 +43,8 @@ const updateSiteResourceParamsSchema = z.strictObject({ const updateSiteResourceSchema = z .strictObject({ name: z.string().min(1).max(255).optional(), - siteIds: z.array(z.int()), + siteIds: z.array(z.int()).optional(), + siteId: z.int().positive().optional(), // niceId: z.string().min(1).max(255).regex(/^[a-zA-Z0-9-]+$/, "niceId can only contain letters, numbers, and dashes").optional(), niceId: z .string() @@ -142,6 +143,17 @@ const updateSiteResourceSchema = z message: "HTTP mode requires scheme (http or https) and a valid destination port" } + ) + .refine( + (data) => { + return ( + (data.siteIds !== undefined && data.siteIds.length > 0) || + data.siteId !== undefined + ); + }, + { + message: "At least one of siteIds or siteId must be provided" + } ); export type UpdateSiteResourceBody = z.infer; @@ -196,7 +208,8 @@ export async function updateSiteResource( const { siteResourceId } = parsedParams.data; const { name, - siteIds, // because it can change + siteIds: siteIdsInput = [], // because it can change + siteId, niceId, mode, scheme, @@ -217,6 +230,12 @@ export async function updateSiteResource( subdomain } = parsedBody.data; + // Backward compatibility: merge deprecated siteId into siteIds array + const siteIds = [...siteIdsInput]; + if (siteId !== undefined && !siteIds.includes(siteId)) { + siteIds.push(siteId); + } + // Check if site resource exists const [existingSiteResource] = await db .select() @@ -440,9 +459,12 @@ export async function updateSiteResource( destinationPort, enabled, alias: alias ? alias.trim() : null, - tcpPortRangeString, - udpPortRangeString, - disableIcmp, + tcpPortRangeString: + mode == "http" ? "443,80" : tcpPortRangeString, + udpPortRangeString: + mode == "http" ? "" : udpPortRangeString, + disableIcmp: + disableIcmp || (mode == "http" ? true : false), // default to true for http resources, otherwise false domainId, subdomain: finalSubdomain, fullDomain, @@ -730,8 +752,13 @@ export async function handleMessagingForUpdatedSiteResource( updatedSiteResource.destinationPort; const aliasChanged = existingSiteResource && - (existingSiteResource.alias !== updatedSiteResource.alias || - existingSiteResource.fullDomain !== updatedSiteResource.fullDomain); // because the full domain gets sent down to the stuff as an alias + existingSiteResource.alias !== updatedSiteResource.alias; + const fullDomainChanged = + existingSiteResource && + existingSiteResource.fullDomain !== updatedSiteResource.fullDomain; + const sslChanged = + existingSiteResource && + existingSiteResource.ssl !== updatedSiteResource.ssl; const portRangesChanged = existingSiteResource && (existingSiteResource.tcpPortRangeString !== @@ -746,6 +773,8 @@ export async function handleMessagingForUpdatedSiteResource( if ( destinationChanged || aliasChanged || + fullDomainChanged || + sslChanged || portRangesChanged || destinationPortChanged ) { @@ -762,10 +791,12 @@ export async function handleMessagingForUpdatedSiteResource( ); } - // Only update targets on newt if destination changed + // Only update targets on newt if these items change if ( destinationChanged || + sslChanged || // we need to push a new cert if the ssl changed portRangesChanged || + fullDomainChanged || // if the domain changes we need to update the certs and stuff destinationPortChanged ) { const oldTargets = await generateSubnetProxyTargetV2( @@ -844,7 +875,7 @@ export async function handleMessagingForUpdatedSiteResource( ]) } : undefined, - aliasChanged + aliasChanged || fullDomainChanged // the full domain is sent down as an alias ? { oldAliases: generateAliasConfig([ existingSiteResource diff --git a/server/routers/target/createTarget.ts b/server/routers/target/createTarget.ts index e5c1f246e..d582d06da 100644 --- a/server/routers/target/createTarget.ts +++ b/server/routers/target/createTarget.ts @@ -1,6 +1,11 @@ import { Request, Response, NextFunction } from "express"; import { z } from "zod"; -import { db, TargetHealthCheck, targetHealthCheck } from "@server/db"; +import { + db, + statusHistory, + TargetHealthCheck, + targetHealthCheck +} from "@server/db"; import { newts, resources, sites, Target, targets } from "@server/db"; import response from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; @@ -14,6 +19,11 @@ import { eq } from "drizzle-orm"; import { pickPort } from "./helpers"; import { isTargetValid } from "@server/lib/validators"; import { OpenAPITags, registry } from "@server/openApi"; +import { + fireHealthCheckHealthyAlert, + fireHealthCheckUnhealthyAlert, + fireHealthCheckUnknownAlert +} from "#dynamic/lib/alerts"; const createTargetParamsSchema = z.strictObject({ resourceId: z.string().transform(Number).pipe(z.int().positive()) @@ -136,121 +146,155 @@ export async function createTarget( ); } - const existingTargets = await db - .select() - .from(targets) - .where(eq(targets.resourceId, resourceId)); - - const existingTarget = existingTargets.find( - (target) => - target.ip === targetData.ip && - target.port === targetData.port && - target.method === targetData.method && - target.siteId === targetData.siteId - ); - - if (existingTarget) { - // log a warning - logger.warn( - `Target with IP ${targetData.ip}, port ${targetData.port}, method ${targetData.method} already exists for resource ID ${resourceId}` - ); - } - let newTarget: Target[] = []; - let healthCheck: TargetHealthCheck[] = []; let targetIps: string[] = []; - if (site.type == "local") { - newTarget = await db - .insert(targets) - .values({ - resourceId, - ...targetData, - priority: targetData.priority || 100 - }) - .returning(); - } else { - // make sure the target is within the site subnet - if ( - site.type == "wireguard" && - !isIpInCidr(targetData.ip, site.subnet!) - ) { - return next( - createHttpError( - HttpCode.BAD_REQUEST, - `Target IP is not within the site subnet` - ) - ); - } + let healthCheck: TargetHealthCheck[] = []; + await db.transaction(async (trx) => { + const existingTargets = await trx + .select() + .from(targets) + .where(eq(targets.resourceId, resourceId)); - const { internalPort, targetIps: newTargetIps } = await pickPort( - site.siteId!, - db + const existingTarget = existingTargets.find( + (target) => + target.ip === targetData.ip && + target.port === targetData.port && + target.method === targetData.method && + target.siteId === targetData.siteId ); - if (!internalPort) { - return next( - createHttpError( - HttpCode.BAD_REQUEST, - `No available internal port` - ) + if (existingTarget) { + // log a warning + logger.warn( + `Target with IP ${targetData.ip}, port ${targetData.port}, method ${targetData.method} already exists for resource ID ${resourceId}` ); } - newTarget = await db - .insert(targets) + if (site.type == "local") { + newTarget = await trx + .insert(targets) + .values({ + resourceId, + ...targetData, + priority: targetData.priority || 100 + }) + .returning(); + } else { + // make sure the target is within the site subnet + if ( + site.type == "wireguard" && + !isIpInCidr(targetData.ip, site.subnet!) + ) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + `Target IP is not within the site subnet` + ) + ); + } + + const { internalPort, targetIps: newTargetIps } = + await pickPort(site.siteId!, trx); + + if (!internalPort) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + `No available internal port` + ) + ); + } + + newTarget = await trx + .insert(targets) + .values({ + resourceId, + siteId: site.siteId, + ip: targetData.ip, + method: targetData.method, + port: targetData.port, + internalPort, + enabled: targetData.enabled, + path: targetData.path, + pathMatchType: targetData.pathMatchType, + rewritePath: targetData.rewritePath, + rewritePathType: targetData.rewritePathType, + priority: targetData.priority || 100 + }) + .returning(); + + // add the new target to the targetIps array + newTargetIps.push(`${targetData.ip}/32`); + + targetIps = newTargetIps; + } + + let hcHeaders = null; + if (targetData.hcHeaders) { + hcHeaders = JSON.stringify(targetData.hcHeaders); + } + + healthCheck = await trx + .insert(targetHealthCheck) .values({ - resourceId, - siteId: site.siteId, - ip: targetData.ip, - method: targetData.method, - port: targetData.port, - internalPort, - enabled: targetData.enabled, - path: targetData.path, - pathMatchType: targetData.pathMatchType, - rewritePath: targetData.rewritePath, - rewritePathType: targetData.rewritePathType, - priority: targetData.priority || 100 + 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, + hcMode: targetData.hcMode ?? null, + hcHostname: targetData.hcHostname ?? null, + hcPort: targetData.hcPort ?? null, + hcInterval: targetData.hcInterval ?? null, + hcUnhealthyInterval: targetData.hcUnhealthyInterval ?? null, + hcTimeout: targetData.hcTimeout ?? null, + hcHeaders: hcHeaders, + hcFollowRedirects: targetData.hcFollowRedirects ?? null, + hcMethod: targetData.hcMethod ?? null, + hcStatus: targetData.hcStatus ?? null, + hcHealth: targetData.hcEnabled ? "unhealthy" : "unknown", + hcTlsServerName: targetData.hcTlsServerName ?? null, + hcHealthyThreshold: targetData.hcHealthyThreshold ?? null, + hcUnhealthyThreshold: + targetData.hcUnhealthyThreshold ?? null }) .returning(); - // add the new target to the targetIps array - newTargetIps.push(`${targetData.ip}/32`); - - targetIps = newTargetIps; - } - - let hcHeaders = null; - if (targetData.hcHeaders) { - hcHeaders = JSON.stringify(targetData.hcHeaders); - } - - 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, - hcMode: targetData.hcMode ?? null, - hcHostname: targetData.hcHostname ?? null, - hcPort: targetData.hcPort ?? null, - hcInterval: targetData.hcInterval ?? null, - hcUnhealthyInterval: targetData.hcUnhealthyInterval ?? null, - hcTimeout: targetData.hcTimeout ?? null, - hcHeaders: hcHeaders, - hcFollowRedirects: targetData.hcFollowRedirects ?? null, - hcMethod: targetData.hcMethod ?? null, - hcStatus: targetData.hcStatus ?? null, - hcHealth: "unknown", - hcTlsServerName: targetData.hcTlsServerName ?? null, - hcHealthyThreshold: targetData.hcHealthyThreshold ?? null, - hcUnhealthyThreshold: targetData.hcUnhealthyThreshold ?? null - }) - .returning(); + if (healthCheck[0].hcHealth === "unhealthy") { + await fireHealthCheckUnhealthyAlert( + healthCheck[0].orgId, + healthCheck[0].targetHealthCheckId, + healthCheck[0].name || "", + healthCheck[0].targetId, + undefined, + false, // dont send the alert because we just want to create the alert, not notify users yet + trx + ); + } else if (healthCheck[0].hcHealth === "unknown") { + // if the health is unknown, we want to fire an alert to notify users to enable health checks + await fireHealthCheckUnknownAlert( + healthCheck[0].orgId, + healthCheck[0].targetHealthCheckId, + healthCheck[0].name, + healthCheck[0].targetId, + undefined, + false, // dont send the alert because we just want to create the alert, not notify users yet + trx + ); + } else if (healthCheck[0].hcHealth === "healthy") { + await fireHealthCheckHealthyAlert( + healthCheck[0].orgId, + healthCheck[0].targetHealthCheckId, + healthCheck[0].name || "", + healthCheck[0].targetId, + undefined, + false, // dont send the alert because we just want to create the alert, not notify users yet + trx + ); + } + }); if (site.pubKey) { if (site.type == "wireguard") { diff --git a/server/routers/target/deleteTarget.ts b/server/routers/target/deleteTarget.ts index 606d86351..685c41e7e 100644 --- a/server/routers/target/deleteTarget.ts +++ b/server/routers/target/deleteTarget.ts @@ -2,16 +2,15 @@ import { Request, Response, NextFunction } from "express"; import { z } from "zod"; import { db } from "@server/db"; import { newts, resources, sites, targets } from "@server/db"; -import { eq } from "drizzle-orm"; +import { eq, ne, and } 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 { addPeer } from "../gerbil/peers"; import { fromError } from "zod-validation-error"; import { removeTargets } from "../newt/targets"; -import { getAllowedIps } from "./helpers"; import { OpenAPITags, registry } from "@server/openApi"; +import { targetHealthCheck } from "@server/db"; const deleteTargetSchema = z.strictObject({ targetId: z.string().transform(Number).pipe(z.int().positive()) @@ -46,6 +45,11 @@ export async function deleteTarget( const { targetId } = parsedParams.data; + const [deletedHealthCheck] = await db + .delete(targetHealthCheck) + .where(eq(targetHealthCheck.targetId, targetId)) + .returning(); + const [deletedTarget] = await db .delete(targets) .where(eq(targets.targetId, targetId)) @@ -74,38 +78,59 @@ export async function deleteTarget( ); } - // const [site] = await db - // .select() - // .from(sites) - // .where(eq(sites.siteId, resource.siteId!)) - // .limit(1); - // - // if (!site) { - // return next( - // createHttpError( - // HttpCode.NOT_FOUND, - // `Site with ID ${resource.siteId} not found` - // ) - // ); - // } - // - // if (site.pubKey) { - // if (site.type == "wireguard") { - // await addPeer(site.exitNodeId!, { - // publicKey: site.pubKey, - // allowedIps: await getAllowedIps(site.siteId) - // }); - // } else if (site.type == "newt") { - // // get the newt on the site by querying the newt table for siteId - // const [newt] = await db - // .select() - // .from(newts) - // .where(eq(newts.siteId, site.siteId)) - // .limit(1); - // - // removeTargets(newt.newtId, [deletedTarget], resource.protocol, resource.proxyPort); - // } - // } + // check if there are other targets on the resource + const otherTargets = await db + .select() + .from(targets) + .where( + and( + eq(targets.resourceId, resource.resourceId), + ne(targets.targetId, targetId) + ) + ); + + if (otherTargets.length == 0) { + // set the resource status + await db + .update(resources) + .set({ health: "unknown" }) + .where(eq(resources.resourceId, resource.resourceId)); + } + + const [site] = await db + .select() + .from(sites) + .where(eq(sites.siteId, deletedTarget.siteId)) + .limit(1); + + if (!site) { + return next( + createHttpError( + HttpCode.NOT_FOUND, + `Site with ID ${targets.siteId} not found` + ) + ); + } + + if (site.pubKey) { + if (site.type == "newt") { + // get the newt on the site by querying the newt table for siteId + const [newt] = await db + .select() + .from(newts) + .where(eq(newts.siteId, site.siteId)) + .limit(1); + + await removeTargets( + newt.newtId, + // [deletedTarget], + [], // deleting the target from newt causes issues because we cant unbind the port. this needs to be fixed in newt before we can do this + [deletedHealthCheck], + resource.protocol, + newt.version + ); + } + } return response(res, { data: null, diff --git a/server/routers/target/handleHealthcheckStatusMessage.ts b/server/routers/target/handleHealthcheckStatusMessage.ts index 50331deb8..e5f286524 100644 --- a/server/routers/target/handleHealthcheckStatusMessage.ts +++ b/server/routers/target/handleHealthcheckStatusMessage.ts @@ -1,11 +1,4 @@ -import { - db, - targets, - resources, - sites, - targetHealthCheck, - statusHistory -} from "@server/db"; +import { db, primaryDb, targetHealthCheck } from "@server/db"; import { MessageHandler } from "@server/routers/ws"; import { Newt } from "@server/db"; import { eq, and, ne } from "drizzle-orm"; @@ -15,7 +8,6 @@ import { fireHealthCheckUnhealthyAlert } from "#dynamic/lib/alerts"; - interface TargetHealthStatus { status: string; lastCheck: string; @@ -89,31 +81,39 @@ export const handleHealthcheckStatusMessage: MessageHandler = async ( continue; } - const [targetCheck] = await db + const [targetCheck] = await primaryDb // using the primary db here in case it has just been updated and we are getting the immediate status back and it has not made it out to the repliacs yet .select({ targetId: targetHealthCheck.targetId, orgId: targetHealthCheck.orgId, targetHealthCheckId: targetHealthCheck.targetHealthCheckId, name: targetHealthCheck.name, - hcHealth: targetHealthCheck.hcHealth + hcHealth: targetHealthCheck.hcHealth, + hcEnabled: targetHealthCheck.hcEnabled }) .from(targetHealthCheck) .where( and( eq(targetHealthCheck.targetHealthCheckId, targetIdNum), - eq(sites.siteId, newt.siteId) + eq(targetHealthCheck.siteId, newt.siteId) ) ) .limit(1); if (!targetCheck) { - logger.warn( + logger.debug( `Target ${targetId} not found or does not belong to site ${newt.siteId}` ); errorCount++; continue; } + if (!targetCheck.hcEnabled) { + logger.debug( + `Health check for target ${targetId} is not enabled, skipping update` + ); + continue; + } + // check if the status has changed if (targetCheck.hcHealth === healthStatus.status) { logger.debug( @@ -132,7 +132,12 @@ export const handleHealthcheckStatusMessage: MessageHandler = async ( | "healthy" | "unhealthy" }) - .where(eq(targetHealthCheck.targetHealthCheckId, targetCheck.targetHealthCheckId)); + .where( + eq( + targetHealthCheck.targetHealthCheckId, + targetCheck.targetHealthCheckId + ) + ); // because we are checking above if there was a change we can fire the alert here because it changed if (healthStatus.status === "unhealthy") { @@ -142,6 +147,7 @@ export const handleHealthcheckStatusMessage: MessageHandler = async ( targetCheck.name ?? undefined, targetCheck.targetId, undefined, + true, trx ); } else if (healthStatus.status === "healthy") { @@ -151,6 +157,7 @@ export const handleHealthcheckStatusMessage: MessageHandler = async ( targetCheck.name ?? undefined, targetCheck.targetId, undefined, + true, trx ); } diff --git a/server/routers/target/updateTarget.ts b/server/routers/target/updateTarget.ts index a633deb4d..92c434a19 100644 --- a/server/routers/target/updateTarget.ts +++ b/server/routers/target/updateTarget.ts @@ -10,10 +10,10 @@ import logger from "@server/logger"; import { fromError } from "zod-validation-error"; import { addPeer } from "../gerbil/peers"; import { addTargets } from "../newt/targets"; +import { fireHealthCheckHealthyAlert, fireHealthCheckUnknownAlert, fireHealthCheckUnhealthyAlert } from "#dynamic/lib/alerts"; import { pickPort } from "./helpers"; import { isTargetValid } from "@server/lib/validators"; import { OpenAPITags, registry } from "@server/openApi"; -import { vs } from "@react-email/components"; const updateTargetParamsSchema = z.strictObject({ targetId: z.string().transform(Number).pipe(z.int().positive()) @@ -153,32 +153,6 @@ export async function updateTarget( ); } - const targetData = { - ...target, - ...parsedBody.data - }; - - const existingTargets = await db - .select() - .from(targets) - .where(eq(targets.resourceId, target.resourceId)); - - const foundTarget = existingTargets.find( - (target) => - target.targetId !== targetId && // Exclude the current target being updated - target.ip === targetData.ip && - target.port === targetData.port && - target.method === targetData.method && - target.siteId === targetData.siteId - ); - - if (foundTarget) { - // log a warning - logger.warn( - `Target with IP ${targetData.ip}, port ${targetData.port}, method ${targetData.method} already exists for resource ID ${target.resourceId}` - ); - } - const { internalPort, targetIps } = await pickPort(site.siteId!, db); if (!internalPort) { @@ -192,63 +166,135 @@ export async function updateTarget( const pathMatchTypeRemoved = parsedBody.data.pathMatchType === null; - const [updatedTarget] = await db - .update(targets) - .set({ - siteId: parsedBody.data.siteId, - ip: parsedBody.data.ip, - method: parsedBody.data.method, - port: parsedBody.data.port, - internalPort, - enabled: parsedBody.data.enabled, - path: parsedBody.data.path, - pathMatchType: parsedBody.data.pathMatchType, - priority: parsedBody.data.priority, - rewritePath: pathMatchTypeRemoved ? null : parsedBody.data.rewritePath, - rewritePathType: pathMatchTypeRemoved ? null : parsedBody.data.rewritePathType - }) - .where(eq(targets.targetId, targetId)) - .returning(); + let updatedTarget: any; + let updatedHc: any; + await db.transaction(async (trx) => { + [updatedTarget] = await trx + .update(targets) + .set({ + siteId: parsedBody.data.siteId, + ip: parsedBody.data.ip, + method: parsedBody.data.method, + port: parsedBody.data.port, + internalPort, + enabled: parsedBody.data.enabled, + path: parsedBody.data.path, + pathMatchType: parsedBody.data.pathMatchType, + priority: parsedBody.data.priority, + rewritePath: pathMatchTypeRemoved ? null : parsedBody.data.rewritePath, + rewritePathType: pathMatchTypeRemoved ? null : parsedBody.data.rewritePathType + }) + .where(eq(targets.targetId, targetId)) + .returning(); - let hcHeaders = null; - if (parsedBody.data.hcHeaders) { - hcHeaders = JSON.stringify(parsedBody.data.hcHeaders); - } + const [existingHc] = await trx + .select() + .from(targetHealthCheck) + .where(eq(targetHealthCheck.targetId, targetId)) + .limit(1); - // When health check is disabled, reset hcHealth to "unknown" - // to prevent previously unhealthy targets from being excluded - // Also when the site is not a newt, set hcHealth to "unknown" - const hcHealthValue = - parsedBody.data.hcEnabled === false || - parsedBody.data.hcEnabled === null || - site.type !== "newt" - ? "unknown" - : undefined; + if (!existingHc) { + return next( + createHttpError( + HttpCode.NOT_FOUND, + `Health check for target with ID ${targetId} not found` + ) + ); + } - const [updatedHc] = await db - .update(targetHealthCheck) - .set({ - siteId: parsedBody.data.siteId, - hcEnabled: parsedBody.data.hcEnabled || false, - hcPath: parsedBody.data.hcPath, - hcScheme: parsedBody.data.hcScheme, - hcMode: parsedBody.data.hcMode, - hcHostname: parsedBody.data.hcHostname, - hcPort: parsedBody.data.hcPort, - hcInterval: parsedBody.data.hcInterval, - hcUnhealthyInterval: parsedBody.data.hcUnhealthyInterval, - hcTimeout: parsedBody.data.hcTimeout, - hcHeaders: hcHeaders, - hcFollowRedirects: parsedBody.data.hcFollowRedirects, - 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)) - .returning(); + let hcHeaders = null; + if (parsedBody.data.hcHeaders) { + hcHeaders = JSON.stringify(parsedBody.data.hcHeaders); + } + + // When health check is disabled, reset hcHealth to "unknown" + // to prevent previously unhealthy targets from being excluded. + // Also when the site is not a newt, set hcHealth to "unknown". + // If hcEnabled is being turned on (was false, now true), set to "unhealthy" + // so the target must pass a health check before being considered healthy. + const hcEnabledTurnedOn = + parsedBody.data.hcEnabled === true && existingHc.hcEnabled === false; + + let hcHealthValue: "unknown" | "healthy" | "unhealthy" | undefined; + if ( + parsedBody.data.hcEnabled === false || + parsedBody.data.hcEnabled === null || + site.type !== "newt" + ) { + hcHealthValue = "unknown"; + } else if (hcEnabledTurnedOn) { + hcHealthValue = "unhealthy"; + } else { + hcHealthValue = undefined; + } + + [updatedHc] = await trx + .update(targetHealthCheck) + .set({ + siteId: parsedBody.data.siteId, + hcEnabled: parsedBody.data.hcEnabled || false, + hcPath: parsedBody.data.hcPath, + hcScheme: parsedBody.data.hcScheme, + hcMode: parsedBody.data.hcMode, + hcHostname: parsedBody.data.hcHostname, + hcPort: parsedBody.data.hcPort, + hcInterval: parsedBody.data.hcInterval, + hcUnhealthyInterval: parsedBody.data.hcUnhealthyInterval, + hcTimeout: parsedBody.data.hcTimeout, + hcHeaders: hcHeaders, + hcFollowRedirects: parsedBody.data.hcFollowRedirects, + hcMethod: parsedBody.data.hcMethod, + hcStatus: parsedBody.data.hcStatus, + hcTlsServerName: parsedBody.data.hcTlsServerName, + hcHealthyThreshold: parsedBody.data.hcHealthyThreshold, + hcUnhealthyThreshold: parsedBody.data.hcUnhealthyThreshold, + hcHealth: hcHealthValue + }) + .where(eq(targetHealthCheck.targetId, targetId)) + .returning(); + + if (updatedHc.hcHealth === "unhealthy" && existingHc.hcHealth !== "unhealthy") { + logger.debug( + `Health check ${updatedHc.targetHealthCheckId} for target ${targetId} is now unhealthy, firing alert` + ); + await fireHealthCheckUnhealthyAlert( + updatedHc.orgId, + updatedHc.targetHealthCheckId, + updatedHc.name || "", + updatedHc.targetId, + undefined, + false, // dont send the alert because we just want to create the alert, not notify users yet + trx + ); + } else if (updatedHc.hcHealth === "unknown" && existingHc.hcHealth !== "unknown") { + logger.debug( + `Health check ${updatedHc.targetHealthCheckId} for target ${targetId} is now unknown, firing alert` + ); + // if the health is unknown, we want to fire an alert to notify users to enable health checks + await fireHealthCheckUnknownAlert( + updatedHc.orgId, + updatedHc.targetHealthCheckId, + updatedHc.name, + updatedHc.targetId, + undefined, + false, // dont send the alert because we just want to create the alert, not notify users yet + trx + ); + } else if (updatedHc.hcHealth === "healthy" && existingHc.hcHealth !== "healthy") { + logger.debug( + `Health check ${updatedHc.targetHealthCheckId} for target ${targetId} is now healthy, firing alert` + ); + await fireHealthCheckHealthyAlert( + updatedHc.orgId, + updatedHc.targetHealthCheckId, + updatedHc.name, + updatedHc.targetId, + undefined, + false, // dont send the alert because we just want to create the alert, not notify users yet + trx + ); + } + }); if (site.pubKey) { if (site.type == "wireguard") { @@ -273,6 +319,7 @@ export async function updateTarget( ); } } + return response(res, { data: { ...updatedTarget, diff --git a/server/setup/scriptsPg/1.18.0.ts b/server/setup/scriptsPg/1.18.0.ts index 2f2b3067c..df22faa2d 100644 --- a/server/setup/scriptsPg/1.18.0.ts +++ b/server/setup/scriptsPg/1.18.0.ts @@ -67,11 +67,12 @@ export default async function migration() { FROM "siteResources" sr WHERE sr."siteId" IS NOT NULL` ); - const existingSiteResourcesForNetwork = siteResourcesForNetworkQuery.rows as { - siteResourceId: number; - orgId: string; - siteId: number; - }[]; + const existingSiteResourcesForNetwork = + siteResourcesForNetworkQuery.rows as { + siteResourceId: number; + orgId: string; + siteId: number; + }[]; console.log( `Found ${existingSiteResourcesForNetwork.length} existing siteResource(s) to migrate to networks` @@ -346,6 +347,14 @@ export default async function migration() { ALTER TABLE "siteResources" DROP COLUMN "protocol"; `); + await db.execute(sql` + ALTER TABLE "resources" ADD "health" varchar DEFAULT 'unknown'; + `); + + await db.execute(sql` + ALTER TABLE "resources" ADD "wildcard" boolean DEFAULT false NOT NULL; + `); + await db.execute(sql`COMMIT`); console.log("Migrated database"); } catch (e) { @@ -438,10 +447,7 @@ export default async function migration() { `Migrated ${existingHealthChecks.length} targetHealthCheck row(s) with corrected IDs` ); } catch (e) { - console.error( - "Error while migrating targetHealthCheck rows:", - e - ); + console.error("Error while migrating targetHealthCheck rows:", e); throw e; } } @@ -485,5 +491,156 @@ export default async function migration() { } } + // Seed statusHistory for all existing sites + try { + const sitesQuery = await db.execute( + sql`SELECT "siteId", "orgId", "online" FROM "sites"` + ); + const allSites = sitesQuery.rows as { + siteId: number; + orgId: string; + online: boolean; + }[]; + + const now = Math.floor(Date.now() / 1000); + + for (const site of allSites) { + await db.execute(sql` + INSERT INTO "statusHistory" ("entityType", "entityId", "orgId", "status", "timestamp") + VALUES ('site', ${site.siteId}, ${site.orgId}, ${site.online ? "online" : "offline"}, ${now}) + `); + } + + console.log(`Seeded statusHistory for ${allSites.length} site(s)`); + } catch (e) { + console.error("Error while seeding statusHistory for sites:", e); + throw e; + } + + // Seed statusHistory for all existing resources + try { + const resourcesQuery = await db.execute( + sql`SELECT "resourceId", "orgId", "health" FROM "resources"` + ); + const allResources = resourcesQuery.rows as { + resourceId: number; + orgId: string; + health: string | null; + }[]; + + const now = Math.floor(Date.now() / 1000); + + for (const resource of allResources) { + await db.execute(sql` + INSERT INTO "statusHistory" ("entityType", "entityId", "orgId", "status", "timestamp") + VALUES ('resource', ${resource.resourceId}, ${resource.orgId}, ${resource.health ?? "unknown"}, ${now}) + `); + } + + console.log( + `Seeded statusHistory for ${allResources.length} resource(s)` + ); + } catch (e) { + console.error("Error while seeding statusHistory for resources:", e); + throw e; + } + + // Recompute resource health by aggregating across the resource's targets' + // target health checks, then update the resources.health column to match. + try { + const resourceTargetHealthQuery = await db.execute( + sql`SELECT + r."resourceId" AS "resourceId", + thc."hcHealth" AS "hcHealth" + FROM "resources" r + LEFT JOIN "targets" t ON t."resourceId" = r."resourceId" + LEFT JOIN "targetHealthCheck" thc ON thc."targetId" = t."targetId"` + ); + const resourceTargetHealthRows = + resourceTargetHealthQuery.rows as { + resourceId: number; + hcHealth: string | null; + }[]; + + const resourceHealthMap = new Map< + number, + { hasHealthy: boolean; hasUnhealthy: boolean; hasUnknown: boolean } + >(); + for (const row of resourceTargetHealthRows) { + const entry = resourceHealthMap.get(row.resourceId) ?? { + hasHealthy: false, + hasUnhealthy: false, + hasUnknown: false + }; + const status = row.hcHealth ?? "unknown"; + if (status === "healthy") entry.hasHealthy = true; + else if (status === "unhealthy") entry.hasUnhealthy = true; + else entry.hasUnknown = true; + resourceHealthMap.set(row.resourceId, entry); + } + + let updatedResourceCount = 0; + for (const [resourceId, flags] of resourceHealthMap.entries()) { + let aggregated: "healthy" | "unhealthy" | "degraded" | "unknown"; + if (flags.hasHealthy && flags.hasUnhealthy) { + aggregated = "degraded"; + } else if (flags.hasHealthy) { + aggregated = "healthy"; + } else if (flags.hasUnhealthy) { + aggregated = "unhealthy"; + } else { + aggregated = "unknown"; + } + + await db.execute(sql` + UPDATE "resources" + SET "health" = ${aggregated} + WHERE "resourceId" = ${resourceId} + `); + updatedResourceCount++; + } + + console.log( + `Recomputed health for ${updatedResourceCount} resource(s) based on target health checks` + ); + } catch (e) { + console.error( + "Error while recomputing resource health from target health checks:", + e + ); + throw e; + } + + // Seed statusHistory for all existing health checks + try { + const healthChecksQuery = await db.execute( + sql`SELECT "targetHealthCheckId", "orgId", "hcHealth" FROM "targetHealthCheck"` + ); + const allHealthChecks = healthChecksQuery.rows as { + targetHealthCheckId: number; + orgId: string; + hcHealth: string | null; + }[]; + + const now = Math.floor(Date.now() / 1000); + + for (const hc of allHealthChecks) { + await db.execute(sql` + INSERT INTO "statusHistory" ("entityType", "entityId", "orgId", "status", "timestamp") + VALUES ('health_check', ${hc.targetHealthCheckId}, ${hc.orgId}, ${hc.hcHealth ?? "unknown"}, ${now}) + `); + } + + console.log( + `Seeded statusHistory for ${allHealthChecks.length} health check(s)` + ); + } catch (e) { + console.error( + "Error while seeding statusHistory for health checks:", + 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 index c9d2ddc95..49ee8c450 100644 --- a/server/setup/scriptsSqlite/1.18.0.ts +++ b/server/setup/scriptsSqlite/1.18.0.ts @@ -255,7 +255,7 @@ export default async function migration() { ).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'; + 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", COALESCE("tcpPortRangeString", '*'), COALESCE("udpPortRangeString", '*'), COALESCE("disableIcmp", 0), "authDaemonPort", "authDaemonMode", NULL, NULL, NULL FROM 'siteResources'; ` ).run(); db.prepare( @@ -330,6 +330,16 @@ export default async function migration() { ALTER TABLE 'sites' ADD 'networkId' integer REFERENCES networks(networkId); ` ).run(); + db.prepare( + ` + ALTER TABLE 'resources' ADD 'health' text DEFAULT 'unknown'; + ` + ).run(); + db.prepare( + ` + ALTER TABLE 'resources' ADD 'wildcard' integer DEFAULT false NOT NULL; + ` + ).run(); })(); db.pragma("foreign_keys = ON"); @@ -353,7 +363,11 @@ export default async function migration() { const result = insertNetwork.run("resource", sr.orgId); const networkId = result.lastInsertRowid as number; insertSiteNetwork.run(sr.siteId, networkId); - updateSiteResource.run(networkId, networkId, sr.siteResourceId); + updateSiteResource.run( + networkId, + networkId, + sr.siteResourceId + ); } }); @@ -443,6 +457,151 @@ export default async function migration() { } console.log(`Migrated database`); + + // Seed statusHistory for all existing sites + const allSites = db + .prepare(`SELECT "siteId", "orgId", "online" FROM 'sites'`) + .all() as { siteId: number; orgId: string; online: number }[]; + + const insertSiteHistory = db.prepare( + `INSERT INTO 'statusHistory' ("entityType", "entityId", "orgId", "status", "timestamp") VALUES (?, ?, ?, ?, ?)` + ); + const now = Math.floor(Date.now() / 1000); + const seedSites = db.transaction(() => { + for (const site of allSites) { + insertSiteHistory.run( + "site", + site.siteId, + site.orgId, + site.online ? "online" : "offline", + now + ); + } + }); + seedSites(); + console.log(`Seeded statusHistory for ${allSites.length} site(s)`); + + // Seed statusHistory for all existing resources + const allResources = db + .prepare(`SELECT "resourceId", "orgId", "health" FROM 'resources'`) + .all() as { + resourceId: number; + orgId: string; + health: string | null; + }[]; + + const insertResourceHistory = db.prepare( + `INSERT INTO 'statusHistory' ("entityType", "entityId", "orgId", "status", "timestamp") VALUES (?, ?, ?, ?, ?)` + ); + const seedResources = db.transaction(() => { + for (const resource of allResources) { + insertResourceHistory.run( + "resource", + resource.resourceId, + resource.orgId, + resource.health ?? "unknown", + now + ); + } + }); + seedResources(); + console.log( + `Seeded statusHistory for ${allResources.length} resource(s)` + ); + + // Recompute resource health by aggregating across the resource's + // targets' target health checks, then update resources.health. + const resourceTargetHealthRows = db + .prepare( + `SELECT + r."resourceId" AS "resourceId", + thc."hcHealth" AS "hcHealth" + FROM 'resources' r + LEFT JOIN 'targets' t ON t."resourceId" = r."resourceId" + LEFT JOIN 'targetHealthCheck' thc ON thc."targetId" = t."targetId"` + ) + .all() as { + resourceId: number; + hcHealth: string | null; + }[]; + + const resourceHealthMap = new Map< + number, + { + hasHealthy: boolean; + hasUnhealthy: boolean; + hasUnknown: boolean; + } + >(); + for (const row of resourceTargetHealthRows) { + const entry = resourceHealthMap.get(row.resourceId) ?? { + hasHealthy: false, + hasUnhealthy: false, + hasUnknown: false + }; + const status = row.hcHealth ?? "unknown"; + if (status === "healthy") entry.hasHealthy = true; + else if (status === "unhealthy") entry.hasUnhealthy = true; + else entry.hasUnknown = true; + resourceHealthMap.set(row.resourceId, entry); + } + + const updateResourceHealth = db.prepare( + `UPDATE 'resources' SET "health" = ? WHERE "resourceId" = ?` + ); + const recomputeResourceHealth = db.transaction(() => { + for (const [resourceId, flags] of resourceHealthMap.entries()) { + let aggregated: + | "healthy" + | "unhealthy" + | "degraded" + | "unknown"; + if (flags.hasHealthy && flags.hasUnhealthy) { + aggregated = "degraded"; + } else if (flags.hasHealthy) { + aggregated = "healthy"; + } else if (flags.hasUnhealthy) { + aggregated = "unhealthy"; + } else { + aggregated = "unknown"; + } + updateResourceHealth.run(aggregated, resourceId); + } + }); + recomputeResourceHealth(); + console.log( + `Recomputed health for ${resourceHealthMap.size} resource(s) based on target health checks` + ); + + // Seed statusHistory for all existing health checks + const allHealthChecks = db + .prepare( + `SELECT "targetHealthCheckId", "orgId", "hcHealth" FROM 'targetHealthCheck'` + ) + .all() as { + targetHealthCheckId: number; + orgId: string; + hcHealth: string | null; + }[]; + + const insertHealthCheckHistory = db.prepare( + `INSERT INTO 'statusHistory' ("entityType", "entityId", "orgId", "status", "timestamp") VALUES (?, ?, ?, ?, ?)` + ); + const seedHealthChecks = db.transaction(() => { + for (const hc of allHealthChecks) { + insertHealthCheckHistory.run( + "health_check", + hc.targetHealthCheckId, + hc.orgId, + hc.hcHealth ?? "unknown", + now + ); + } + }); + seedHealthChecks(); + console.log( + `Seeded statusHistory for ${allHealthChecks.length} health check(s)` + ); } catch (e) { console.log("Failed to migrate db:", e); throw e; diff --git a/src/app/[orgId]/settings/(private)/billing/page.tsx b/src/app/[orgId]/settings/(private)/billing/page.tsx index 8f714336a..778062e8e 100644 --- a/src/app/[orgId]/settings/(private)/billing/page.tsx +++ b/src/app/[orgId]/settings/(private)/billing/page.tsx @@ -836,7 +836,14 @@ export default function BillingPage() { {/* Plan Cards Grid */} -
+
{visiblePlanOptions.map((plan) => { const isCurrentPlan = plan.id === currentPlanId; const planAction = getPlanAction(plan); @@ -967,7 +974,7 @@ export default function BillingPage() { {t("billingCurrentUsage") || "Current Usage"}
- + {getUserCount()} @@ -1298,7 +1305,7 @@ export default function BillingPage() { "Current Keys"}
- + {getLicenseKeyCount()} diff --git a/src/app/[orgId]/settings/alerting/(list)/health-checks/page.tsx b/src/app/[orgId]/settings/alerting/(list)/health-checks/page.tsx index 5cbb9ea3d..f3cf0160f 100644 --- a/src/app/[orgId]/settings/alerting/(list)/health-checks/page.tsx +++ b/src/app/[orgId]/settings/alerting/(list)/health-checks/page.tsx @@ -151,6 +151,7 @@ export default async function AlertingHealthChecksPage( fullDomain: string | null; niceId: string; ssl: boolean; + wildcard: boolean; } | null = null; if (resourceIdParam) { try { @@ -165,7 +166,8 @@ export default async function AlertingHealthChecksPage( resourceId: r.resourceId, fullDomain: r.fullDomain, niceId: r.niceId, - ssl: r.ssl + ssl: r.ssl, + wildcard: r.wildcard }; } } catch { diff --git a/src/app/[orgId]/settings/clients/user/page.tsx b/src/app/[orgId]/settings/clients/user/page.tsx index 23fba583a..880019177 100644 --- a/src/app/[orgId]/settings/clients/user/page.tsx +++ b/src/app/[orgId]/settings/clients/user/page.tsx @@ -96,6 +96,9 @@ export default async function ClientsPage(props: ClientsPageProps) { userId: client.userId, username: client.username, userEmail: client.userEmail, + userType: client.userType ?? null, + idpName: client.idpName ?? null, + idpVariant: client.idpVariant ?? null, niceId: client.niceId, agent: client.agent, archived: Boolean(client.archived), diff --git a/src/app/[orgId]/settings/not-found.tsx b/src/app/[orgId]/settings/not-found.tsx index d3ca37ccf..680962d23 100644 --- a/src/app/[orgId]/settings/not-found.tsx +++ b/src/app/[orgId]/settings/not-found.tsx @@ -5,7 +5,7 @@ export default async function NotFound() { return (
-

404

+

404

{t("pageNotFound")}

diff --git a/src/app/[orgId]/settings/provisioning/pending/page.tsx b/src/app/[orgId]/settings/provisioning/pending/page.tsx index ee7246821..a85b0d7d9 100644 --- a/src/app/[orgId]/settings/provisioning/pending/page.tsx +++ b/src/app/[orgId]/settings/provisioning/pending/page.tsx @@ -69,6 +69,7 @@ export default async function PendingSitesPage(props: PendingSitesPageProps) { address: site.address?.split("/")[0], mbIn: formatSize(site.megabytesIn || 0, site.type), mbOut: formatSize(site.megabytesOut || 0, site.type), + resourceCount: Number(site.resourceCount ?? 0), orgId: params.orgId, type: site.type as any, online: site.online, diff --git a/src/app/[orgId]/settings/resources/client/page.tsx b/src/app/[orgId]/settings/resources/client/page.tsx index da967feea..42d4e69eb 100644 --- a/src/app/[orgId]/settings/resources/client/page.tsx +++ b/src/app/[orgId]/settings/resources/client/page.tsx @@ -7,7 +7,9 @@ import { authCookieHeader } from "@app/lib/api/cookies"; import { getCachedOrg } from "@app/lib/api/getCachedOrg"; import OrgProvider from "@app/providers/OrgProvider"; import type { ListResourcesResponse } from "@server/routers/resource"; +import { GetSiteResponse } from "@server/routers/site/getSite"; import type { ListAllSiteResourcesByOrgResponse } from "@server/routers/siteResource"; +import type ResponseT from "@server/types/Response"; import type { AxiosResponse } from "axios"; import { getTranslations } from "next-intl/server"; import type { Metadata } from "next"; @@ -22,6 +24,13 @@ export interface ClientResourcesPageProps { searchParams: Promise>; } +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 ClientResourcesPage( props: ClientResourcesPageProps ) { @@ -47,6 +56,32 @@ export default async function ClientResourcesPage( pagination = responseData.pagination; } catch (e) {} + const siteIdParam = parsePositiveInt(searchParams.get("siteId") ?? undefined); + + let initialFilterSite: { + siteId: number; + name: string; + type: string; + } | null = null; + if (siteIdParam) { + try { + const siteRes = await internal.get( + `/site/${siteIdParam}`, + await authCookieHeader() + ); + 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 org = null; try { const res = await getCachedOrg(params.orgId); @@ -114,6 +149,7 @@ export default async function ClientResourcesPage( pageIndex: pagination.page - 1, pageSize: pagination.pageSize }} + initialFilterSite={initialFilterSite} /> 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 2b87da745..62a6b9fed 100644 --- a/src/app/[orgId]/settings/resources/proxy/[niceId]/general/page.tsx +++ b/src/app/[orgId]/settings/resources/proxy/[niceId]/general/page.tsx @@ -29,6 +29,7 @@ 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 } from "lucide-react"; @@ -506,7 +507,7 @@ export default function GeneralForm() { name: data.name, niceId: data.niceId, subdomain: data.subdomain - ? toASCII(data.subdomain) + ? toASCII(finalizeSubdomainSanitize(data.subdomain, true)) : undefined, domainId: data.domainId, proxyPort: data.proxyPort @@ -670,6 +671,7 @@ export default function GeneralForm() {
)} + {build === "saas" && + targets.length > 1 && + new Set(targets.map((t) => t.siteId)).size > 1 && ( +

+ + + Round robin routing will not work between + sites that are not connected to the same + node, but failover will work. + +

+ )}
diff --git a/src/app/[orgId]/settings/resources/proxy/create/page.tsx b/src/app/[orgId]/settings/resources/proxy/create/page.tsx index 1c9e5b1bb..8eae652cd 100644 --- a/src/app/[orgId]/settings/resources/proxy/create/page.tsx +++ b/src/app/[orgId]/settings/resources/proxy/create/page.tsx @@ -488,7 +488,7 @@ export default function Page() { const httpData = httpForm.getValues(); sanitizedSubdomain = httpData.subdomain - ? finalizeSubdomainSanitize(httpData.subdomain) + ? finalizeSubdomainSanitize(httpData.subdomain, true) : undefined; Object.assign(payload, { @@ -694,19 +694,6 @@ export default function Page() { 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) { @@ -720,19 +707,7 @@ export default function Page() { } }; - const getStatusIcon = (status: string) => { - switch (status) { - case "healthy": - return ; - case "unhealthy": - return ; - case "unknown": - default: - return null; - } - }; - - return ( + return (
{row.original.siteType === "newt" ? ( + ) : ( - )} @@ -1132,6 +1111,7 @@ export default function Page() { = 1 @@ -1439,6 +1419,18 @@ export default function Page() {
)} + {build === "enterprise" && + targets.length > 1 && + new Set(targets.map((t) => t.siteId)).size > 1 && ( +

+ + + Round robin routing will not work between + sites that are not connected to the same + node, but failover will work. + +

+ )} diff --git a/src/app/[orgId]/settings/resources/proxy/page.tsx b/src/app/[orgId]/settings/resources/proxy/page.tsx index cdbf959f4..0bbc8aa66 100644 --- a/src/app/[orgId]/settings/resources/proxy/page.tsx +++ b/src/app/[orgId]/settings/resources/proxy/page.tsx @@ -7,7 +7,8 @@ import { authCookieHeader } from "@app/lib/api/cookies"; import OrgProvider from "@app/providers/OrgProvider"; import type { GetOrgResponse } from "@server/routers/org"; import type { ListResourcesResponse } from "@server/routers/resource"; -import type { ListAllSiteResourcesByOrgResponse } from "@server/routers/siteResource"; +import { GetSiteResponse } from "@server/routers/site/getSite"; +import type ResponseT from "@server/types/Response"; import type { AxiosResponse } from "axios"; import { getTranslations } from "next-intl/server"; import { redirect } from "next/navigation"; @@ -24,6 +25,13 @@ export interface ProxyResourcesPageProps { searchParams: Promise>; } +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 ProxyResourcesPage( props: ProxyResourcesPageProps ) { @@ -47,13 +55,31 @@ export default async function ProxyResourcesPage( pagination = responseData.pagination; } catch (e) {} - let siteResources: ListAllSiteResourcesByOrgResponse["siteResources"] = []; - try { - const res = await internal.get< - AxiosResponse - >(`/org/${params.orgId}/site-resources`, await authCookieHeader()); - siteResources = res.data.data.siteResources; - } catch (e) {} + const siteIdParam = parsePositiveInt(searchParams.get("siteId") ?? undefined); + + let initialFilterSite: { + siteId: number; + name: string; + type: string; + } | null = null; + if (siteIdParam) { + try { + const siteRes = await internal.get( + `/site/${siteIdParam}`, + await authCookieHeader() + ); + 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 org = null; try { @@ -94,6 +120,7 @@ export default async function ProxyResourcesPage( : "not_protected", enabled: resource.enabled, domainId: resource.domainId || undefined, + fullDomain: resource.fullDomain ?? null, ssl: resource.ssl, targets: resource.targets?.map((target) => ({ targetId: target.targetId, @@ -102,7 +129,9 @@ export default async function ProxyResourcesPage( enabled: target.enabled, healthStatus: target.healthStatus, siteName: target.siteName - })) + })), + sites: resource.sites ?? [], + health: (resource.health as ResourceRow["health"]) ?? undefined }; }); return ( @@ -123,6 +152,7 @@ export default async function ProxyResourcesPage( pageIndex: pagination.page - 1, pageSize: pagination.pageSize }} + initialFilterSite={initialFilterSite} /> diff --git a/src/app/[orgId]/settings/sites/[niceId]/layout.tsx b/src/app/[orgId]/settings/sites/[niceId]/layout.tsx index d5e11e9bc..ba65d06e0 100644 --- a/src/app/[orgId]/settings/sites/[niceId]/layout.tsx +++ b/src/app/[orgId]/settings/sites/[niceId]/layout.tsx @@ -42,6 +42,10 @@ export default async function SettingsLayout(props: SettingsLayoutProps) { title: t("general"), href: `/${params.orgId}/settings/sites/${params.niceId}/general` }, + { + title: t("siteResourcesTab"), + href: `/${params.orgId}/settings/sites/${params.niceId}/resources` + }, ...(site.type !== "local" ? [ { diff --git a/src/app/[orgId]/settings/sites/[niceId]/resources/page.tsx b/src/app/[orgId]/settings/sites/[niceId]/resources/page.tsx new file mode 100644 index 000000000..fcb460b87 --- /dev/null +++ b/src/app/[orgId]/settings/sites/[niceId]/resources/page.tsx @@ -0,0 +1,64 @@ +import SiteResourcesOverview from "@app/components/SiteResourcesOverview"; +import { internal } from "@app/lib/api"; +import { authCookieHeader } from "@app/lib/api/cookies"; +import type { ListResourcesResponse } from "@server/routers/resource"; +import type { GetSiteResponse } from "@server/routers/site"; +import type { ListAllSiteResourcesByOrgResponse } from "@server/routers/siteResource"; +import type { AxiosResponse } from "axios"; + +type SiteResourcesPageProps = { + params: Promise<{ orgId: string; niceId: string }>; +}; + +export default async function SiteResourcesPage(props: SiteResourcesPageProps) { + const { orgId, niceId } = await props.params; + + const siteRes = await internal.get>( + `/org/${orgId}/site/${niceId}`, + await authCookieHeader() + ); + const site = siteRes.data.data; + + const baseSearch = new URLSearchParams({ + page: "1", + pageSize: "5", + siteId: String(site.siteId) + }); + + let initialPublicData: ListResourcesResponse | null = null; + let initialPrivateData: ListAllSiteResourcesByOrgResponse | null = null; + let initialPublicForbidden = false; + let initialPrivateForbidden = false; + + try { + const res = await internal.get>( + `/org/${orgId}/resources?${baseSearch.toString()}`, + await authCookieHeader() + ); + initialPublicData = res.data.data; + } catch (e: any) { + initialPublicForbidden = e?.response?.status === 403; + } + + try { + const res = await internal.get< + AxiosResponse + >( + `/org/${orgId}/site-resources?${baseSearch.toString()}`, + await authCookieHeader() + ); + initialPrivateData = res.data.data; + } catch (e: any) { + initialPrivateForbidden = e?.response?.status === 403; + } + + return ( + + ); +} diff --git a/src/app/[orgId]/settings/sites/page.tsx b/src/app/[orgId]/settings/sites/page.tsx index d78666d78..631baee41 100644 --- a/src/app/[orgId]/settings/sites/page.tsx +++ b/src/app/[orgId]/settings/sites/page.tsx @@ -64,6 +64,7 @@ export default async function SitesPage(props: SitesPageProps) { address: site.address?.split("/")[0], mbIn: formatSize(site.megabytesIn || 0, site.type), mbOut: formatSize(site.megabytesOut || 0, site.type), + resourceCount: Number(site.resourceCount ?? 0), orgId: params.orgId, type: site.type as any, online: site.online, diff --git a/src/app/admin/users/AdminUsersTable.tsx b/src/app/admin/users/AdminUsersTable.tsx new file mode 100644 index 000000000..1c7d1b7fd --- /dev/null +++ b/src/app/admin/users/AdminUsersTable.tsx @@ -0,0 +1,264 @@ +"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/auth/initial-setup/page.tsx b/src/app/auth/initial-setup/page.tsx index 4a4438964..bf38eee9e 100644 --- a/src/app/auth/initial-setup/page.tsx +++ b/src/app/auth/initial-setup/page.tsx @@ -92,7 +92,7 @@ export default function InitialSetupPage() { />
-

+

{t("initialSetupTitle")}

diff --git a/src/app/auth/login/device/success/page.tsx b/src/app/auth/login/device/success/page.tsx index dab609351..56f84c835 100644 --- a/src/app/auth/login/device/success/page.tsx +++ b/src/app/auth/login/device/success/page.tsx @@ -23,8 +23,10 @@ export default function DeviceAuthSuccessPage() { useEffect(() => { // Detect if we're on iOS or Android - const userAgent = navigator.userAgent || navigator.vendor || (window as any).opera; - const isIOS = /iPad|iPhone|iPod/.test(userAgent) && !(window as any).MSStream; + const userAgent = + navigator.userAgent || navigator.vendor || (window as any).opera; + const isIOS = + /iPad|iPhone|iPod/.test(userAgent) && !(window as any).MSStream; const isAndroid = /android/i.test(userAgent); if (isAndroid) { @@ -32,7 +34,8 @@ export default function DeviceAuthSuccessPage() { // This explicitly tells Chrome to send an intent to the app, which will bring // SignInCodeActivity back to the foreground (it has launchMode="singleTop") setTimeout(() => { - window.location.href = "intent://auth-success#Intent;scheme=pangolin;package=net.pangolin.Pangolin;end"; + window.location.href = + "intent://auth-success#Intent;scheme=pangolin;package=net.pangolin.Pangolin;end"; }, 500); } else if (isIOS) { // Wait 500ms then attempt to open the app @@ -41,7 +44,8 @@ export default function DeviceAuthSuccessPage() { window.location.href = "pangolin://"; setTimeout(() => { - window.location.href = "https://apps.apple.com/app/pangolin/net.pangolin.Pangolin.PangoliniOS"; + window.location.href = + "https://apps.apple.com/app/pangolin/net.pangolin.Pangolin.PangoliniOS"; }, 2000); }, 500); } @@ -64,7 +68,7 @@ export default function DeviceAuthSuccessPage() {
-

+

{t("deviceConnected")}

diff --git a/src/app/auth/login/page.tsx b/src/app/auth/login/page.tsx index 9b1639925..c2aaefaa6 100644 --- a/src/app/auth/login/page.tsx +++ b/src/app/auth/login/page.tsx @@ -135,7 +135,7 @@ export default async function Page(props: {

-

+

{t("inviteAlready")}

diff --git a/src/app/auth/resource/[resourceGuid]/page.tsx b/src/app/auth/resource/[resourceGuid]/page.tsx index f22a59d6b..c78c277b6 100644 --- a/src/app/auth/resource/[resourceGuid]/page.tsx +++ b/src/app/auth/resource/[resourceGuid]/page.tsx @@ -106,10 +106,22 @@ export default async function ResourceAuthPage(props: { const redirectPort = new URL(searchParams.redirect).port; const serverResourceHostWithPort = `${serverResourceHost}:${redirectPort}`; + const wildcardMatchesRedirect = (wildcardDomain: string, host: string): boolean => { + if (!wildcardDomain.startsWith("*.")) return false; + const suffix = wildcardDomain.slice(1); // e.g. ".wildcard.owen.fosrl.io" + return host.endsWith(suffix) && host.length > suffix.length; + }; + if (serverResourceHost === redirectHost) { redirectUrl = searchParams.redirect; } else if (serverResourceHostWithPort === redirectHost) { redirectUrl = searchParams.redirect; + } else if ( + authInfo.wildcard && + authInfo.fullDomain && + wildcardMatchesRedirect(authInfo.fullDomain, redirectHost) + ) { + redirectUrl = searchParams.redirect; } } catch (e) {} } diff --git a/src/app/auth/signup/page.tsx b/src/app/auth/signup/page.tsx index be138c45d..42829acfd 100644 --- a/src/app/auth/signup/page.tsx +++ b/src/app/auth/signup/page.tsx @@ -65,7 +65,7 @@ export default async function Page(props: {

-

+

{t("inviteAlready")}

diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 9cf66dd28..d04cc0b6e 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, Mona_Sans } from "next/font/google"; +import localFont from "next/font/local"; export const metadata: Metadata = { title: `Dashboard - ${process.env.BRANDING_APP_NAME || "Pangolin"}`, @@ -32,12 +32,30 @@ export const metadata: Metadata = { export const dynamic = "force-dynamic"; -const inter = Inter({ - subsets: ["latin"] -}); - -const monaSans = Mona_Sans({ - subsets: ["latin"] +const monaSans = localFont({ + src: [ + { + path: "../fonts/mona-sans/MonaSans-Regular.woff2", + weight: "400", + style: "normal" + }, + { + path: "../fonts/mona-sans/MonaSans-Medium.woff2", + weight: "500", + style: "normal" + }, + { + path: "../fonts/mona-sans/MonaSans-SemiBold.woff2", + weight: "600", + style: "normal" + }, + { + path: "../fonts/mona-sans/MonaSans-Bold.woff2", + weight: "700", + style: "normal" + } + ], + display: "swap" }); const fontClassName = monaSans.className; diff --git a/src/app/not-found.tsx b/src/app/not-found.tsx index d3ca37ccf..680962d23 100644 --- a/src/app/not-found.tsx +++ b/src/app/not-found.tsx @@ -5,7 +5,7 @@ export default async function NotFound() { return (

-

404

+

404

{t("pageNotFound")}

diff --git a/src/components/AccessToken.tsx b/src/components/AccessToken.tsx index 54f926433..802be769a 100644 --- a/src/components/AccessToken.tsx +++ b/src/components/AccessToken.tsx @@ -143,7 +143,7 @@ export default function AccessToken({ token, resourceId }: AccessTokenProps) { ) : ( - + {renderTitle()} diff --git a/src/components/AccessTokenUsage.tsx b/src/components/AccessTokenUsage.tsx index 4b1703717..b10f793d0 100644 --- a/src/components/AccessTokenUsage.tsx +++ b/src/components/AccessTokenUsage.tsx @@ -58,12 +58,12 @@ export default function AccessTokenSection({
-
{t("tokenId")}
+
{t("tokenId")}
-
{t("token")}
+
{t("token")}
diff --git a/src/components/AdminUsersDataTable.tsx b/src/components/AdminUsersDataTable.tsx new file mode 100644 index 000000000..afa473e86 --- /dev/null +++ b/src/components/AdminUsersDataTable.tsx @@ -0,0 +1,37 @@ +"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/AlertingRulesTable.tsx b/src/components/AlertingRulesTable.tsx index 52ff3b609..f8fcf468d 100644 --- a/src/components/AlertingRulesTable.tsx +++ b/src/components/AlertingRulesTable.tsx @@ -118,6 +118,8 @@ function triggerLabel(rule: AlertRuleRow, t: (k: string) => string) { return t("alertingTriggerResourceHealthy"); case "resource_unhealthy": return t("alertingTriggerResourceUnhealthy"); + case "resource_degraded": + return t("alertingTriggerResourceDegraded"); case "resource_toggle": return t("alertingTriggerResourceToggle"); default: diff --git a/src/components/AuthPageSettings.tsx b/src/components/AuthPageSettings.tsx index 1e825fa1e..edd1e3a19 100644 --- a/src/components/AuthPageSettings.tsx +++ b/src/components/AuthPageSettings.tsx @@ -399,11 +399,10 @@ function AuthPageSettings({
)} - {env.flags.usePangolinDns && - (build === "enterprise" || - !isPaidUser( - tierMatrix.loginPageDomain - )) && + {build !== "oss" && (build === "enterprise" || + !isPaidUser( + tierMatrix.loginPageDomain + )) && loginPage?.domainId && loginPage?.fullDomain && !hasUnsavedChanges && ( diff --git a/src/components/CertificateStatus.tsx b/src/components/CertificateStatus.tsx index 65e0d19ae..cc22b1e88 100644 --- a/src/components/CertificateStatus.tsx +++ b/src/components/CertificateStatus.tsx @@ -1,43 +1,38 @@ "use client"; import { Button } from "@/components/ui/button"; -import { RotateCw } from "lucide-react"; +import { FileBadge, RotateCw } from "lucide-react"; import { useCertificate } from "@app/hooks/useCertificate"; +import type { GetCertificateResponse } from "@server/routers/certificates/types"; import { useTranslations } from "next-intl"; -type CertificateStatusProps = { - orgId: string; - domainId: string; - fullDomain: string; - autoFetch?: boolean; +export type CertificateStatusContentProps = { + cert: GetCertificateResponse | null; + certLoading: boolean; + certError: string | null; + refreshing: boolean; + refreshCert: () => Promise; showLabel?: boolean; className?: string; onRefresh?: () => void; - polling?: boolean; - pollingInterval?: number; }; -export default function CertificateStatus({ - orgId, - domainId, - fullDomain, - autoFetch = true, +/** Presentation-only certificate row (shared hook state possible via props). */ +export function CertificateStatusContent({ + cert, + certLoading, + certError, + refreshing, + refreshCert, showLabel = true, className = "", - onRefresh, - polling = false, - pollingInterval = 5000 -}: CertificateStatusProps) { + onRefresh +}: CertificateStatusContentProps) { const t = useTranslations(); - const { cert, certLoading, certError, refreshing, refreshCert } = - useCertificate({ - orgId, - domainId, - fullDomain, - autoFetch, - polling, - pollingInterval - }); + + const labelClass = + "inline-flex shrink-0 items-center self-center text-sm font-medium leading-none"; + const valueClass = "inline-flex items-center gap-2 text-sm leading-none"; const handleRefresh = async () => { await refreshCert(); @@ -74,11 +69,15 @@ export default function CertificateStatus({ return (
{showLabel && ( - + {t("certificateStatus")}: )} - + + {t("loading")}
@@ -89,11 +88,17 @@ export default function CertificateStatus({ return (
{showLabel && ( - + {t("certificateStatus")}: )} - {certError} + + + {certError} +
); } @@ -102,32 +107,64 @@ export default function CertificateStatus({ return (
{showLabel && ( - + {t("certificateStatus")}: )} - + + {t("none", { defaultValue: "None" })}
); } + const isPending = cert.status === "pending"; + const disableRestartButton = cert.domainType === "wildcard"; + return (
{showLabel && ( - - {t("certificateStatus")}: - + {t("certificateStatus")}: )} - - + {isPending && !disableRestartButton ? ( + + ) : ( + + {cert.status.charAt(0).toUpperCase() + cert.status.slice(1)} - {shouldShowRefreshButton(cert.status, cert.updatedAt) && ( + {shouldShowRefreshButton(cert.status, cert.updatedAt) && + !disableRestartButton ? ( - )} + ) : null} - + )}
); } + +type CertificateStatusProps = { + orgId: string; + domainId: string; + fullDomain: string; + autoFetch?: boolean; + showLabel?: boolean; + className?: string; + onRefresh?: () => void; + polling?: boolean; + pollingInterval?: number; +}; + +export default function CertificateStatus({ + orgId, + domainId, + fullDomain, + autoFetch = true, + showLabel = true, + className = "", + onRefresh, + polling = false, + pollingInterval = 5000 +}: CertificateStatusProps) { + const hook = useCertificate({ + orgId, + domainId, + fullDomain, + autoFetch, + polling, + pollingInterval + }); + + return ( + + ); +} diff --git a/src/components/ClientInfoCard.tsx b/src/components/ClientInfoCard.tsx index 7f55a46cd..4815c85fb 100644 --- a/src/components/ClientInfoCard.tsx +++ b/src/components/ClientInfoCard.tsx @@ -8,6 +8,7 @@ import { InfoSections, InfoSectionTitle } from "@app/components/InfoSection"; +import IdpTypeBadge from "@app/components/IdpTypeBadge"; import { getUserDisplayName } from "@app/lib/getUserDisplayName"; import { useTranslations } from "next-intl"; @@ -36,7 +37,24 @@ export default function SiteInfoCard({}: ClientInfoCardProps) { {userDisplayName ? t("user") : t("identifier")} - {userDisplayName || client.niceId} +
+ {userDisplayName || client.niceId} + {userDisplayName && + (client.userType ?? "internal") !== + "internal" && ( + + )} +
diff --git a/src/components/ClientResourcesTable.tsx b/src/components/ClientResourcesTable.tsx index 36f8caa78..88b1e938e 100644 --- a/src/components/ClientResourcesTable.tsx +++ b/src/components/ClientResourcesTable.tsx @@ -4,6 +4,7 @@ import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog"; import CopyToClipboard from "@app/components/CopyToClipboard"; import { DataTable } from "@app/components/ui/data-table"; import { ExtendedColumnDef } from "@app/components/ui/data-table"; +import { Badge } from "@app/components/ui/badge"; import { Button } from "@app/components/ui/button"; import { DropdownMenu, @@ -12,6 +13,11 @@ import { DropdownMenuTrigger } from "@app/components/ui/dropdown-menu"; import { InfoPopup } from "@app/components/ui/info-popup"; +import { + Popover, + PopoverContent, + PopoverTrigger +} from "@app/components/ui/popover"; import { useEnvContext } from "@app/hooks/useEnvContext"; import { toast } from "@app/hooks/useToast"; import { createApiClient, formatAxiosError } from "@app/lib/api"; @@ -23,30 +29,32 @@ import { ArrowUpRight, ChevronDown, ChevronsUpDownIcon, + Funnel, MoreHorizontal } from "lucide-react"; import { useTranslations } from "next-intl"; import Link from "next/link"; import { useRouter } from "next/navigation"; -import { useState, useTransition } from "react"; - +import { Selectedsite, SitesSelector } from "@app/components/site-selector"; +import { useEffect, useMemo, useState, useTransition } from "react"; import CreateInternalResourceDialog from "@app/components/CreateInternalResourceDialog"; import EditInternalResourceDialog from "@app/components/EditInternalResourceDialog"; -import { orgQueries } from "@app/lib/queries"; -import { useQuery } from "@tanstack/react-query"; import type { PaginationState } from "@tanstack/react-table"; 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"; +import { dataTableFilterPopoverContentClassName } from "@app/lib/dataTableFilterPopover"; +import { formatSiteResourceDestinationDisplay } from "@app/lib/formatSiteResourceAccess"; +import { + ResourceSitesStatusCell, + type ResourceSiteRow +} from "@app/components/ResourceSitesStatusCell"; +import { ResourceAccessCertIndicator } from "@app/components/ResourceAccessCertIndicator"; +import { build } from "@server/build"; -export type InternalResourceSiteRow = { - siteId: number; - siteName: string; - siteNiceId: string; - online: boolean; -}; +export type InternalResourceSiteRow = ResourceSiteRow; export type InternalResourceRow = { id: number; @@ -78,28 +86,13 @@ export type InternalResourceRow = { 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}`; + return formatSiteResourceDestinationDisplay({ + mode: row.mode, + destination: row.destination, + httpHttpsPort: row.httpHttpsPort, + scheme: row.scheme + }); } function isSafeUrlForLink(href: string): boolean { @@ -111,121 +104,20 @@ function isSafeUrlForLink(href: string): boolean { } } -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; pagination: PaginationState; rowCount: number; + initialFilterSite?: Selectedsite | null; }; export default function ClientResourcesTable({ internalResources, orgId, pagination, - rowCount + rowCount, + initialFilterSite = null }: ClientResourcesTableProps) { const router = useRouter(); const { @@ -247,9 +139,33 @@ export default function ClientResourcesTable({ const [editingResource, setEditingResource] = useState(); const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false); + const [siteFilterOpen, setSiteFilterOpen] = useState(false); const [isRefreshing, startTransition] = useTransition(); + useEffect(() => { + const interval = setInterval(() => { + router.refresh(); + }, 30_000); + return () => clearInterval(interval); + }, [router]); + + 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 refreshData = () => { startTransition(() => { try { @@ -289,14 +205,16 @@ export default function ClientResourcesTable({ const { siteNames, siteNiceIds, orgId } = resourceRow; if (!siteNames || siteNames.length === 0) { - return -; + return ( + + {t("noSites", { defaultValue: "No sites" })} + + ); } if (siteNames.length === 1) { return ( - + + + +
+ +
+ +
+ + ), cell: ({ row }) => { const resourceRow = row.original; return ( - @@ -479,13 +442,34 @@ export default function ClientResourcesTable({ ); } if (resourceRow.mode === "http") { - const url = `${resourceRow.ssl ? "https" : "http"}://${resourceRow.fullDomain}`; + const domainId = resourceRow.domainId; + const fullDomain = resourceRow.fullDomain; + const url = `${resourceRow.ssl ? "https" : "http"}://${fullDomain}`; + const did = + build !== "oss" && + resourceRow.ssl && + domainId != null && + domainId !== "" && + fullDomain != null && + fullDomain !== ""; + return ( - +
+ {did ? ( + + ) : null} +
+ +
+
); } return -; @@ -576,6 +560,16 @@ export default function ClientResourcesTable({ }); } + const clearSiteFilter = () => { + handleFilterChange("siteId", undefined); + setSiteFilterOpen(false); + }; + + const onPickSite = (site: Selectedsite) => { + handleFilterChange("siteId", String(site.siteId)); + setSiteFilterOpen(false); + }; + function toggleSort(column: string) { const newSearch = getNextSortOrder(column, searchParams); @@ -632,6 +626,7 @@ export default function ClientResourcesTable({ rows={internalResources} tableId="internal-resources" searchPlaceholder={t("resourcesSearch")} + searchQuery={searchParams.get("query") ?? ""} onAdd={() => setIsCreateDialogOpen(true)} addButtonText={t("resourceAdd")} onSearch={handleSearchChange} diff --git a/src/components/ColumnFilter.tsx b/src/components/ColumnFilter.tsx index 3e7b585b8..5a944cd88 100644 --- a/src/components/ColumnFilter.tsx +++ b/src/components/ColumnFilter.tsx @@ -15,6 +15,7 @@ import { } from "@app/components/ui/command"; import { CheckIcon, ChevronDownIcon, Filter } from "lucide-react"; import { cn } from "@app/lib/cn"; +import { dataTableFilterPopoverContentClassName } from "@app/lib/dataTableFilterPopover"; import { Badge } from "./ui/badge"; interface FilterOption { @@ -74,7 +75,10 @@ export function ColumnFilter({ - + diff --git a/src/components/ColumnFilterButton.tsx b/src/components/ColumnFilterButton.tsx index 7d17066cb..689f78983 100644 --- a/src/components/ColumnFilterButton.tsx +++ b/src/components/ColumnFilterButton.tsx @@ -15,6 +15,7 @@ import { } from "@app/components/ui/command"; import { CheckIcon, ChevronDownIcon, Funnel } from "lucide-react"; import { cn } from "@app/lib/cn"; +import { dataTableFilterPopoverContentClassName } from "@app/lib/dataTableFilterPopover"; import { Badge } from "./ui/badge"; interface FilterOption { @@ -75,7 +76,10 @@ export function ColumnFilterButton({
- + diff --git a/src/components/ColumnMultiFilterButton.tsx b/src/components/ColumnMultiFilterButton.tsx index ee386461d..787a306b2 100644 --- a/src/components/ColumnMultiFilterButton.tsx +++ b/src/components/ColumnMultiFilterButton.tsx @@ -18,6 +18,7 @@ import { } from "@app/components/ui/command"; import { CheckIcon, Funnel } from "lucide-react"; import { cn } from "@app/lib/cn"; +import { dataTableFilterPopoverContentClassName } from "@app/lib/dataTableFilterPopover"; import { Badge } from "./ui/badge"; type FilterOption = { @@ -101,7 +102,10 @@ export function ColumnMultiFilterButton({
- + diff --git a/src/components/ConfirmDeleteDialog.tsx b/src/components/ConfirmDeleteDialog.tsx index 4c5c6ad63..32fc83179 100644 --- a/src/components/ConfirmDeleteDialog.tsx +++ b/src/components/ConfirmDeleteDialog.tsx @@ -92,7 +92,7 @@ export default function ConfirmDeleteDialog({
{dialog} -
+
{warningText || t("cannotbeUndone")}
@@ -142,7 +142,9 @@ export default function ConfirmDeleteDialog({ form="confirm-delete-form" loading={loading} disabled={loading || !isConfirmed} - className={!isConfirmed && !loading ? "opacity-50" : ""} + className={ + !isConfirmed && !loading ? "opacity-50" : "" + } > {buttonText} diff --git a/src/components/CreateShareLinkForm.tsx b/src/components/CreateShareLinkForm.tsx index d0e26a1c2..2e5dbe655 100644 --- a/src/components/CreateShareLinkForm.tsx +++ b/src/components/CreateShareLinkForm.tsx @@ -47,15 +47,7 @@ import { PopoverTrigger } from "@app/components/ui/popover"; import { CaretSortIcon } from "@radix-ui/react-icons"; -import { - Command, - CommandEmpty, - CommandGroup, - CommandInput, - CommandItem, - CommandList -} from "@app/components/ui/command"; -import { CheckIcon, ChevronsUpDown } from "lucide-react"; +import { ChevronsUpDown } from "lucide-react"; import { Checkbox } from "@app/components/ui/checkbox"; import { GenerateAccessTokenResponse } from "@server/routers/accessToken"; import { constructShareLink } from "@app/lib/shareLinks"; @@ -275,10 +267,11 @@ export default function CreateShareLinkForm({ ({
-

{t("dnsRecord")}

+

{t("dnsRecord")}

{t("required")}
)}
-

+

{t("cannotbeUndone")}

diff --git a/src/components/DomainPicker.tsx b/src/components/DomainPicker.tsx index 7a90dfa67..daacf892b 100644 --- a/src/components/DomainPicker.tsx +++ b/src/components/DomainPicker.tsx @@ -27,6 +27,7 @@ import { cn } from "@/lib/cn"; import { finalizeSubdomainSanitize, isValidSubdomainStructure, + isWildcardSubdomain, sanitizeInputRaw, validateByDomainType } from "@/lib/subdomain-utils"; @@ -41,10 +42,12 @@ import { Check, CheckCircle2, ChevronsUpDown, + ExternalLink, KeyRound, Zap } from "lucide-react"; import { useTranslations } from "next-intl"; +import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert"; import { usePaidStatus } from "@/hooks/usePaidStatus"; import { TierFeature, tierMatrix } from "@server/lib/billing/tierMatrix"; import { toUnicode } from "punycode"; @@ -77,6 +80,7 @@ interface DomainPickerProps { subdomain?: string; fullDomain: string; baseDomain: string; + wildcard?: boolean; } | null ) => void; cols?: number; @@ -85,6 +89,7 @@ interface DomainPickerProps { defaultSubdomain?: string | null; defaultDomainId?: string | null; warnOnProvidedDomain?: boolean; + allowWildcard?: boolean; } export default function DomainPicker({ @@ -95,23 +100,30 @@ export default function DomainPicker({ defaultSubdomain, defaultFullDomain, defaultDomainId, - warnOnProvidedDomain = false + warnOnProvidedDomain = false, + allowWildcard = false }: DomainPickerProps) { const { env } = useEnvContext(); const { user } = useUserContext(); const api = createApiClient({ env }); const t = useTranslations(); - const { hasSaasSubscription } = usePaidStatus(); + const { hasSaasSubscription, isPaidUser } = usePaidStatus(); const requiresPaywall = build === "saas" && !hasSaasSubscription(tierMatrix[TierFeature.DomainNamespaces]) && new Date(user.dateCreated) > new Date("2026-04-13"); + const wildcardAllowed = + allowWildcard && isPaidUser(tierMatrix[TierFeature.WildcardSubdomain]); + const { data = [], isLoading: loadingDomains } = useQuery( orgQueries.domains({ orgId }) ); + // Wildcard mode is derived from the input itself — if the user types a + // wildcard subdomain (e.g. *.foo) and allowWildcard is enabled, it's active. + if (!env.flags.usePangolinDns) { hideFreeDomain = true; } @@ -180,13 +192,16 @@ export default function DomainPicker({ firstOrExistingDomain.type !== "cname" ? defaultSubdomain?.trim() || undefined : undefined; + const isWc = + allowWildcard && !!sub && isWildcardSubdomain(sub); onDomainChange?.({ domainId: firstOrExistingDomain.domainId, type: "organization", subdomain: sub, fullDomain: sub ? `${sub}.${base}` : base, - baseDomain: base + baseDomain: base, + wildcard: isWc }); } } @@ -285,7 +300,8 @@ export default function DomainPicker({ }, [userInput, debouncedCheckAvailability, selectedBaseDomain]); const finalizeSubdomain = (sub: string, base: DomainOption): string => { - const sanitized = finalizeSubdomainSanitize(sub); + const wildcardMode = wildcardAllowed && isWildcardSubdomain(sub); + const sanitized = finalizeSubdomainSanitize(sub, wildcardMode); if (!sanitized) { toast({ @@ -301,7 +317,8 @@ export default function DomainPicker({ base.type === "provided-search" ? "provided-search" : "organization", - domainType: base.domainType + domainType: base.domainType, + allowWildcard: wildcardMode }); if (!ok) { @@ -330,7 +347,7 @@ export default function DomainPicker({ }; const handleSubdomainChange = (value: string) => { - const raw = sanitizeInputRaw(value); + const raw = sanitizeInputRaw(value, allowWildcard); setSubdomainInput(raw); setSelectedProvidedDomain(null); @@ -338,13 +355,15 @@ export default function DomainPicker({ const fullDomain = raw ? `${raw}.${selectedBaseDomain.domain}` : selectedBaseDomain.domain; + const isWc = wildcardAllowed && isWildcardSubdomain(raw); onDomainChange?.({ domainId: selectedBaseDomain.domainId!, type: "organization", subdomain: raw || undefined, fullDomain, - baseDomain: selectedBaseDomain.domain + baseDomain: selectedBaseDomain.domain, + wildcard: isWc }); } }; @@ -366,6 +385,17 @@ export default function DomainPicker({ const handleBaseDomainSelect = (option: DomainOption) => { let sub = subdomainInput; + // If the selected domain doesn't support wildcards, strip any wildcard prefix. + const supportsWildcard = + wildcardAllowed && + option.type === "organization" && + option.domainType !== "cname"; + + if (!supportsWildcard && isWildcardSubdomain(sub)) { + sub = sub.replace(/^\*\./, ""); + setSubdomainInput(sub); + } + if (sub && sub.trim() !== "") { sub = finalizeSubdomain(sub, option) || ""; setSubdomainInput(sub); @@ -389,6 +419,7 @@ export default function DomainPicker({ } const fullDomain = sub ? `${sub}.${option.domain}` : option.domain; + const isWc = wildcardAllowed && !!sub && isWildcardSubdomain(sub); if (option.type === "provided-search") { onDomainChange?.(null); // prevent the modal from closing with `.Free Provided domain` @@ -402,7 +433,8 @@ export default function DomainPicker({ ? sub || undefined : undefined, fullDomain, - baseDomain: option.domain + baseDomain: option.domain, + wildcard: isWc }); } }; @@ -431,7 +463,9 @@ export default function DomainPicker({ selectedBaseDomain.type === "provided-search" ? "provided-search" : "organization", - domainType: selectedBaseDomain.domainType + domainType: selectedBaseDomain.domainType, + allowWildcard: + wildcardAllowed && isWildcardSubdomain(subdomainInput) }) : true; @@ -439,6 +473,7 @@ export default function DomainPicker({ selectedBaseDomain && selectedBaseDomain.type === "organization" && selectedBaseDomain.domainType !== "cname"; + const showProvidedDomainSearch = selectedBaseDomain?.type === "provided-search"; @@ -463,9 +498,11 @@ export default function DomainPicker({
- +
+ +
{showSubdomainInput && subdomainInput && - !isValidSubdomainStructure(subdomainInput) && ( + !isValidSubdomainStructure( + subdomainInput, + wildcardAllowed && + isWildcardSubdomain(subdomainInput) + ) && (

{t("domainPickerInvalidSubdomainStructure")}

)} + {allowWildcard && + !wildcardAllowed && + showSubdomainInput && + isWildcardSubdomain(subdomainInput) && ( + <> +

+ {t( + "domainPickerWildcardSubdomainNotAllowed" + )} +

+ + + )}
@@ -592,23 +655,23 @@ export default function DomainPicker({ {orgDomain.type === - "wildcard" - ? t( - "domainPickerManual" - ) - : ( - <> - {orgDomain.type.toUpperCase()}{" "} - •{" "} - {orgDomain.verified - ? t( - "domainPickerVerified" - ) - : t( - "domainPickerUnverified" - )} - - )} + "wildcard" ? ( + t( + "domainPickerManual" + ) + ) : ( + <> + {orgDomain.type.toUpperCase()}{" "} + •{" "} + {orgDomain.verified + ? t( + "domainPickerVerified" + ) + : t( + "domainPickerUnverified" + )} + + )}
{requiresPaywall && !hideFreeDomain && ( - - -
- - - {t("domainPickerFreeDomainsPaidFeature")} - -
-
-
- )} + + +
+ + + {t("domainPickerFreeDomainsPaidFeature")} + +
+
+
+ )} {/*showProvidedDomainSearch && build === "saas" && ( @@ -845,6 +908,22 @@ export default function DomainPicker({ )}
)} + {selectedBaseDomain?.domainType === "wildcard" && + isWildcardSubdomain(subdomainInput) && ( +

+ {t("domainPickerWildcardCertWarning")}{" "} + + {t("domainPickerWildcardCertWarningLink")} + + + . +

+ )}
); } diff --git a/src/components/HealthCheckCredenza.tsx b/src/components/HealthCheckCredenza.tsx index 671a16e7d..0360a15e7 100644 --- a/src/components/HealthCheckCredenza.tsx +++ b/src/components/HealthCheckCredenza.tsx @@ -46,6 +46,7 @@ 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"; +import { SwitchInput } from "@app/components/SwitchInput"; export type HealthCheckConfig = { hcEnabled: boolean; @@ -118,7 +119,7 @@ const DEFAULT_VALUES = { name: "", hcEnabled: true, hcMode: "http", - hcScheme: "https", + hcScheme: "http", hcMethod: "GET", hcHostname: "", hcPort: "", @@ -270,7 +271,7 @@ export function HealthCheckCredenza(props: HealthCheckCredenzaProps) { name: initialValues.name, hcEnabled: initialValues.hcEnabled, hcMode: initialValues.hcMode ?? "http", - hcScheme: initialValues.hcScheme ?? "https", + hcScheme: initialValues.hcScheme ?? "http", hcMethod: initialValues.hcMethod ?? "GET", hcHostname: initialValues.hcHostname ?? "", hcPort: initialValues.hcPort @@ -407,7 +408,7 @@ export function HealthCheckCredenza(props: HealthCheckCredenzaProps) { }) : t("standaloneHcDescription"); - const showFields = mode === "submit" || watchedEnabled; + const disableTabInputs = mode === "autoSave" && !watchedEnabled; const isSnmpOrIcmp = watchedMode === "snmp" || watchedMode === "icmp"; const isTcp = watchedMode === "tcp"; @@ -484,6 +485,7 @@ export function HealthCheckCredenza(props: HealthCheckCredenzaProps) { onSelectSite={(site) => { setSelectedSite(site); }} + filterTypes={["newt"]} />
@@ -491,6 +493,40 @@ export function HealthCheckCredenza(props: HealthCheckCredenzaProps) {
)} + {mode === "autoSave" && ( +
+ ( + + + + handleChange( + "hcEnabled", + value, + field.onChange + ) + } + /> + + + )} + /> +
+ )} +
{/* ── Strategy tab ──────────────────────── */} -
- {/* Enable toggle (autoSave mode only) */} - {mode === "autoSave" && ( - ( - -
- - {t( - "enableHealthChecks" - )} - -
- - - handleChange( - "hcEnabled", - value, - field.onChange - ) - } - /> - -
- )} - /> - )} - +
+
{/* Strategy picker */} - {showFields && ( - ( - - - - handleChange( - "hcMode", - value, - field.onChange + ( + + + - - - - )} - /> - )} + }, + { + id: "tcp", + title: "TCP", + description: t( + "healthCheckStrategyTcp" + ) + }, + // lets hide these for now until they are implemented + // { + // id: "snmp", + // title: "SNMP", + // description: t( + // "healthCheckStrategySnmp" + // ) + // }, + // { + // id: "icmp", + // title: "Ping (ICMP)", + // description: t( + // "healthCheckStrategyIcmp" + // ) + // } + ]} + value={field.value} + onChange={(value) => + handleChange( + "hcMode", + value, + field.onChange + ) + } + /> + + + + )} + /> +
{/* ── Connection tab ────────────────────── */} -
- {!showFields && ( -

- {t("enableHealthChecks")} -

- )} - +
+
{/* Contact-sales banner for SNMP / ICMP */} - {showFields && isSnmpOrIcmp && ( - - )} + {isSnmpOrIcmp && } - {showFields && !isSnmpOrIcmp && ( + {!isSnmpOrIcmp && ( <> {/* Scheme / Hostname / Port */} {isTcp ? ( @@ -1021,22 +1022,23 @@ export function HealthCheckCredenza(props: HealthCheckCredenzaProps) { )} )} +
{/* ── Advanced tab ──────────────────────── */} -
- {!showFields && ( -

- {t("enableHealthChecks")} -

- )} - +
+
{/* Contact-sales banner for SNMP / ICMP */} - {showFields && isSnmpOrIcmp && ( - - )} + {isSnmpOrIcmp && } - {showFields && !isSnmpOrIcmp && ( + {!isSnmpOrIcmp && ( <> {/* Healthy interval + threshold */}
@@ -1350,6 +1352,7 @@ export function HealthCheckCredenza(props: HealthCheckCredenzaProps) { )} )} +
diff --git a/src/components/HealthChecksTable.tsx b/src/components/HealthChecksTable.tsx index 404ade547..68976bf40 100644 --- a/src/components/HealthChecksTable.tsx +++ b/src/components/HealthChecksTable.tsx @@ -50,6 +50,7 @@ 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"; +import { dataTableFilterPopoverContentClassName } from "@app/lib/dataTableFilterPopover"; type StandaloneHealthChecksTableProps = { orgId: string; @@ -150,7 +151,8 @@ export default function HealthChecksTable({ resourceId: resourceIdNum, fullDomain: null, niceId: "", - ssl: false + ssl: false, + wildcard: false }; }, [initialFilterResource, resourceIdQ, resourceIdNum, t]); @@ -165,7 +167,7 @@ export default function HealthChecksTable({ useEffect(() => { const interval = setInterval(() => { router.refresh(); - }, 10_000); + }, 30_000); return () => clearInterval(interval); }, [router]); @@ -376,7 +378,7 @@ export default function HealthChecksTable({
@@ -445,7 +447,7 @@ export default function HealthChecksTable({
@@ -584,7 +586,7 @@ export default function HealthChecksTable({ handleToggleEnabled(r, v)} /> diff --git a/src/components/InfoSection.tsx b/src/components/InfoSection.tsx index b00503c3d..f680a51ca 100644 --- a/src/components/InfoSection.tsx +++ b/src/components/InfoSection.tsx @@ -4,18 +4,29 @@ import { cn } from "@app/lib/cn"; export function InfoSections({ children, - cols + cols, + columnSizing = "content" }: { children: React.ReactNode; cols?: number; + /** content (default): fixed gap, columns hug content, left-aligned; fill: equal-width columns across the row */ + columnSizing?: "fill" | "content"; }) { + const n = cols || 1; + const track = + columnSizing === "fill" ? "minmax(0, 1fr)" : "minmax(0, max-content)"; + return (
{children} diff --git a/src/components/InternalResourceForm.tsx b/src/components/InternalResourceForm.tsx index fd0455b70..bdf8dab48 100644 --- a/src/components/InternalResourceForm.tsx +++ b/src/components/InternalResourceForm.tsx @@ -62,6 +62,7 @@ import { SwitchInput } from "@app/components/SwitchInput"; import CertificateStatus from "@app/components/CertificateStatus"; import { UsersSelector } from "./users-selector"; import { RolesSelector } from "./roles-selector"; +import { build } from "@server/build"; // --- Helpers (shared) --- @@ -754,108 +755,139 @@ export function InternalResourceForm({ )}
-
-
- ( - - - {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)} + {t("sites")} - - options={modeOptions} - value={field.value} - onChange={ - field.onChange - } - cols={3} - /> + + + + + + + + { + 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} + /> + + + ); + }} + /> +
+ {selectedSites.length > 1 && ( +

+ {t( + "internalResourceFormMultiSiteRoutingHelp" + )}{" "} + + {t( + "internalResourceFormMultiSiteRoutingHelpLearnMore" + )} + + + . +

+ )}
- +
+ {t("certificateStatus")}: - + {loading ? t("checkingInvite") : t("inviteNotAccepted")} diff --git a/src/components/MemberResourcesPortal.tsx b/src/components/MemberResourcesPortal.tsx index 8ce721c88..0ca6c550b 100644 --- a/src/components/MemberResourcesPortal.tsx +++ b/src/components/MemberResourcesPortal.tsx @@ -67,7 +67,7 @@ type SiteResource = { enabled: boolean; alias: string | null; aliasAddress: string | null; - type: 'site'; + type: "site"; }; type MemberResourcesPortalProps = { @@ -130,7 +130,9 @@ const ResourceInfo = ({ resource }: { resource: Resource }) => { resource.whitelist; const hasAnyInfo = - Boolean(resource.siteName) || Boolean(hasAuthMethods) || !resource.enabled; + Boolean(resource.siteName) || + Boolean(hasAuthMethods) || + !resource.enabled; if (!hasAnyInfo) return null; @@ -353,7 +355,9 @@ export default function MemberResourcesPortal({ const [resources, setResources] = useState([]); const [siteResources, setSiteResources] = useState([]); const [filteredResources, setFilteredResources] = useState([]); - const [filteredSiteResources, setFilteredSiteResources] = useState([]); + const [filteredSiteResources, setFilteredSiteResources] = useState< + SiteResource[] + >([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [searchQuery, setSearchQuery] = useState(""); @@ -381,7 +385,9 @@ export default function MemberResourcesPortal({ setResources(response.data.data.resources); setSiteResources(response.data.data.siteResources || []); setFilteredResources(response.data.data.resources); - setFilteredSiteResources(response.data.data.siteResources || []); + setFilteredSiteResources( + response.data.data.siteResources || [] + ); } else { setError("Failed to load resources"); } @@ -459,9 +465,10 @@ export default function MemberResourcesPortal({ case "domain-asc": case "domain-desc": // Sort by destination for site resources - const destCompare = sortBy === "domain-asc" - ? a.destination.localeCompare(b.destination) - : b.destination.localeCompare(a.destination); + const destCompare = + sortBy === "domain-asc" + ? a.destination.localeCompare(b.destination) + : b.destination.localeCompare(a.destination); return destCompare; case "status-enabled": return b.enabled ? 1 : -1; @@ -487,12 +494,14 @@ export default function MemberResourcesPortal({ startIndex + itemsPerPage ); const remainingSlots = itemsPerPage - paginatedResources.length; - const paginatedSiteResources = remainingSlots > 0 - ? filteredSiteResources.slice( - Math.max(0, startIndex - filteredResources.length), - Math.max(0, startIndex - filteredResources.length) + remainingSlots - ) - : []; + const paginatedSiteResources = + remainingSlots > 0 + ? filteredSiteResources.slice( + Math.max(0, startIndex - filteredResources.length), + Math.max(0, startIndex - filteredResources.length) + + remainingSlots + ) + : []; const handleOpenResource = (resource: Resource) => { // Open the resource in a new tab @@ -640,7 +649,8 @@ export default function MemberResourcesPortal({
{/* Resources Content */} - {filteredResources.length === 0 && filteredSiteResources.length === 0 ? ( + {filteredResources.length === 0 && + filteredSiteResources.length === 0 ? ( /* Enhanced Empty State */ @@ -697,87 +707,96 @@ export default function MemberResourcesPortal({ Public Resources

- Web applications and services accessible via browser + Web applications and services accessible via + browser

{paginatedResources.map((resource) => ( - -
-
-
- - - - - {resource.name} - - - -

- {resource.name} -

-
-
-
+ +
+
+
+ + + + + { + resource.name + } + + + +

+ { + resource.name + } +

+
+
+
+
+ +
+ +
+
+ +
+ + +
-
- +
+
-
- -
- - -
-
- -
- -
- - ))} -
+ + ))} +
)} @@ -790,7 +809,8 @@ export default function MemberResourcesPortal({ Private Resources

- Internal network resources accessible via client + Internal network resources accessible via + client

@@ -802,13 +822,17 @@ export default function MemberResourcesPortal({ - - {siteResource.name} + + { + siteResource.name + }

- {siteResource.name} + { + siteResource.name + }

@@ -818,39 +842,63 @@ export default function MemberResourcesPortal({
-
Resource Details
+
+ Resource Details +
- Mode: + + Mode: + - {siteResource.mode} + { + siteResource.mode + }
{siteResource.protocol && (
- Protocol: + + Protocol: + - {siteResource.protocol} + { + siteResource.protocol + }
)}
- Destination: + + Destination: + - {siteResource.destination} + { + siteResource.destination + }
{siteResource.alias && (
- Alias: + + Alias: + - {siteResource.alias} + { + siteResource.alias + }
)}
- Status: - - {siteResource.enabled ? 'Enabled' : 'Disabled'} + + Status: + + + {siteResource.enabled + ? "Enabled" + : "Disabled"}
@@ -864,7 +912,9 @@ export default function MemberResourcesPortal({ {/* Alias as primary */}
- {siteResource.alias} + { + siteResource.alias + }
+ + +
+ +
+ +
+ + ), + cell: ({ row }) => ( + + ) + }, { accessorKey: "protocol", friendlyName: t("protocol"), @@ -396,7 +463,7 @@ export default function ProxyResourcesTable({ { id: "status", accessorKey: "status", - friendlyName: t("status"), + friendlyName: t("health"), header: () => ( ), cell: ({ row }) => { const resourceRow = row.original; - return ; + return ( + + ); }, sortingFn: (rowA, rowB) => { - const statusA = getOverallHealthStatus(rowA.original.targets); - const statusB = getOverallHealthStatus(rowB.original.targets); + const statusA = rowA.original.health; + const statusB = rowB.original.health; + if (!statusA && !statusB) return 0; + if (!statusA) return 1; + if (!statusB) return -1; const statusOrder = { - online: 3, + healthy: 3, degraded: 2, - offline: 1, + unhealthy: 1, unknown: 0 }; return statusOrder[statusA] - statusOrder[statusB]; @@ -446,9 +520,7 @@ export default function ProxyResourcesTable({ header: () => {t("uptime30d")}, cell: ({ row }) => { const resourceRow = row.original; - return ( - - ); + return ; } }, { @@ -457,24 +529,52 @@ export default function ProxyResourcesTable({ header: () => {t("access")}, cell: ({ row }) => { const resourceRow = row.original; - return ( -
- {!resourceRow.http ? ( + + if (!resourceRow.http) { + return ( +
- ) : !resourceRow.domainId ? ( +
+ ); + } + + if (!resourceRow.domainId) { + return ( +
- ) : ( +
+ ); + } + + const domainId = resourceRow.domainId; + const certHostname = resourceRow.fullDomain; + const showHttpsCertIndicator = + build !== "oss" && + resourceRow.ssl && + certHostname != null && + certHostname !== ""; + + return ( +
+ {showHttpsCertIndicator ? ( + + ) : null} +
- )} +
); } @@ -620,6 +720,16 @@ export default function ProxyResourcesTable({ }); } + const clearSiteFilter = () => { + handleFilterChange("siteId", undefined); + setSiteFilterOpen(false); + }; + + const onPickSite = (site: Selectedsite) => { + handleFilterChange("siteId", String(site.siteId)); + setSiteFilterOpen(false); + }; + function toggleSort(column: string) { const newSearch = getNextSortOrder(column, searchParams); diff --git a/src/components/ResourceAccessCertIndicator.tsx b/src/components/ResourceAccessCertIndicator.tsx new file mode 100644 index 000000000..40ddfbfab --- /dev/null +++ b/src/components/ResourceAccessCertIndicator.tsx @@ -0,0 +1,179 @@ +"use client"; + +import { CertificateStatusContent } from "@app/components/CertificateStatus"; +import { + Popover, + PopoverAnchor, + PopoverContent +} from "@app/components/ui/popover"; +import { useCertificate } from "@app/hooks/useCertificate"; +import { cn } from "@app/lib/cn"; +import { FileBadge } from "lucide-react"; +import { useTranslations } from "next-intl"; +import { + useCallback, + useEffect, + useRef, + useState, + type ReactNode +} from "react"; + +type ResourceAccessCertIndicatorProps = { + orgId: string; + domainId: string; + fullDomain: string; +}; + +function getStatusColor(status: string) { + switch (status) { + case "valid": + return "text-green-500"; + case "pending": + case "requested": + return "text-yellow-500"; + case "expired": + case "failed": + return "text-red-500"; + default: + return "text-muted-foreground"; + } +} + +/** Compact cert icon + hover popover with full certificate status (shared by proxy and client resource tables). */ +export function ResourceAccessCertIndicator({ + orgId, + domainId, + fullDomain +}: ResourceAccessCertIndicatorProps) { + const t = useTranslations(); + const [open, setOpen] = useState(false); + const closeTimerRef = useRef | null>(null); + + const certificate = useCertificate({ + orgId, + domainId, + fullDomain, + autoFetch: true, + polling: open, + pollingInterval: 5000 + }); + + const { cert, certLoading, certError, refreshing, fetchCert } = certificate; + + useEffect(() => { + if (!open) return; + void fetchCert(false); + }, [open, fetchCert]); + + const clearCloseTimer = useCallback(() => { + if (closeTimerRef.current != null) { + clearTimeout(closeTimerRef.current); + closeTimerRef.current = null; + } + }, []); + + const scheduleClose = useCallback(() => { + clearCloseTimer(); + closeTimerRef.current = setTimeout(() => setOpen(false), 280); + }, [clearCloseTimer]); + + const handleEnterOpen = useCallback(() => { + clearCloseTimer(); + setOpen(true); + }, [clearCloseTimer]); + + useEffect(() => { + return () => clearCloseTimer(); + }, [clearCloseTimer]); + + let triggerBody: ReactNode; + if (certLoading) { + triggerBody = ( +
+ ); + } else if (refreshing) { + triggerBody = ( + + ); + } else if (certError) { + triggerBody = ( + + ); + } else if (cert) { + triggerBody = ( + + ); + } else { + triggerBody = ( + + ); + } + + return ( + + + + + e.preventDefault()} + > +
+ +

+ {t("certificateStatusAutoRefreshHint")} +

+
+
+
+ ); +} diff --git a/src/components/ResourceAccessDenied.tsx b/src/components/ResourceAccessDenied.tsx index b45aa0d74..3625e4d39 100644 --- a/src/components/ResourceAccessDenied.tsx +++ b/src/components/ResourceAccessDenied.tsx @@ -17,7 +17,7 @@ export default function ResourceAccessDenied() { return ( - + {t("accessDenied")} diff --git a/src/components/ResourceInfoBox.tsx b/src/components/ResourceInfoBox.tsx index ad3cb5f34..7ddb06ddd 100644 --- a/src/components/ResourceInfoBox.tsx +++ b/src/components/ResourceInfoBox.tsx @@ -1,7 +1,15 @@ "use client"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; -import { ShieldCheck, ShieldOff, Eye, EyeOff } from "lucide-react"; +import { + ShieldCheck, + ShieldOff, + Eye, + EyeOff, + CheckCircle2, + XCircle, + Clock +} from "lucide-react"; import { useResourceContext } from "@app/hooks/useResourceContext"; import CopyToClipboard from "@app/components/CopyToClipboard"; import { @@ -13,13 +21,12 @@ import { import { useTranslations } from "next-intl"; import CertificateStatus from "@app/components/CertificateStatus"; import { toUnicode } from "punycode"; -import { useEnvContext } from "@app/hooks/useEnvContext"; +import { build } from "@server/build"; type ResourceInfoBoxType = {}; export default function ResourceInfoBox({}: ResourceInfoBoxType) { - const { resource, authInfo, updateResource } = useResourceContext(); - const { env } = useEnvContext(); + const { resource, authInfo } = useResourceContext(); const t = useTranslations(); @@ -29,9 +36,7 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) { {/* 4 cols because of the certs */} - + {t("identifier")} @@ -43,10 +48,14 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) { URL - + {resource.wildcard ? ( + {fullUrl} + ) : ( + + )} @@ -60,12 +69,12 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) { authInfo.whitelist || authInfo.headerAuth ? (
- + {t("protected")}
) : ( -
- +
+ {t("notProtected")}
)} @@ -136,7 +145,8 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) { {/* Certificate Status Column */} {resource.http && resource.domainId && - resource.fullDomain && ( + resource.fullDomain && + build != "oss" && ( {t("certificateStatus", { @@ -155,6 +165,36 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) { )} + + {t("health")} + + {resource.health === "healthy" && ( +
+ + {t("resourcesTableHealthy")} +
+ )} + {resource.health === "degraded" && ( +
+ + {t("resourcesTableDegraded")} +
+ )} + {resource.health === "unhealthy" && ( +
+ + {t("resourcesTableUnhealthy")} +
+ )} + {(!resource.health || + resource.health === "unknown") && ( +
+ + {t("resourcesTableUnknown")} +
+ )} +
+
{t("visibility")} diff --git a/src/components/ResourceNotFound.tsx b/src/components/ResourceNotFound.tsx index 10859dcda..b657340cb 100644 --- a/src/components/ResourceNotFound.tsx +++ b/src/components/ResourceNotFound.tsx @@ -15,7 +15,7 @@ export default async function ResourceNotFound() { return ( - + {t("resourceNotFound")} diff --git a/src/components/ResourceSitesStatusCell.tsx b/src/components/ResourceSitesStatusCell.tsx new file mode 100644 index 000000000..4560c2f26 --- /dev/null +++ b/src/components/ResourceSitesStatusCell.tsx @@ -0,0 +1,141 @@ +"use client"; + +import { Button } from "@app/components/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger +} from "@app/components/ui/dropdown-menu"; +import { cn } from "@app/lib/cn"; +import { ChevronDown } from "lucide-react"; +import { useTranslations } from "next-intl"; +import Link from "next/link"; + +export type ResourceSiteRow = { + siteId: number; + siteName: string; + siteNiceId: string; + online?: boolean | null; +}; + +type AggregateSitesStatus = "allOnline" | "partial" | "allOffline" | "unknown"; + +function aggregateSitesStatus( + resourceSites: ResourceSiteRow[] +): AggregateSitesStatus { + if (resourceSites.length === 0) { + return "allOffline"; + } + + const knownStatuses = resourceSites + .map((rs) => rs.online) + .filter((status): status is boolean => typeof status === "boolean"); + + if (knownStatuses.length === 0) { + return "unknown"; + } + + const onlineCount = knownStatuses.filter(Boolean).length; + if (onlineCount === knownStatuses.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": + return "bg-neutral-500"; + case "unknown": + default: + return "border border-muted-foreground/50 bg-transparent"; + } +} + +export function ResourceSitesStatusCell({ + orgId, + resourceSites +}: { + orgId: string; + resourceSites: ResourceSiteRow[]; +}) { + 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; + const hasKnownStatus = typeof isOnline === "boolean"; + return ( + + +
+
+ + {site.siteName} + +
+ + {!hasKnownStatus + ? t("resourcesTableUnknown") + : isOnline + ? t("online") + : t("offline")} + + + + ); + })} + + + ); +} diff --git a/src/components/RolesDataTable.tsx b/src/components/RolesDataTable.tsx new file mode 100644 index 000000000..5a2d1cb4c --- /dev/null +++ b/src/components/RolesDataTable.tsx @@ -0,0 +1,41 @@ +"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[]; + createRole?: () => void; + onRefresh?: () => void; + isRefreshing?: boolean; +} + +export function RolesDataTable({ + columns, + data, + createRole, + onRefresh, + isRefreshing +}: DataTableProps) { + const t = useTranslations(); + + return ( + + ); +} diff --git a/src/components/Settings.tsx b/src/components/Settings.tsx index 194d8b467..e3138550b 100644 --- a/src/components/Settings.tsx +++ b/src/components/Settings.tsx @@ -38,7 +38,7 @@ export function SettingsSectionTitle({ children: React.ReactNode; }) { return ( -

+

{children}

); diff --git a/src/components/SettingsSectionTitle.tsx b/src/components/SettingsSectionTitle.tsx index 8e5073584..e1f3fcd0b 100644 --- a/src/components/SettingsSectionTitle.tsx +++ b/src/components/SettingsSectionTitle.tsx @@ -16,7 +16,7 @@ export default function SettingsSectionTitle({

{title}

diff --git a/src/components/ShowTrialCard.tsx b/src/components/ShowTrialCard.tsx index 1cc8e79f1..dc58483f8 100644 --- a/src/components/ShowTrialCard.tsx +++ b/src/components/ShowTrialCard.tsx @@ -14,7 +14,7 @@ import { } from "@app/components/ui/tooltip"; import { useTranslations } from "next-intl"; -const TRIAL_DURATION_DAYS = 14; +const TRIAL_DURATION_DAYS = 10; export default function ShowTrialCard({ isCollapsed diff --git a/src/components/SiteResourcesOverview.tsx b/src/components/SiteResourcesOverview.tsx new file mode 100644 index 000000000..080074d87 --- /dev/null +++ b/src/components/SiteResourcesOverview.tsx @@ -0,0 +1,513 @@ +"use client"; + +import CopyToClipboard from "@app/components/CopyToClipboard"; +import { Button } from "@app/components/ui/button"; +import { InfoPopup } from "@app/components/ui/info-popup"; +import { SettingsContainer } from "@app/components/Settings"; +import { useEnvContext } from "@app/hooks/useEnvContext"; +import { createApiClient } from "@app/lib/api"; +import { formatSiteResourceDestinationDisplay } from "@app/lib/formatSiteResourceAccess"; +import type { ListAllSiteResourcesByOrgResponse } from "@server/routers/siteResource"; +import type { ListResourcesResponse } from "@server/routers/resource"; +import type ResponseT from "@server/types/Response"; +import { useQuery } from "@tanstack/react-query"; +import { isAxiosError } from "axios"; +import { Loader2 } from "lucide-react"; +import { useTranslations } from "next-intl"; +import Link from "next/link"; +import { useParams } from "next/navigation"; +import { toUnicode } from "punycode"; +import { useMemo, useState, type ReactNode } from "react"; + +const INITIAL_PAGE_SIZE = 5; +const LOAD_MORE_INCREMENT = 20; + +type SiteResourceRow = + ListAllSiteResourcesByOrgResponse["siteResources"][number]; + +type PublicResourceRow = ListResourcesResponse["resources"][number]; + +function isForbidden(e: unknown): boolean { + return isAxiosError(e) && e.response?.status === 403; +} + +function isSafeUrlForLink(href: string): boolean { + try { + void new URL(href); + return true; + } catch { + return false; + } +} + +/** Meta text inside the left column (width comes from the column wrapper). */ +const OVERVIEW_META_CLASS = "w-full min-w-0 text-muted-foreground text-sm"; + +function publicProtocolLabel(r: PublicResourceRow): string { + if (r.http) { + return r.ssl ? "HTTPS" : "HTTP"; + } + const p = (r.protocol || "").toLowerCase(); + if (p === "tcp") return "TCP"; + if (p === "udp") return "UDP"; + return (r.protocol || "—").toUpperCase(); +} + +function PublicResourceMeta({ resource: r }: { resource: PublicResourceRow }) { + return ( +
+
+ {publicProtocolLabel(r)} +
+
+ ); +} + +function PrivateResourceMeta({ row }: { row: SiteResourceRow }) { + const t = useTranslations(); + const modeLabel: Record = { + host: t("editInternalResourceDialogModeHost"), + cidr: t("editInternalResourceDialogModeCidr"), + http: t("editInternalResourceDialogModeHttp") + }; + const dest = formatSiteResourceDestinationDisplay({ + mode: row.mode, + destination: row.destination, + httpHttpsPort: row.destinationPort ?? null, + scheme: row.scheme + }); + return ( +
+
+ {modeLabel[row.mode]} +
+
+ ); +} + +function PublicAccessMethod({ resource: r }: { resource: PublicResourceRow }) { + const t = useTranslations(); + if (!r.http) { + return ( + + ); + } + if (!r.domainId) { + return ( + + ); + } + const fullUrl = `${r.ssl ? "https" : "http"}://${toUnicode(r.fullDomain || "")}`; + return ( + + ); +} + +function PrivateAccessMethod({ row }: { row: SiteResourceRow }) { + if (row.mode === "http" && row.fullDomain) { + const url = `${row.ssl ? "https" : "http"}://${toUnicode(row.fullDomain)}`; + return ( + + ); + } + if (row.mode === "host" && row.alias) { + return ( + + ); + } + const fromAlias = row.alias?.trim(); + if (fromAlias) { + return ( + + ); + } + const dest = formatSiteResourceDestinationDisplay({ + mode: row.mode, + destination: row.destination, + httpHttpsPort: row.destinationPort, + scheme: row.scheme + }); + return ( + + ); +} + +type OverviewRow = { + key: number; + meta: ReactNode; + name: string; + access: ReactNode; + editHref: string; +}; + +type OverviewColumnProps = { + title: string; + description: string; + viewAllHref: string; + viewAllLabel: string; + emptyLabel: string; + isForbidden: boolean; + isFetching: boolean; + /** When there are no rows and the first fetch (no SSR initial data) is in flight. */ + isLoading: boolean; + rows: OverviewRow[]; + canShowMore: boolean; + onShowMore: () => void; +}; + +function OverviewColumn({ + title, + description, + viewAllHref, + viewAllLabel, + emptyLabel, + isForbidden, + isFetching, + isLoading, + rows, + canShowMore, + onShowMore +}: OverviewColumnProps) { + const t = useTranslations(); + + const header = ( +
+
+
+

+ {title} +

+

+ {description} +

+
+ + {viewAllLabel} + +
+
+ ); + + if (isForbidden) { + return ( +
+ {header} +

+ {t("siteResourcesPermissionDenied")} +

+
+ ); + } + + return ( +
+ {header} + {rows.length === 0 ? ( +
+ {isLoading ? ( +
+ + {t("loading")} +
+ ) : ( +

+ {emptyLabel} +

+ )} +
+ ) : ( + <> +
+
+
    + {rows.map((row) => ( +
  • +
    + {row.meta} +
    +
    +
    + {row.name} +
    +
    + {row.access} +
    +
    +
    + +
    +
  • + ))} +
+
+ {canShowMore ? ( +
+ +
+ ) : null} + + )} +
+ ); +} + +type SiteResourcesOverviewProps = { + siteId: number; + initialPublicData: ListResourcesResponse | null; + initialPrivateData: ListAllSiteResourcesByOrgResponse | null; + initialPublicForbidden: boolean; + initialPrivateForbidden: boolean; + /** When not under `/[orgId]/...` routes, pass org id explicitly (e.g. credenza on sites list). */ + orgIdOverride?: string; +}; + +export default function SiteResourcesOverview({ + siteId, + initialPublicData, + initialPrivateData, + initialPublicForbidden, + initialPrivateForbidden, + orgIdOverride +}: SiteResourcesOverviewProps) { + const t = useTranslations(); + const params = useParams<{ orgId: string }>(); + const orgId = orgIdOverride ?? params.orgId; + const { env } = useEnvContext(); + const api = useMemo(() => createApiClient({ env }), [env]); + + const enabled = Boolean(orgId && siteId); + + const [publicPageSize, setPublicPageSize] = useState(INITIAL_PAGE_SIZE); + const [privatePageSize, setPrivatePageSize] = useState(INITIAL_PAGE_SIZE); + + const publicQuery = useQuery({ + queryKey: [ + "siteResourcesOverview", + "public", + orgId, + siteId, + publicPageSize + ] as const, + enabled: enabled && !initialPublicForbidden, + initialData: initialPublicData ?? undefined, + queryFn: async (): Promise => { + const sp = new URLSearchParams({ + page: "1", + pageSize: String(publicPageSize), + siteId: String(siteId) + }); + const res = await api.get( + `/org/${orgId}/resources?${sp.toString()}` + ); + const envelope = res.data as ResponseT; + const payload = envelope.data; + if (!payload) { + throw new Error("No data"); + } + return payload; + } + }); + + const privateQuery = useQuery({ + queryKey: [ + "siteResourcesOverview", + "private", + orgId, + siteId, + privatePageSize + ] as const, + enabled: enabled && !initialPrivateForbidden, + initialData: initialPrivateData ?? undefined, + queryFn: async (): Promise => { + const sp = new URLSearchParams({ + page: "1", + pageSize: String(privatePageSize), + siteId: String(siteId) + }); + const res = await api.get( + `/org/${orgId}/site-resources?${sp.toString()}` + ); + const envelope = + res.data as ResponseT; + const payload = envelope.data; + if (!payload) { + throw new Error("No data"); + } + return payload; + } + }); + + const publicList = publicQuery.data?.resources ?? []; + const publicTotal = publicQuery.data?.pagination.total ?? 0; + const privateList = privateQuery.data?.siteResources ?? []; + const privateTotal = privateQuery.data?.pagination.total ?? 0; + + const publicForbidden = + initialPublicForbidden || + (publicQuery.isError && isForbidden(publicQuery.error)); + const privateForbidden = + initialPrivateForbidden || + (privateQuery.isError && isForbidden(privateQuery.error)); + + const waitingOnPublicList = + enabled && !publicForbidden && publicQuery.isPending; + const waitingOnPrivateList = + enabled && !privateForbidden && privateQuery.isPending; + + const showEmptyPlaceholder = + !waitingOnPublicList && + !waitingOnPrivateList && + !publicForbidden && + !privateForbidden && + publicList.length === 0 && + privateList.length === 0; + + const publicViewAllHref = `/${orgId}/settings/resources/proxy?siteId=${siteId}`; + const privateViewAllHref = `/${orgId}/settings/resources/client?siteId=${siteId}`; + + const publicRows = publicList.map((r) => ({ + key: r.resourceId, + meta: , + name: r.name, + access: , + editHref: `/${orgId}/settings/resources/proxy/${r.niceId}` + })); + + const privateRows = privateList.map((row) => { + const qs = new URLSearchParams({ + siteId: String(siteId), + query: row.niceId + }); + return { + key: row.siteResourceId, + meta: , + name: row.name, + access: , + editHref: `/${orgId}/settings/resources/client?${qs.toString()}` + }; + }); + + if (showEmptyPlaceholder) { + return ( + +

+ {t("siteResourcesNoneOnSite")} +

+
+ ); + } + + const publicEmptyLoading = + enabled && + !publicForbidden && + publicRows.length === 0 && + publicQuery.isPending; + const privateEmptyLoading = + enabled && + !privateForbidden && + privateRows.length === 0 && + privateQuery.isPending; + + const publicColumn = ( + setPublicPageSize((n) => n + LOAD_MORE_INCREMENT)} + /> + ); + + const privateColumn = ( + + setPrivatePageSize((n) => n + LOAD_MORE_INCREMENT) + } + /> + ); + + return ( + +
+ {publicColumn} + {privateColumn} +
+
+ ); +} diff --git a/src/components/SitesTable.tsx b/src/components/SitesTable.tsx index d59244552..c29314874 100644 --- a/src/components/SitesTable.tsx +++ b/src/components/SitesTable.tsx @@ -24,6 +24,7 @@ import { ArrowRight, ArrowUp10Icon, ArrowUpRight, + ChevronDown, ChevronsUpDownIcon, MoreHorizontal } from "lucide-react"; @@ -34,6 +35,16 @@ import { useState, useTransition, useEffect } from "react"; import { useDebouncedCallback } from "use-debounce"; import z from "zod"; import { ColumnFilterButton } from "./ColumnFilterButton"; +import SiteResourcesOverview from "@app/components/SiteResourcesOverview"; +import { + Credenza, + CredenzaBody, + CredenzaContent, + CredenzaDescription, + CredenzaFooter, + CredenzaHeader, + CredenzaTitle +} from "@app/components/Credenza"; import { ControlledDataTable, type ExtendedColumnDef @@ -49,11 +60,12 @@ export type SiteRow = { type: "newt" | "wireguard" | "local"; newtVersion?: string; newtUpdateAvailable?: boolean; - online: boolean; + online?: boolean | null; address?: string; exitNodeName?: string; exitNodeEndpoint?: string; remoteExitNodeId?: string; + resourceCount: number; }; type SitesTableProps = { @@ -79,6 +91,8 @@ export default function SitesTable({ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); const [selectedSite, setSelectedSite] = useState(null); + const [resourcesDialogSite, setResourcesDialogSite] = + useState(null); const [isRefreshing, startTransition] = useTransition(); const [isNavigatingToAddPage, startNavigation] = useTransition(); @@ -88,7 +102,7 @@ export default function SitesTable({ useEffect(() => { const interval = setInterval(() => { router.refresh(); - }, 10_000); + }, 30_000); return () => clearInterval(interval); }, []); @@ -239,9 +253,7 @@ export default function SitesTable({ if (originalRow.type == "local") { return -; } - return ( - - ); + return ; } }, { @@ -341,6 +353,29 @@ export default function SitesTable({ } } }, + { + id: "resources", + accessorKey: "resourceCount", + friendlyName: t("resources"), + header: () => {t("resources")}, + cell: ({ row }) => { + const siteRow = row.original; + return ( + + ); + } + }, { accessorKey: "exitNode", friendlyName: t("exitNode"), @@ -437,6 +472,22 @@ export default function SitesTable({ {t("viewSettings")} + + + {t("sitesTableViewPublicResources")} + + + + + {t("sitesTableViewPrivateResources")} + + { setSelectedSite(siteRow); @@ -489,6 +540,43 @@ export default function SitesTable({ return ( <> + { + if (!open) setResourcesDialogSite(null); + }} + > + + + {t("siteResourcesTab")} + + {t("siteResourcesDialogDescription")} + + + + {resourcesDialogSite != null && ( + + )} + + + + + + + {selectedSite && ( = { good: "bg-green-500", degraded: "bg-yellow-500", bad: "bg-red-500", - no_data: "bg-neutral-200 dark:bg-neutral-700" + no_data: "bg-neutral-200 dark:bg-neutral-700", + unknown: "bg-neutral-200 dark:bg-neutral-700" }; type UptimeBarProps = { @@ -188,7 +189,7 @@ export default function UptimeBar({
{formatDate(day.date)}
- {day.status !== "no_data" && ( + {day.status !== "no_data" && day.status !== "unknown" && (
{t("uptimeTooltipUptimeLabel")}:{" "} @@ -224,7 +225,7 @@ export default function UptimeBar({ ))}
)} - {day.status === "no_data" && ( + {(day.status === "no_data" || day.status === "unknown") && (
{t("uptimeNoMonitoringData")}
diff --git a/src/components/UptimeMiniBar.tsx b/src/components/UptimeMiniBar.tsx index b4c8aa3bd..b7e684c8b 100644 --- a/src/components/UptimeMiniBar.tsx +++ b/src/components/UptimeMiniBar.tsx @@ -34,7 +34,8 @@ const barColorClass: Record = { good: "bg-green-500", degraded: "bg-yellow-500", bad: "bg-red-500", - no_data: "bg-neutral-200 dark:bg-neutral-700" + no_data: "bg-neutral-200 dark:bg-neutral-700", + unknown: "bg-neutral-200 dark:bg-neutral-700" }; type UptimeMiniBarProps = { @@ -137,7 +138,7 @@ export default function UptimeMiniBar({ {formatDate(day.date)}
- {day.status === "no_data" + {day.status === "no_data" || day.status === "unknown" ? t("uptimeNoData") : `${day.uptimePercent.toFixed(1)}% ${t("uptimeSuffix")}`}
diff --git a/src/components/UserDevicesTable.tsx b/src/components/UserDevicesTable.tsx index 88e495406..0a130cc16 100644 --- a/src/components/UserDevicesTable.tsx +++ b/src/components/UserDevicesTable.tsx @@ -35,6 +35,7 @@ import { useMemo, useState, useTransition } from "react"; import { useDebouncedCallback } from "use-debounce"; import ClientDownloadBanner from "./ClientDownloadBanner"; import { ColumnFilterButton } from "./ColumnFilterButton"; +import IdpTypeBadge from "./IdpTypeBadge"; import { Badge } from "./ui/badge"; import { ControlledDataTable } from "./ui/controlled-data-table"; @@ -52,6 +53,9 @@ export type ClientRow = { userId: string | null; username: string | null; userEmail: string | null; + userType: string | null; + idpName: string | null; + idpVariant: string | null; niceId: string; agent: string | null; approvalState: "approved" | "pending" | "denied" | null; @@ -370,17 +374,30 @@ export default function UserDevicesTable({ cell: ({ row }) => { const r = row.original; return r.userId ? ( - - - +
+ + + + {(r.userType ?? "internal") !== "internal" && ( + + )} +
) : ( "-" ); diff --git a/src/components/UsersDataTable.tsx b/src/components/UsersDataTable.tsx new file mode 100644 index 000000000..ececa4c17 --- /dev/null +++ b/src/components/UsersDataTable.tsx @@ -0,0 +1,41 @@ +"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/alert-rule-editor/AlertRuleFields.tsx b/src/components/alert-rule-editor/AlertRuleFields.tsx index 99ad862fe..eac0a72f6 100644 --- a/src/components/alert-rule-editor/AlertRuleFields.tsx +++ b/src/components/alert-rule-editor/AlertRuleFields.tsx @@ -1110,6 +1110,7 @@ export function AlertRuleSourceFields({ if ( curTrigger !== "resource_healthy" && curTrigger !== "resource_unhealthy" && + curTrigger !== "resource_degraded" && curTrigger !== "resource_toggle" ) { setValue("trigger", "resource_toggle", { @@ -1330,6 +1331,9 @@ export function AlertRuleTriggerFields({ {t("alertingTriggerResourceUnhealthy")} + + {t("alertingTriggerResourceDegraded")} + ) : ( <> diff --git a/src/components/multi-site-selector.tsx b/src/components/multi-site-selector.tsx index c06f6c74a..76255e824 100644 --- a/src/components/multi-site-selector.tsx +++ b/src/components/multi-site-selector.tsx @@ -111,11 +111,13 @@ export function MultiSitesSelector({ {site.name} - + {site.online != null && ( + + )}
))} diff --git a/src/components/newt-install-commands.tsx b/src/components/newt-install-commands.tsx index 28581794c..ae378a0f4 100644 --- a/src/components/newt-install-commands.tsx +++ b/src/components/newt-install-commands.tsx @@ -77,8 +77,12 @@ sudo install -d -m 0755 /etc/newt sudo tee /etc/newt/newt.env > /dev/null << 'EOF' NEWT_ID=${id} NEWT_SECRET=${secret} -PANGOLIN_ENDPOINT=${endpoint}${!acceptClients ? ` -DISABLE_CLIENTS=true` : ""} +PANGOLIN_ENDPOINT=${endpoint}${ + !acceptClients + ? ` +DISABLE_CLIENTS=true` + : "" + } EOF sudo chmod 600 /etc/newt/newt.env` }, @@ -232,9 +236,7 @@ WantedBy=default.target` label={ - platform === "windows" - ? t("architecture") - : t("method") + platform === "windows" ? t("architecture") : t("method") } options={getArchitectures(platform).map((arch) => ({ value: arch, @@ -247,7 +249,9 @@ WantedBy=default.target` />
-

{t("siteConfiguration")}

+

+ {t("siteConfiguration")} +

-

{t("commands")}

+

{t("commands")}

{platform === "kubernetes" && (

For more and up to date Kubernetes installation diff --git a/src/components/olm-install-commands.tsx b/src/components/olm-install-commands.tsx index 38bd8e97b..f13a9b6ef 100644 --- a/src/components/olm-install-commands.tsx +++ b/src/components/olm-install-commands.tsx @@ -122,9 +122,7 @@ curl -o olm.exe -L "https://github.com/fosrl/olm/releases/download/${version}/ol label={ - platform === "docker" - ? t("method") - : t("architecture") + platform === "docker" ? t("method") : t("architecture") } options={getArchitectures(platform).map((arch) => ({ value: arch, @@ -137,33 +135,31 @@ curl -o olm.exe -L "https://github.com/fosrl/olm/releases/download/${version}/ol />

-

{t("commands")}

-
- {commands.map((item, index) => { - const commandText = - typeof item === "string" - ? item - : item.command; - const title = - typeof item === "string" - ? undefined - : item.title; +

{t("commands")}

+
+ {commands.map((item, index) => { + const commandText = + typeof item === "string" ? item : item.command; + const title = + typeof item === "string" + ? undefined + : item.title; - return ( -
- {title && ( -

- {title} -

- )} - -
- ); - })} -
+ return ( +
+ {title && ( +

+ {title} +

+ )} + +
+ ); + })} +
diff --git a/src/components/resource-selector.tsx b/src/components/resource-selector.tsx index 96044a8d2..b01263333 100644 --- a/src/components/resource-selector.tsx +++ b/src/components/resource-selector.tsx @@ -17,19 +17,21 @@ import { useDebounce } from "use-debounce"; export type SelectedResource = Pick< ListResourcesResponse["resources"][number], - "name" | "resourceId" | "fullDomain" | "niceId" | "ssl" + "name" | "resourceId" | "fullDomain" | "niceId" | "ssl" | "wildcard" >; export type ResourceSelectorProps = { orgId: string; selectedResource?: SelectedResource | null; onSelectResource: (resource: SelectedResource) => void; + excludeWildcard?: boolean; }; export function ResourceSelector({ orgId, selectedResource, - onSelectResource + onSelectResource, + excludeWildcard = false }: ResourceSelectorProps) { const t = useTranslations(); const [resourceSearchQuery, setResourceSearchQuery] = useState(""); @@ -46,10 +48,13 @@ export function ResourceSelector({ // always include the selected resource in the list of resources shown const resourcesShown = useMemo(() => { - const allResources: Array = [...resources]; + const allResources: Array = excludeWildcard + ? resources.filter((r) => !r.wildcard) + : [...resources]; if ( debouncedSearchQuery.trim().length === 0 && selectedResource && + !(excludeWildcard && selectedResource.wildcard) && !allResources.find( (resource) => resource.resourceId === selectedResource?.resourceId @@ -58,7 +63,7 @@ export function ResourceSelector({ allResources.unshift(selectedResource); } return allResources; - }, [debouncedSearchQuery, resources, selectedResource]); + }, [debouncedSearchQuery, resources, selectedResource, excludeWildcard]); return ( diff --git a/src/components/resource-target-address-item.tsx b/src/components/resource-target-address-item.tsx index c801844ce..08ce40dd3 100644 --- a/src/components/resource-target-address-item.tsx +++ b/src/components/resource-target-address-item.tsx @@ -104,7 +104,7 @@ export function ResourceTargetAddressItem({ role="combobox" className={cn( "w-45 justify-between text-sm border-r pr-4 rounded-none h-8 hover:bg-transparent", - "rounded-l-md rounded-r-xs", + "", !proxyTarget.siteId && "text-muted-foreground" )} > @@ -142,7 +142,7 @@ export function ResourceTargetAddressItem({ }) } > - + {proxyTarget.method || "http"} diff --git a/src/components/site-selector.tsx b/src/components/site-selector.tsx index 1c6302d98..778a6fcf6 100644 --- a/src/components/site-selector.tsx +++ b/src/components/site-selector.tsx @@ -124,11 +124,13 @@ export function SitesSelector({ {site.name} - + {site.online != null && ( + + )}
))} diff --git a/src/components/tags/tag.tsx b/src/components/tags/tag.tsx index 0a35b3746..30ba984dd 100644 --- a/src/components/tags/tag.tsx +++ b/src/components/tags/tag.tsx @@ -57,7 +57,7 @@ export const tagVariants = cva( }, textStyle: { normal: "font-normal", - bold: "font-bold", + bold: "font-semibold", italic: "italic", underline: "underline", lineThrough: "line-through" diff --git a/src/components/ui/checkbox.tsx b/src/components/ui/checkbox.tsx index 5cffd8978..3111afbf4 100644 --- a/src/components/ui/checkbox.tsx +++ b/src/components/ui/checkbox.tsx @@ -20,7 +20,7 @@ const checkboxVariants = cva( outlinePrimarySquare: "border rounded-[5px] border-input data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground", outlineSquare: - "border rounded-[5px] border-input data-[state=checked]:border-primary data-[state=checked]:bg-muted data-[state=checked]:text-accent-foreground" + "border rounded-[5px] border-input data-[state=checked]:border-primary data-[state=checked]:bg-muted data-[state=checked]:text-foreground" } }, defaultVariants: { @@ -44,7 +44,7 @@ const Checkbox = React.forwardRef< {...props} > - + )); diff --git a/src/components/ui/controlled-data-table.tsx b/src/components/ui/controlled-data-table.tsx index 5f17f1887..3599917aa 100644 --- a/src/components/ui/controlled-data-table.tsx +++ b/src/components/ui/controlled-data-table.tsx @@ -33,6 +33,7 @@ import { } from "@app/components/ui/dropdown-menu"; import { Input } from "@app/components/ui/input"; import { useStoredColumnVisibility } from "@app/hooks/useStoredColumnVisibility"; +import { dataTableFilterDropdownContentClassName } from "@app/lib/dataTableFilterPopover"; import { ChevronDown, @@ -345,7 +346,9 @@ export function ControlledDataTable({ {filter.label} diff --git a/src/components/ui/data-table.tsx b/src/components/ui/data-table.tsx index 2b2861bb5..673388454 100644 --- a/src/components/ui/data-table.tsx +++ b/src/components/ui/data-table.tsx @@ -34,6 +34,7 @@ import { Button } from "@app/components/ui/button"; import { useEffect, useMemo, useRef, useState } from "react"; import { Input } from "@app/components/ui/input"; import { DataTablePagination } from "@app/components/DataTablePagination"; +import { dataTableFilterDropdownContentClassName } from "@app/lib/dataTableFilterPopover"; import { ChevronDown, Plus, Search, RefreshCw, Columns, Filter } from "lucide-react"; import { Card, @@ -603,7 +604,9 @@ export function DataTable({ {filter.label} diff --git a/src/fonts/mona-sans/MonaSans-Bold.ttf b/src/fonts/mona-sans/MonaSans-Bold.ttf new file mode 100644 index 000000000..e0591eb20 Binary files /dev/null and b/src/fonts/mona-sans/MonaSans-Bold.ttf differ diff --git a/src/fonts/mona-sans/MonaSans-Bold.woff2 b/src/fonts/mona-sans/MonaSans-Bold.woff2 new file mode 100644 index 000000000..1f86963d9 Binary files /dev/null and b/src/fonts/mona-sans/MonaSans-Bold.woff2 differ diff --git a/src/fonts/mona-sans/MonaSans-Italic-VariableFont_wdth,wght.ttf b/src/fonts/mona-sans/MonaSans-Italic-VariableFont_wdth,wght.ttf new file mode 100644 index 000000000..00bc96dea Binary files /dev/null and b/src/fonts/mona-sans/MonaSans-Italic-VariableFont_wdth,wght.ttf differ diff --git a/src/fonts/mona-sans/MonaSans-Medium.ttf b/src/fonts/mona-sans/MonaSans-Medium.ttf new file mode 100644 index 000000000..c10690aae Binary files /dev/null and b/src/fonts/mona-sans/MonaSans-Medium.ttf differ diff --git a/src/fonts/mona-sans/MonaSans-Medium.woff2 b/src/fonts/mona-sans/MonaSans-Medium.woff2 new file mode 100644 index 000000000..24fa40811 Binary files /dev/null and b/src/fonts/mona-sans/MonaSans-Medium.woff2 differ diff --git a/src/fonts/mona-sans/MonaSans-Regular.ttf b/src/fonts/mona-sans/MonaSans-Regular.ttf new file mode 100644 index 000000000..91fbf9e22 Binary files /dev/null and b/src/fonts/mona-sans/MonaSans-Regular.ttf differ diff --git a/src/fonts/mona-sans/MonaSans-Regular.woff2 b/src/fonts/mona-sans/MonaSans-Regular.woff2 new file mode 100644 index 000000000..69ee83758 Binary files /dev/null and b/src/fonts/mona-sans/MonaSans-Regular.woff2 differ diff --git a/src/fonts/mona-sans/MonaSans-SemiBold.ttf b/src/fonts/mona-sans/MonaSans-SemiBold.ttf new file mode 100644 index 000000000..092959a3a Binary files /dev/null and b/src/fonts/mona-sans/MonaSans-SemiBold.ttf differ diff --git a/src/fonts/mona-sans/MonaSans-SemiBold.woff2 b/src/fonts/mona-sans/MonaSans-SemiBold.woff2 new file mode 100644 index 000000000..82fbcedcf Binary files /dev/null and b/src/fonts/mona-sans/MonaSans-SemiBold.woff2 differ diff --git a/src/fonts/mona-sans/MonaSans-VariableFont_wdth,wght.ttf b/src/fonts/mona-sans/MonaSans-VariableFont_wdth,wght.ttf new file mode 100644 index 000000000..a49f373ec Binary files /dev/null and b/src/fonts/mona-sans/MonaSans-VariableFont_wdth,wght.ttf differ diff --git a/src/fonts/mona-sans/MonaSansVF[wdth,wght,opsz,ital].woff2 b/src/fonts/mona-sans/MonaSansVF[wdth,wght,opsz,ital].woff2 new file mode 100644 index 000000000..576f498c1 Binary files /dev/null and b/src/fonts/mona-sans/MonaSansVF[wdth,wght,opsz,ital].woff2 differ diff --git a/src/hooks/useCertificate.ts b/src/hooks/useCertificate.ts index f5c1429df..cd0802ef0 100644 --- a/src/hooks/useCertificate.ts +++ b/src/hooks/useCertificate.ts @@ -20,7 +20,7 @@ type UseCertificateReturn = { certLoading: boolean; certError: string | null; refreshing: boolean; - fetchCert: () => Promise; + fetchCert: (showLoading?: boolean) => Promise; refreshCert: () => Promise; clearCert: () => void; }; @@ -47,18 +47,18 @@ export function useCertificate({ if (showLoading) { setCertLoading(true); } - setCertError(null); try { const res = await api.get< AxiosResponse >(`/org/${orgId}/certificate/${domainId}/${fullDomain}`); const certData = res.data.data; if (certData) { + setCertError(null); setCert(certData); } } catch (error: any) { console.error("Failed to fetch certificate:", error); - setCertError("Failed to fetch certificate"); + setCertError("Failed"); } finally { if (showLoading) { setCertLoading(false); @@ -84,7 +84,7 @@ export function useCertificate({ }, 500); } catch (error: any) { console.error("Failed to restart certificate:", error); - setCertError("Failed to restart certificate"); + setCertError("Failed to restart"); } finally { setRefreshing(false); } @@ -102,15 +102,33 @@ export function useCertificate({ } }, [autoFetch, orgId, domainId, fullDomain, fetchCert]); - // Polling effect useEffect(() => { if (!polling || !orgId || !domainId || !fullDomain) return; - const interval = setInterval(() => { - fetchCert(false); // Don't show loading for polling - }, pollingInterval); + const POLL_JITTER_MS = 1000; + let cancelled = false; + let timeoutId: ReturnType; - return () => clearInterval(interval); + const scheduleNext = () => { + const jitter = (Math.random() * 2 - 1) * POLL_JITTER_MS; + const delayMs = Math.max( + 1000, + Math.round(pollingInterval + jitter) + ); + + timeoutId = setTimeout(() => { + if (cancelled) return; + void fetchCert(false); + scheduleNext(); + }, delayMs); + }; + + scheduleNext(); + + return () => { + cancelled = true; + clearTimeout(timeoutId); + }; }, [polling, orgId, domainId, fullDomain, pollingInterval, fetchCert]); return { diff --git a/src/hooks/useSubscriptionStatusContext.ts b/src/hooks/useSubscriptionStatusContext.ts index 59d6a6b9a..2fd61dd2e 100644 --- a/src/hooks/useSubscriptionStatusContext.ts +++ b/src/hooks/useSubscriptionStatusContext.ts @@ -8,9 +8,7 @@ export function useSubscriptionStatusContext() { } const context = useContext(SubscriptionStatusContext); if (context === undefined) { - throw new Error( - "useSubscriptionStatusContext must be used within an SubscriptionStatusProvider" - ); + return null; } return context; } diff --git a/src/lib/alertRuleForm.ts b/src/lib/alertRuleForm.ts index 111487c48..039c367b6 100644 --- a/src/lib/alertRuleForm.ts +++ b/src/lib/alertRuleForm.ts @@ -25,6 +25,7 @@ export type AlertTrigger = | "health_check_toggle" | "resource_healthy" | "resource_unhealthy" + | "resource_degraded" | "resource_toggle"; export type AlertRuleFormAction = @@ -77,6 +78,7 @@ export type AlertRuleApiPayload = { | "health_check_toggle" | "resource_healthy" | "resource_unhealthy" + | "resource_degraded" | "resource_toggle"; enabled: boolean; allSites: boolean; @@ -160,6 +162,7 @@ export function buildFormSchema(t: (k: string) => string) { "health_check_toggle", "resource_healthy", "resource_unhealthy", + "resource_degraded", "resource_toggle" ]), actions: z.array( @@ -243,6 +246,7 @@ export function buildFormSchema(t: (k: string) => string) { const resourceTriggers: AlertTrigger[] = [ "resource_healthy", "resource_unhealthy", + "resource_degraded", "resource_toggle" ]; if ( @@ -344,7 +348,9 @@ export function alertRuleAllResourcesSelected( eventType: string, resourceIds: number[] | undefined ): boolean { - return eventType.startsWith("resource_") && (resourceIds?.length ?? 0) === 0; + return ( + eventType.startsWith("resource_") && (resourceIds?.length ?? 0) === 0 + ); } export function alertRuleAllHealthChecksSelected( diff --git a/src/lib/alertRulesLocalStorage.ts b/src/lib/alertRulesLocalStorage.ts new file mode 100644 index 000000000..2471219b0 --- /dev/null +++ b/src/lib/alertRulesLocalStorage.ts @@ -0,0 +1,129 @@ +import { z } from "zod"; + +const STORAGE_PREFIX = "pangolin:alert-rules:"; + +export const webhookHeaderEntrySchema = z.object({ + key: z.string(), + value: z.string() +}); + +export const alertActionSchema = z.discriminatedUnion("type", [ + z.object({ + type: z.literal("notify"), + userIds: z.array(z.string()), + roleIds: z.array(z.number()), + emails: z.array(z.string()) + }), + z.object({ + type: z.literal("webhook"), + url: z.string().url(), + method: z.string().min(1), + headers: z.array(webhookHeaderEntrySchema), + secret: z.string().optional() + }) +]); + +export const alertSourceSchema = z.discriminatedUnion("type", [ + z.object({ + type: z.literal("site"), + siteIds: z.array(z.number()) + }), + z.object({ + type: z.literal("health_check"), + targetIds: z.array(z.number()) + }) +]); + +export const alertTriggerSchema = z.enum([ + "site_online", + "site_offline", + "health_check_healthy", + "health_check_unhealthy" +]); + +export const alertRuleSchema = z.object({ + id: z.string().uuid(), + name: z.string().min(1).max(255), + enabled: z.boolean(), + createdAt: z.string(), + updatedAt: z.string(), + source: alertSourceSchema, + trigger: alertTriggerSchema, + actions: z.array(alertActionSchema).min(1) +}); + +export type AlertRule = z.infer; +export type AlertAction = z.infer; +export type AlertTrigger = z.infer; + +function storageKey(orgId: string) { + return `${STORAGE_PREFIX}${orgId}`; +} + +export function getRule(orgId: string, ruleId: string): AlertRule | undefined { + return loadRules(orgId).find((r) => r.id === ruleId); +} + +export function loadRules(orgId: string): AlertRule[] { + if (typeof window === "undefined") { + return []; + } + try { + const raw = localStorage.getItem(storageKey(orgId)); + if (!raw) { + return []; + } + const parsed = JSON.parse(raw) as unknown; + if (!Array.isArray(parsed)) { + return []; + } + const out: AlertRule[] = []; + for (const item of parsed) { + const r = alertRuleSchema.safeParse(item); + if (r.success) { + out.push(r.data); + } + } + return out; + } catch { + return []; + } +} + +export function saveRules(orgId: string, rules: AlertRule[]) { + if (typeof window === "undefined") { + return; + } + localStorage.setItem(storageKey(orgId), JSON.stringify(rules)); +} + +export function upsertRule(orgId: string, rule: AlertRule) { + const rules = loadRules(orgId); + const i = rules.findIndex((r) => r.id === rule.id); + if (i >= 0) { + rules[i] = rule; + } else { + rules.push(rule); + } + saveRules(orgId, rules); +} + +export function deleteRule(orgId: string, ruleId: string) { + const rules = loadRules(orgId).filter((r) => r.id !== ruleId); + saveRules(orgId, rules); +} + +export function newRuleId() { + if (typeof crypto !== "undefined" && crypto.randomUUID) { + return crypto.randomUUID(); + } + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { + const r = (Math.random() * 16) | 0; + const v = c === "x" ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +} + +export function isoNow() { + return new Date().toISOString(); +} diff --git a/src/lib/dataTableFilterPopover.ts b/src/lib/dataTableFilterPopover.ts new file mode 100644 index 000000000..606527209 --- /dev/null +++ b/src/lib/dataTableFilterPopover.ts @@ -0,0 +1,5 @@ +export const dataTableFilterPopoverContentClassName = + "w-[min(16rem,calc(100vw-2rem))] p-0"; + +export const dataTableFilterDropdownContentClassName = + "w-[min(16rem,calc(100vw-2rem))]"; diff --git a/src/lib/formatSiteResourceAccess.ts b/src/lib/formatSiteResourceAccess.ts new file mode 100644 index 000000000..b6fefa1d8 --- /dev/null +++ b/src/lib/formatSiteResourceAccess.ts @@ -0,0 +1,32 @@ +export type SiteResourceDestinationInput = { + mode: "host" | "cidr" | "http"; + destination: string; + httpHttpsPort: number | null; + scheme: "http" | "https" | null; +}; + +export function resolveHttpHttpsDisplayPort( + mode: "http", + httpHttpsPort: number | null +): number { + if (httpHttpsPort != null) { + return httpHttpsPort; + } + return 80; +} + +export function formatSiteResourceDestinationDisplay( + row: SiteResourceDestinationInput +): 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}`; +} diff --git a/src/lib/subdomain-utils.ts b/src/lib/subdomain-utils.ts index 10c027a89..1c5e79207 100644 --- a/src/lib/subdomain-utils.ts +++ b/src/lib/subdomain-utils.ts @@ -5,16 +5,58 @@ export const MULTI_LABEL_RE = /^[\p{L}\p{N}-]+(\.[\p{L}\p{N}-]+)*$/u; // ns/wild export const SINGLE_LABEL_STRICT_RE = /^[\p{L}\p{N}](?:[\p{L}\p{N}-]*[\p{L}\p{N}])?$/u; // start/end alnum -export function sanitizeInputRaw(input: string): string { +/** + * A wildcard subdomain is either bare "*" or "*.label1.label2…" where every + * label after the dot is a valid hostname label. This mirrors the shape that + * the server's `wildcardSubdomainSchema` accepts. + */ +export const WILDCARD_SUBDOMAIN_RE = + /^\*(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*$/; + +export function isWildcardSubdomain(input: string): boolean { + return WILDCARD_SUBDOMAIN_RE.test(input); +} + +export function sanitizeInputRaw(input: string, allowWildcard = false): string { if (!input) return ""; + // When wildcard mode is active, preserve a leading "* " / "*." prefix and + // only sanitize the remainder so the user can type "*.level1" naturally. + if (allowWildcard && input.startsWith("*")) { + const rest = input.slice(1); + const sanitizedRest = rest + .toLowerCase() + .normalize("NFC") + .replace(/[^\p{L}\p{N}.-]/gu, ""); + return "*" + sanitizedRest; + } return input .toLowerCase() .normalize("NFC") // normalize Unicode .replace(/[^\p{L}\p{N}.-]/gu, ""); // allow Unicode letters, numbers, dot, hyphen } -export function finalizeSubdomainSanitize(input: string): string { +export function finalizeSubdomainSanitize( + input: string, + allowWildcard = false +): string { if (!input) return ""; + + // If the input is a valid wildcard and the caller permits it, keep it as-is + // (just lowercase the non-wildcard labels). + if (allowWildcard && input.startsWith("*")) { + const rest = input.slice(1); // everything after the leading "*" + const sanitizedRest = rest + .toLowerCase() + .normalize("NFC") + .replace(/[^\p{L}\p{N}.-]/gu, "") + .replace(/\.{2,}/g, ".") + .replace(/^-+|-+$/g, "") + .replace(/(\.-)|(-\.)/g, "."); + const candidate = "*" + sanitizedRest; + // Return only if it still forms a valid wildcard after sanitizing + return isWildcardSubdomain(candidate) ? candidate : ""; + } + return input .toLowerCase() .normalize("NFC") @@ -30,6 +72,7 @@ export function validateByDomainType( domainType: { type: "provided-search" | "organization"; domainType?: "ns" | "cname" | "wildcard"; + allowWildcard?: boolean; } ): boolean { if (!domainType) return false; @@ -46,6 +89,12 @@ export function validateByDomainType( domainType.domainType === "wildcard" ) { if (subdomain === "") return true; + + // Wildcard subdomain validation (only when caller opts in) + if (domainType.allowWildcard && subdomain.startsWith("*")) { + return isWildcardSubdomain(subdomain); + } + if (!MULTI_LABEL_RE.test(subdomain)) return false; const labels = subdomain.split("."); return labels.every( @@ -57,10 +106,19 @@ export function validateByDomainType( return false; } -export const isValidSubdomainStructure = (input: string): boolean => { +export const isValidSubdomainStructure = ( + input: string, + allowWildcard = false +): boolean => { + if (!input) return false; + + // A valid wildcard subdomain is structurally valid when the caller allows it + if (allowWildcard && input.startsWith("*")) { + return isWildcardSubdomain(input); + } + const regex = /^(?!-)([\p{L}\p{N}-]{1,63})(? regex.test(label));