Merge pull request #3826 from fosrl/dev

1.24.0
This commit is contained in:
Owen Schwartz
2026-09-28 20:40:08 -04:00
committed by GitHub
103 changed files with 2576 additions and 676 deletions
+18 -11
View File
@@ -3,18 +3,25 @@ name: ESLint
permissions:
contents: read
# Disabled from running on PRs: typescript-eslint does not yet support
# TypeScript 7 (which this repo is on), so eslint currently crashes on
# every run. Kept as workflow_dispatch so it can still be triggered
# manually, and re-enabled on pull_request once upstream support lands.
# https://github.com/typescript-eslint/typescript-eslint/issues/10940
# on:
# pull_request:
# paths:
# - '**/*.js'
# - '**/*.jsx'
# - '**/*.ts'
# - '**/*.tsx'
# - '.eslintrc*'
# - 'package.json'
# - 'yarn.lock'
# - 'pnpm-lock.yaml'
# - 'package-lock.json'
on:
pull_request:
paths:
- '**/*.js'
- '**/*.jsx'
- '**/*.ts'
- '**/*.tsx'
- '.eslintrc*'
- 'package.json'
- 'yarn.lock'
- 'pnpm-lock.yaml'
- 'package-lock.json'
workflow_dispatch:
jobs:
Linter:
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "Инсталирайте Newt",
"siteInstallNewtDescription": "Пуснете Newt на вашата система",
"siteInstallKubernetesDocsDescription": "За повече и актуална информация относно инсталацията на Kubernetes, вижте <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>.",
"siteInstallAdvantechDocsDescription": "За инструкции за инсталиране на Advantech модем, вижте <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>.",
"siteInstallAdvantechDocsDescription": "За инструкции за инсталиране на Advantech модем, вижте <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>.",
"WgConfiguration": "WireGuard конфигурация",
"WgConfigurationDescription": "Използвайте следната конфигурация, за да се свържете с мрежата",
"operatingSystem": "Операционна система",
@@ -2826,8 +2826,10 @@
"retryAttempts": "Опити за повторно",
"expectedResponseCodes": "Очаквани кодове за отговор",
"expectedResponseCodesDescription": "HTTP статус код, указващ здравословно състояние. Ако бъде оставено празно, между 200-300 се счита за здравословно.",
"customHeaders": "Персонализирани заглавия",
"customHeadersDescription": "Add custom headers to be sent when proxying requests. One per line in the format Header-Name: value",
"customRequestHeaders": "Персонализирани заглавия на заявката",
"customRequestHeadersDescription": "Заглавия на заявката, изпратени до целевите сървъри. По едно на ред: Заглавие-Име: стойност",
"customResponseHeaders": "Персонализирани заглавия на отговора",
"customResponseHeadersDescription": "Заглавия на отговора, върнати на клиента. По едно на ред: Заглавие-Име: стойност",
"headersValidationError": "Заглавията трябва да бъдат във формат: Име на заглавието: стойност.",
"saveHealthCheck": "Запазване на проверка на здравето",
"healthCheckSaved": "Проверка на здравето е запазена",
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "Nainstalovat Newt",
"siteInstallNewtDescription": "Spustit Newt na vašem systému",
"siteInstallKubernetesDocsDescription": "Pro více aktuálních informací o instalaci Kubernetes navštivte <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>.",
"siteInstallAdvantechDocsDescription": "Pro pokyny k instalaci modemu Advantech navštivte <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>.",
"siteInstallAdvantechDocsDescription": "Pro pokyny k instalaci modemu Advantech navštivte <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>.",
"WgConfiguration": "Konfigurace WireGuard",
"WgConfigurationDescription": "K připojení k síti použijte následující konfiguraci",
"operatingSystem": "Operační systém",
@@ -2826,8 +2826,10 @@
"retryAttempts": "Opakovat pokusy",
"expectedResponseCodes": "Očekávané kódy odezvy",
"expectedResponseCodesDescription": "HTTP kód stavu, který označuje zdravý stav. Ponecháte-li prázdné, 200-300 je považováno za zdravé.",
"customHeaders": "Vlastní záhlaví",
"customHeadersDescription": "Záhlaví oddělená nová řádka: hodnota",
"customRequestHeaders": "Vlastní záhlaví požadavku",
"customRequestHeadersDescription": "Záhlaví požadavku odeslaná do cílů. Jedno na řádek: Název-záhlaví: hodnota",
"customResponseHeaders": "Vlastní záhlaví odpovědi",
"customResponseHeadersDescription": "Záhlaví odpovědi vrácená klientovi. Jedno na řádek: Název-záhlaví: hodnota",
"headersValidationError": "Headers must be in the format: Header-Name: value.",
"saveHealthCheck": "Uložit kontrolu stavu",
"healthCheckSaved": "Kontrola stavu uložena",
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "Installer Newt",
"siteInstallNewtDescription": "Få Newt til at køre på dit system",
"siteInstallKubernetesDocsDescription": "For mere og opdateret information om Kubernetes-installation, se <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>.",
"siteInstallAdvantechDocsDescription": "For installationsvejledning til Advantech-modemmer, se <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>.",
"siteInstallAdvantechDocsDescription": "For installationsvejledning til Advantech-modemmer, se <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>.",
"WgConfiguration": "WireGuard Konfiguration",
"WgConfigurationDescription": "Brug følgende konfiguration til at oprette forbindelse til netværket.",
"operatingSystem": "Operativsystem",
@@ -2826,8 +2826,10 @@
"retryAttempts": "Forsøg igen",
"expectedResponseCodes": "Forventede svarkoder",
"expectedResponseCodesDescription": "HTTP-statuskode som indikerer sund status. Hvis den bliver stående tom, regnes 200-300 som sund.",
"customHeaders": "Brugerdefinerede headers",
"customHeadersDescription": "Headers som er adskilt med linje: Overskriftsnavn: værdi",
"customRequestHeaders": "Brugerdefinerede anmodnings-headers",
"customRequestHeadersDescription": "Anmodnings-headers som sendes til destinationerne. Én pr. linje: Header-navn: værdi",
"customResponseHeaders": "Brugerdefinerede svar-headers",
"customResponseHeadersDescription": "Svar-headers som sendes tilbage til klienten. Én pr. linje: Header-navn: værdi",
"headersValidationError": "Header skal være i formatet: header-navn: værdi.",
"saveHealthCheck": "Gem Sundhedstjek",
"healthCheckSaved": "Sundhedstjek Gemt",
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "Newt installieren",
"siteInstallNewtDescription": "Installiere Newt auf deinem System.",
"siteInstallKubernetesDocsDescription": "Für aktuelle Installationsinformationen zu Kubernetes, siehe <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>.",
"siteInstallAdvantechDocsDescription": "Für Installationsanweisungen für Advantech-Modems siehe <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>.",
"siteInstallAdvantechDocsDescription": "Für Installationsanweisungen für Advantech-Modems siehe <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>.",
"WgConfiguration": "WireGuard Konfiguration",
"WgConfigurationDescription": "Verwenden Sie folgende Konfiguration, um sich mit dem Netzwerk zu verbinden",
"operatingSystem": "Betriebssystem",
@@ -2826,8 +2826,10 @@
"retryAttempts": "Wiederholungsversuche",
"expectedResponseCodes": "Erwartete Antwortcodes",
"expectedResponseCodesDescription": "HTTP-Statuscode, der einen gesunden Zustand anzeigt. Wenn leer gelassen, wird 200-300 als gesund angesehen.",
"customHeaders": "Eigene Kopfzeilen",
"customHeadersDescription": "Header neue Zeile getrennt: Header-Name: Wert",
"customRequestHeaders": "Eigene Anfrage-Header",
"customRequestHeadersDescription": "Anfrage-Header, die an die Ziele gesendet werden. Eine pro Zeile: Header-Name: Wert",
"customResponseHeaders": "Eigene Antwort-Header",
"customResponseHeadersDescription": "Antwort-Header, die an den Client zurückgesendet werden. Eine pro Zeile: Header-Name: Wert",
"headersValidationError": "Header müssen im Format Header-Name: Wert sein.",
"saveHealthCheck": "Gesundheits-Check speichern",
"healthCheckSaved": "Gesundheits-Check gespeichert",
+36 -12
View File
@@ -26,7 +26,7 @@
"trialBannerMessage": "Your trial expires in {countdown}. Upgrade to keep access.",
"trialBannerExpired": "Your trial has expired. Upgrade now to restore access.",
"billingTrialBannerTitle": "Free Trial Active",
"billingTrialBannerDescription": "You're currently on a free trial on the business tier. When the trial ends, your account will automatically revert to the Basic tier features and limits. Upgrade anytime to keep access to your current plan's features.",
"billingTrialBannerDescription": "You're currently on a free trial on the {tier} tier. When the trial ends, your account will automatically revert to the Basic tier features and limits. Upgrade anytime to keep access to your current plan's features.",
"billingTrialBannerUpgrade": "Upgrade Now",
"billingTrialBadge": "Free Trial",
"trialActive": "Free Trial Active",
@@ -110,7 +110,7 @@
"siteInstallNewt": "Install Site",
"siteInstallNewtDescription": "Install the site connector for your system",
"siteInstallKubernetesDocsDescription": "For more and up to date Kubernetes installation information, see <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>.",
"siteInstallAdvantechDocsDescription": "For Advantech modem installation instructions, see <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>.",
"siteInstallAdvantechDocsDescription": "For Advantech modem installation instructions, see <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>.",
"WgConfiguration": "WireGuard Configuration",
"WgConfigurationDescription": "Use the following configuration to connect to the network",
"operatingSystem": "Operating System",
@@ -132,7 +132,7 @@
"siteRestartDialogMessage": "Are you sure you want to restart the WireGuard tunnel for <b>{name}</b>? The site will briefly lose connectivity.",
"siteRestartWarning": "The site will briefly disconnect while the tunnel restarts.",
"siteRestarted": "Site restarted",
"siteRestartedDescription": "The WireGuard tunnel has been restarted.",
"siteRestartedDescription": "The site has been restarted.",
"siteErrorRestart": "Failed to restart site",
"siteErrorRestartDescription": "An error occurred while restarting the site.",
"siteSettingDescription": "Configure the settings on the site",
@@ -235,7 +235,7 @@
"privateResourcesBannerTitle": "Zero-Trust Private Access",
"privateResourcesBannerDescription": "Private resources use zero-trust security, ensuring users and machines can only access resources you explicitly grant. Connect user devices or machine clients to access these resources over a secure virtual private network.",
"licenseBillingBannerTitle": "Manage License Billing",
"licenseBillingBannerDescription": "To manage billing for your license keys, including payment methods and invoices, visit the billing page.",
"licenseBillingBannerDescription": "To manage billing for your license keys, including payment methods and invoices, visit the billing page. You can generate additional licenses below to increase server capacity or deploy more instances.",
"licenseBillingBannerButton": "Go to Billing",
"resourcesSearch": "Search resources...",
"resourceAdd": "Add Resource",
@@ -307,6 +307,8 @@
"privateResourceTypeCidrDescription": "Expose a CIDR range on the site network to connected clients",
"privateResourceTypeHttpDescription": "Access an HTTP or HTTPS service through a domain",
"privateResourceTypeSshDescription": "Access an SSH server from connected clients",
"privateResourceTypeGatewayDescription": "Send all internet traffic to exit through the site network.",
"resourceTypeGatewayDescription": "Send all internet traffic to exit through the site network.",
"resourceDomainDescription": "The resource will be served at this fully qualified domain name.",
"resourceHTTPSSettings": "HTTPS Settings",
"resourceHTTPSSettingsDescription": "Configure how the resource will be accessed over HTTPS",
@@ -558,6 +560,10 @@
"licenseBannerDescription": "Unlock enterprise features for your self-hosted Pangolin instance. Purchase a license key to activate premium capabilities, then add it below.",
"licenseBannerGetLicense": "Get a License",
"licenseBannerViewDocs": "View Documentation",
"licenseUpgradeBannerTitle": "Need More Capacity?",
"licenseUpgradeBannerDescription": "If you need to increase your site or user capacity, you can buy more licenses from the app.pangolin.net portal and add them below to upgrade your instance.",
"licenseUpgradeBannerButton": "Buy More Licenses",
"licenseMultipleKeysDescription": "You have multiple licenses activated on this server. The highest tier is used.",
"communityEdition": "Community Edition",
"licenseAboutDescription": "This is for business and enterprise users who are using Pangolin in a commercial environment. If you are using Pangolin for personal use, you can ignore this section.",
"licenseKeyActivated": "License key activated",
@@ -576,10 +582,10 @@
"licenseQuestionRemove": "Are you sure you want to delete the license key ?",
"licenseKeyDelete": "Delete License Key",
"licenseKeyDeleteConfirm": "Confirm Delete License Key",
"licenseTitle": "Manage License Status",
"licenseTitle": "Manage Licenses",
"licenseTitleDescription": "View and manage license keys in the system",
"licenseHost": "Host License",
"licenseHostDescription": "Manage the main license key for the host.",
"licenseHost": "License",
"licenseHostDescription": "See the license tier and host information",
"licensedNot": "Not Licensed",
"hostId": "Host ID",
"licenseReckeckAll": "Recheck All Keys",
@@ -589,7 +595,16 @@
"licensePurchase": "Purchase License",
"licensePurchaseSites": "Purchase Additional Sites",
"licenseSitesUsedMax": "{usedSites} of {maxSites} sites used",
"licenseSitesUsed": "{count, plural, =0 {# sites} one {# site} other {# sites}} in system.",
"licenseSitesUsed": "{count, plural, =0 {# sites} one {# site} other {# sites}}",
"licenseUsage": "Usage",
"licenseUsageDescription": "View the number of users and sites licensed for this host",
"licenseUsageSites": "Sites",
"licenseUsageUsers": "Users",
"licenseNoUserLimit": "There is no limit on the number of users using an unlicensed hot",
"licenseUsersUsedMax": "{usedUsers} of {maxUsers} users used",
"licenseUsersUsed": "{count, plural, =0 {# users} one {# user} other {# users}}",
"licenseUnlimited": "Unlimited",
"licenseTierLabel": "Tier",
"licensePurchaseDescription": "Choose how many sites you want to {selectedMode, select, license {purchase a license for. You can always add more sites later.} other {add to your existing license.}}",
"licenseFee": "License fee",
"licensePriceSite": "Price per site",
@@ -834,7 +849,7 @@
"rulesErrorDuplicatePriorityDescription": "Each rule must have a unique priority number.",
"rulesErrorValidation": "Invalid rules",
"rulesErrorValidationRuleDescription": "Rule {ruleNumber}: {message}",
"rulesErrorInvalidMatchTypeDescription": "Select a valid match type (path, IP, CIDR, country, region, or ASN).",
"rulesErrorInvalidMatchTypeDescription": "Select a valid match type (path, IP, CIDR, country, region, ASN, or method).",
"rulesErrorValueRequired": "Enter a value for this rule.",
"rulesErrorInvalidCountry": "Invalid country",
"rulesErrorInvalidCountryDescription": "Select a valid country.",
@@ -2829,8 +2844,10 @@
"retryAttempts": "Retry Attempts",
"expectedResponseCodes": "Expected Response Codes",
"expectedResponseCodesDescription": "HTTP status code that indicates healthy status. If left blank, 200-300 is considered healthy.",
"customHeaders": "Custom Request Headers",
"customHeadersDescription": "Request headers sent to the downstream targets. Headers new line separated: Header-Name: value",
"customRequestHeaders": "Custom Request Headers",
"customRequestHeadersDescription": "Request headers sent to the downstream targets. One per line: Header-Name: value",
"customResponseHeaders": "Custom Response Headers",
"customResponseHeadersDescription": "Response headers sent back to the client. One per line: Header-Name: value",
"headersValidationError": "Headers must be in the format: Header-Name: value",
"saveHealthCheck": "Save Health Check",
"healthCheckSaved": "Health Check Saved",
@@ -2912,6 +2929,7 @@
"editInternalResourceDialogModePort": "Port",
"editInternalResourceDialogModeHost": "Host",
"editInternalResourceDialogModeCidr": "CIDR",
"editInternalResourceDialogModeGateway": "Exit Node",
"editInternalResourceDialogModeHttp": "HTTP",
"editInternalResourceDialogModeHttps": "HTTPS",
"editInternalResourceDialogModeInference": "AI Gateway",
@@ -2923,6 +2941,7 @@
"editInternalResourceDialogDestinationHostDescription": "The IP address or hostname of the resource on the site's network.",
"editInternalResourceDialogDestinationIPDescription": "The IP or hostname address of the resource on the site's network.",
"editInternalResourceDialogDestinationCidrDescription": "The CIDR range of the resource on the site's network.",
"editInternalResourceDialogDestinationGatewayDescription": "The sites to uses as exit nodes for this resource",
"editInternalResourceDialogAlias": "Alias",
"editInternalResourceDialogAliasDescription": "An optional internal DNS alias for this resource.",
"createInternalResourceDialogNoSitesAvailable": "No Sites Available",
@@ -2937,6 +2956,7 @@
"privateResourceNetworkAccessDescription": "Control TCP/UDP port access and whether ICMP ping is allowed for this resource.",
"hostSettings": "Host",
"cidrSettings": "CIDR",
"gatewaySettings": "Exit Node",
"createInternalResourceDialogResourceProperties": "Resource Properties",
"createInternalResourceDialogName": "Name",
"createInternalResourceDialogSite": "Site",
@@ -2975,6 +2995,7 @@
"createInternalResourceDialogModeHttps": "HTTPS",
"createInternalResourceDialogModeSsh": "SSH",
"createInternalResourceDialogModeInference": "AI Gateway",
"createInternalResourceDialogModeGateway": "Exit Node",
"scheme": "Scheme",
"createInternalResourceDialogScheme": "Scheme",
"createInternalResourceDialogEnableSsl": "Enable TLS",
@@ -4400,5 +4421,8 @@
"sessionToolbarShow": "Show toolbar",
"sessionToolbarHide": "Hide toolbar",
"actionUpdateSiteApprovals": "Update Site Approvals",
"check": "Check"
"check": "Check",
"rulesErrorInvalidMethod": "Invalid HTTP method",
"rulesErrorInvalidMethodDescription": "Select at least one HTTP method.",
"rulesSelectMethods": "Select methods"
}
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "Instalar Newt",
"siteInstallNewtDescription": "Recibe Newt corriendo en tu sistema",
"siteInstallKubernetesDocsDescription": "Para información de instalación de Kubernetes más reciente, consulta <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>.",
"siteInstallAdvantechDocsDescription": "Para instrucciones de instalación del módem Advantech, consulta <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>.",
"siteInstallAdvantechDocsDescription": "Para instrucciones de instalación del módem Advantech, consulta <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>.",
"WgConfiguration": "Configuración de Wirex Guard",
"WgConfigurationDescription": "Utilice la siguiente configuración para conectarse a la red",
"operatingSystem": "Sistema operativo",
@@ -2826,8 +2826,10 @@
"retryAttempts": "Intentos de Reintento",
"expectedResponseCodes": "Códigos de respuesta esperados",
"expectedResponseCodesDescription": "Código de estado HTTP que indica un estado saludable. Si se deja en blanco, se considera saludable de 200 a 300.",
"customHeaders": "Cabeceras personalizadas",
"customHeadersDescription": "Nueva línea de cabeceras separada: Nombre de cabecera: valor",
"customRequestHeaders": "Cabeceras de solicitud personalizadas",
"customRequestHeadersDescription": "Cabeceras de solicitud enviadas a los destinos. Una por línea: Nombre-Cabecera: valor",
"customResponseHeaders": "Cabeceras de respuesta personalizadas",
"customResponseHeadersDescription": "Cabeceras de respuesta devueltas al cliente. Una por línea: Nombre-Cabecera: valor",
"headersValidationError": "Los encabezados deben estar en el formato: Nombre de cabecera: valor.",
"saveHealthCheck": "Guardar Chequeo de Salud",
"healthCheckSaved": "Chequeo de Salud Guardado",
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "Installer Newt",
"siteInstallNewtDescription": "Faites fonctionner Newt sur votre système",
"siteInstallKubernetesDocsDescription": "Pour plus d'informations à jour sur l'installation de Kubernetes, consultez <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>.",
"siteInstallAdvantechDocsDescription": "Pour les instructions d'installation du modem Advantech, voir <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>.",
"siteInstallAdvantechDocsDescription": "Pour les instructions d'installation du modem Advantech, voir <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>.",
"WgConfiguration": "Configuration WireGuard",
"WgConfigurationDescription": "Utilisez la configuration suivante pour vous connecter au réseau",
"operatingSystem": "Système d'exploitation",
@@ -2826,8 +2826,10 @@
"retryAttempts": "Tentatives de réessai",
"expectedResponseCodes": "Codes de réponse attendus",
"expectedResponseCodesDescription": "Code de statut HTTP indiquant un état de santé satisfaisant. Si non renseigné, 200-300 est considéré comme satisfaisant.",
"customHeaders": "En-têtes personnalisés",
"customHeadersDescription": "En-têtes séparés par une nouvelle ligne: En-nom: valeur",
"customRequestHeaders": "En-têtes de requête personnalisés",
"customRequestHeadersDescription": "En-têtes de requête envoyés aux cibles. Un par ligne : Nom-En-tête : valeur",
"customResponseHeaders": "En-têtes de réponse personnalisés",
"customResponseHeadersDescription": "En-têtes de réponse renvoyés au client. Un par ligne : Nom-En-tête : valeur",
"headersValidationError": "Les entêtes doivent être au format : Header-Name: valeur.",
"saveHealthCheck": "Sauvegarder la vérification de l'état de santé",
"healthCheckSaved": "Vérification de l'état de santé enregistrée",
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "Installa Newt",
"siteInstallNewtDescription": "Esegui Newt sul tuo sistema",
"siteInstallKubernetesDocsDescription": "Per ulteriori informazioni aggiornate sull'installazione di Kubernetes, consulta <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>.",
"siteInstallAdvantechDocsDescription": "Per le istruzioni sull'installazione del modem Advantech, consulta <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>.",
"siteInstallAdvantechDocsDescription": "Per le istruzioni sull'installazione del modem Advantech, consulta <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>.",
"WgConfiguration": "Configurazione WireGuard",
"WgConfigurationDescription": "Utilizzare la seguente configurazione per connettersi alla rete",
"operatingSystem": "Sistema Operativo",
@@ -2826,8 +2826,10 @@
"retryAttempts": "Tentativi di Riprova",
"expectedResponseCodes": "Codici di Risposta Attesi",
"expectedResponseCodesDescription": "Codice di stato HTTP che indica lo stato di salute. Se lasciato vuoto, considerato sano è compreso tra 200-300.",
"customHeaders": "Intestazioni Personalizzate",
"customHeadersDescription": "Intestazioni nuova riga separate: Intestazione-Nome: valore",
"customRequestHeaders": "Intestazioni di richiesta personalizzate",
"customRequestHeadersDescription": "Intestazioni di richiesta inviate ai target. Una per riga: Nome-Intestazione: valore",
"customResponseHeaders": "Intestazioni di risposta personalizzate",
"customResponseHeadersDescription": "Intestazioni di risposta restituite al client. Una per riga: Nome-Intestazione: valore",
"headersValidationError": "Le intestazioni devono essere nel formato: Intestazione-Nome: valore.",
"saveHealthCheck": "Salva Controllo Salute",
"healthCheckSaved": "Controllo Salute Salvato",
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "Newt 설치",
"siteInstallNewtDescription": "시스템에서 Newt 실행하기",
"siteInstallKubernetesDocsDescription": "더 많은 정보와 최신의 쿠버네티스 설치 정보를 보려면 <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>를 참조하세요.",
"siteInstallAdvantechDocsDescription": "Advantech 모뎀 설치 지침은 <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>을 참조하세요.",
"siteInstallAdvantechDocsDescription": "Advantech 모뎀 설치 지침은 <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>을 참조하세요.",
"WgConfiguration": "WireGuard 구성",
"WgConfigurationDescription": "네트워크에 연결하기 위한 다음 구성을 사용하세요.",
"operatingSystem": "운영 체제",
@@ -2826,8 +2826,10 @@
"retryAttempts": "재시도 횟수",
"expectedResponseCodes": "예상 응답 코드",
"expectedResponseCodesDescription": "정상 상태를 나타내는 HTTP 상태 코드입니다. 비워 두면 200-300이 정상으로 간주됩니다.",
"customHeaders": "사용자 정의 헤더",
"customHeadersDescription": "헤더는 새 줄로 구분됨: Header-Name: value",
"customRequestHeaders": "사용자 정의 요청 헤더",
"customRequestHeadersDescription": "다운스트림 대상으로 전송되는 요청 헤더. 한 줄에 하나씩: 헤더-이름: 값",
"customResponseHeaders": "사용자 정의 응답 헤더",
"customResponseHeadersDescription": "클라이언트로 반환되는 응답 헤더. 한 줄에 하나씩: 헤더-이름: 값",
"headersValidationError": "헤더는 형식이어야 합니다: 헤더명: 값.",
"saveHealthCheck": "상태 확인 저장",
"healthCheckSaved": "상태 확인이 저장되었습니다.",
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "Installer Newt",
"siteInstallNewtDescription": "Få Newt til å kjøre på systemet ditt",
"siteInstallKubernetesDocsDescription": "For mer og oppdatert informasjon om Kubernetes-installasjon, se <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>.",
"siteInstallAdvantechDocsDescription": "For installasjonsinstruksjoner for Advantech-modem, se <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>.",
"siteInstallAdvantechDocsDescription": "For installasjonsinstruksjoner for Advantech-modem, se <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>.",
"WgConfiguration": "WireGuard Konfigurasjon",
"WgConfigurationDescription": "Bruk følgende konfigurasjon for å koble til nettverket",
"operatingSystem": "Operativsystem",
@@ -2826,8 +2826,10 @@
"retryAttempts": "Forsøk på nytt",
"expectedResponseCodes": "Forventede svarkoder",
"expectedResponseCodesDescription": "HTTP-statuskode som indikerer sunn status. Hvis den blir stående tom, regnes 200-300 som sunn.",
"customHeaders": "Egendefinerte topptekster",
"customHeadersDescription": "Overskrifter som er adskilt med linje: Overskriftsnavn: verdi",
"customRequestHeaders": "Egendefinerte forespørselshoder",
"customRequestHeadersDescription": "Forespørselshoder sendt til målene. Én per linje: Header-Navn: verdi",
"customResponseHeaders": "Egendefinerte svarhoder",
"customResponseHeadersDescription": "Svarhoder sendt tilbake til klienten. Én per linje: Header-Navn: verdi",
"headersValidationError": "Topptekst må være i formatet: header-navn: verdi.",
"saveHealthCheck": "Lagre Helsekontroll",
"healthCheckSaved": "Helsekontroll Lagret",
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "Installeer Newt",
"siteInstallNewtDescription": "Laat Newt draaien op uw systeem",
"siteInstallKubernetesDocsDescription": "Voor meer informatie over de installatie van Kubernetes, zie <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>.",
"siteInstallAdvantechDocsDescription": "Voor instructies voor de installatie van Advantech modems, zie <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>.",
"siteInstallAdvantechDocsDescription": "Voor instructies voor de installatie van Advantech modems, zie <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>.",
"WgConfiguration": "WireGuard Configuratie",
"WgConfigurationDescription": "Gebruik de volgende configuratie om verbinding te maken met het netwerk",
"operatingSystem": "Operating systeem",
@@ -2826,8 +2826,10 @@
"retryAttempts": "Herhaal Pogingen",
"expectedResponseCodes": "Verwachte Reactiecodes",
"expectedResponseCodesDescription": "HTTP-statuscode die gezonde status aangeeft. Indien leeg wordt 200-300 als gezond beschouwd.",
"customHeaders": "Aangepaste headers",
"customHeadersDescription": "Kopregeleinde: Header-Naam: waarde",
"customRequestHeaders": "Aangepaste verzoekheaders",
"customRequestHeadersDescription": "Verzoekheaders die worden doorgestuurd naar het doel. Per regel één: Header-Naam: waarde",
"customResponseHeaders": "Aangepaste antwoordheaders",
"customResponseHeadersDescription": "Antwoordheaders die worden teruggestuurd naar de client. Per regel één: Header-Naam: waarde",
"headersValidationError": "Headers moeten in het formaat zijn: Header-Naam: waarde.",
"saveHealthCheck": "Opslaan Gezondheidscontrole",
"healthCheckSaved": "Gezondheidscontrole Opgeslagen",
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "Zainstaluj Newt",
"siteInstallNewtDescription": "Uruchom Newt w swoim systemie",
"siteInstallKubernetesDocsDescription": "Aby uzyskać więcej aktualnych informacji o instalacji Kubernetes, zobacz <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>.",
"siteInstallAdvantechDocsDescription": "Aby uzyskać instrukcje dotyczące instalacji modemu Advantech, zobacz: <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>.",
"siteInstallAdvantechDocsDescription": "Aby uzyskać instrukcje dotyczące instalacji modemu Advantech, zobacz: <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>.",
"WgConfiguration": "Konfiguracja WireGuard",
"WgConfigurationDescription": "Użyj następującej konfiguracji, aby połączyć się z siecią",
"operatingSystem": "System operacyjny",
@@ -2826,8 +2826,10 @@
"retryAttempts": "Próby Ponowienia",
"expectedResponseCodes": "Oczekiwane Kody Odpowiedzi",
"expectedResponseCodesDescription": "Kod statusu HTTP, który wskazuje zdrowy status. Jeśli pozostanie pusty, uznaje się 200-300 za zdrowy.",
"customHeaders": "Niestandardowe nagłówki",
"customHeadersDescription": "Nagłówki oddzielone: Nazwa nagłówka: wartość",
"customRequestHeaders": "Niestandardowe nagłówki żądania",
"customRequestHeadersDescription": "Nagłówki żądania wysyłane do celów. Jeden w wierszu: Nazwa-Nagłówka: wartość",
"customResponseHeaders": "Niestandardowe nagłówki odpowiedzi",
"customResponseHeadersDescription": "Nagłówki odpowiedzi zwracane do klienta. Jeden w wierszu: Nazwa-Nagłówka: wartość",
"headersValidationError": "Nagłówki muszą być w formacie: Nazwa nagłówka: wartość.",
"saveHealthCheck": "Zapisz Kontrolę Zdrowia",
"healthCheckSaved": "Kontrola Zdrowia Zapisana",
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "Instalar Novo",
"siteInstallNewtDescription": "Novo item em execução no seu sistema",
"siteInstallKubernetesDocsDescription": "Para mais informações atualizadas sobre a instalação do Kubernetes, veja <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>.",
"siteInstallAdvantechDocsDescription": "Para instruções de instalação do modem da Advantech, veja <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>.",
"siteInstallAdvantechDocsDescription": "Para instruções de instalação do modem da Advantech, veja <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>.",
"WgConfiguration": "Configuração do WireGuard",
"WgConfigurationDescription": "Use a seguinte configuração para conectar-se à rede",
"operatingSystem": "Sistema operacional",
@@ -2826,8 +2826,10 @@
"retryAttempts": "Tentativas de Repetição",
"expectedResponseCodes": "Códigos de Resposta Esperados",
"expectedResponseCodesDescription": "Código de status HTTP que indica estado saudável. Se deixado em branco, 200-300 é considerado saudável.",
"customHeaders": "Cabeçalhos Personalizados",
"customHeadersDescription": "Separados por cabeçalhos da nova linha: Nome do Cabeçalho: valor",
"customRequestHeaders": "Cabeçalhos de Pedido Personalizados",
"customRequestHeadersDescription": "Cabeçalhos de pedido enviados para os destinos. Um por linha: Nome-Cabeçalho: valor",
"customResponseHeaders": "Cabeçalhos de Resposta Personalizados",
"customResponseHeadersDescription": "Cabeçalhos de resposta enviados de volta ao cliente. Um por linha: Nome-Cabeçalho: valor",
"headersValidationError": "Cabeçalhos devem estar no formato: Nome do Cabeçalho: valor.",
"saveHealthCheck": "Salvar Verificação de Saúde",
"healthCheckSaved": "Verificação de Saúde Salva",
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "Установить Newt",
"siteInstallNewtDescription": "Запустите Newt в вашей системе",
"siteInstallKubernetesDocsDescription": "Для получения дополнительной информации об установке Kubernetes, см. <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>.",
"siteInstallAdvantechDocsDescription": "Для инструкций по установке модема Advantech, см. <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>.",
"siteInstallAdvantechDocsDescription": "Для инструкций по установке модема Advantech, см. <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>.",
"WgConfiguration": "Конфигурация WireGuard",
"WgConfigurationDescription": "Используйте следующую конфигурацию для подключения к сети",
"operatingSystem": "Операционная система",
@@ -2826,8 +2826,10 @@
"retryAttempts": "Количество попыток повторного запроса",
"expectedResponseCodes": "Ожидаемые коды ответов",
"expectedResponseCodesDescription": "HTTP-код состояния, указывающий на здоровое состояние. Если оставить пустым, 200-300 считается здоровым.",
"customHeaders": "Пользовательские заголовки",
"customHeadersDescription": "Заголовки новой строки, разделённые: название заголовка: значение",
"customRequestHeaders": "Пользовательские заголовки запроса",
"customRequestHeadersDescription": "Заголовки запроса, отправляемые целевым серверам. По одному в строке: Имя-Заголовка: значение",
"customResponseHeaders": "Пользовательские заголовки ответа",
"customResponseHeadersDescription": "Заголовки ответа, возвращаемые клиенту. По одному в строке: Имя-Заголовка: значение",
"headersValidationError": "Заголовки должны быть в формате: Название заголовка: значение.",
"saveHealthCheck": "Сохранить проверку здоровья",
"healthCheckSaved": "Проверка здоровья сохранена",
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "Newt Yükle",
"siteInstallNewtDescription": "Newt'i sisteminizde çalıştırma",
"siteInstallKubernetesDocsDescription": "Daha fazla ve güncel Kubernetes kurulum bilgileri için <docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink> adresini inceleyin.",
"siteInstallAdvantechDocsDescription": "Advantech modem kurulum talimatları için <docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink> adresini inceleyin.",
"siteInstallAdvantechDocsDescription": "Advantech modem kurulum talimatları için <docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink> adresini inceleyin.",
"WgConfiguration": "WireGuard Yapılandırması",
"WgConfigurationDescription": "Ağınıza bağlanmak için aşağıdaki yapılandırmayı kullanın",
"operatingSystem": "İşletim Sistemi",
@@ -2826,8 +2826,10 @@
"retryAttempts": "Tekrar Deneme Girişimleri",
"expectedResponseCodes": "Beklenen Yanıt Kodları",
"expectedResponseCodesDescription": "Sağlıklı durumu gösteren HTTP durum kodu. Boş bırakılırsa, 200-300 arası sağlıklı kabul edilir.",
"customHeaders": "Özel Başlıklar",
"customHeadersDescription": "Başlıklar yeni satırla ayrılmış: Başlık-Adı: değer",
"customRequestHeaders": "Özel İstek Başlıkları",
"customRequestHeadersDescription": "Hedeflere gönderilen istek başlıkları. Satır başına bir tane: Başlık-Adı: değer",
"customResponseHeaders": "Özel Yanıt Başlıkları",
"customResponseHeadersDescription": "İstemciye geri gönderilen yanıt başlıkları. Satır başına bir tane: Başlık-Adı: değer",
"headersValidationError": "Başlıklar şu formatta olmalıdır: Başlık-Adı: değer.",
"saveHealthCheck": "Sağlık Kontrolünü Kaydet",
"healthCheckSaved": "Sağlık Kontrolü Kaydedildi",
+5 -3
View File
@@ -110,7 +110,7 @@
"siteInstallNewt": "安装 Newt",
"siteInstallNewtDescription": "在您的系统中运行 Newt",
"siteInstallKubernetesDocsDescription": "有关最新的 Kubernetes 安装信息,请参阅<docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>。",
"siteInstallAdvantechDocsDescription": "有关 Advantech 调制解调器安装说明,请参阅<docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>。",
"siteInstallAdvantechDocsDescription": "有关 Advantech 调制解调器安装说明,请参阅<docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>。",
"WgConfiguration": "WireGuard 配置",
"WgConfigurationDescription": "使用以下配置连接到网络",
"operatingSystem": "操作系统",
@@ -2826,8 +2826,10 @@
"retryAttempts": "重试次数",
"expectedResponseCodes": "期望响应代码",
"expectedResponseCodesDescription": "HTTP 状态码表示健康状态。如留空,200-300 被视为健康。",
"customHeaders": "自定义标题",
"customHeadersDescription": "头部新行分隔:头部名称:值",
"customRequestHeaders": "自定义请求标头",
"customRequestHeadersDescription": "转发到目标的请求标头。每行一个:标头名称:值",
"customResponseHeaders": "自定义响应标头",
"customResponseHeadersDescription": "返回给客户端的响应标头。每行一个:标头名称:值",
"headersValidationError": "头部必须是格式:头部名称:值。",
"saveHealthCheck": "保存健康检查",
"healthCheckSaved": "健康检查已保存",
+5 -3
View File
@@ -1551,8 +1551,10 @@
"retryAttempts": "重試次數",
"expectedResponseCodes": "期望響應代碼",
"expectedResponseCodesDescription": "HTTP 狀態碼表示健康狀態。如留空,200-300 被視為健康。",
"customHeaders": "自訂 Headers",
"customHeadersDescription": "Header 斷行分隔:Header 名稱:值",
"customRequestHeaders": "自訂請求 Headers",
"customRequestHeadersDescription": "轉發至目標的請求標頭。每行一個:Header-名稱:值",
"customResponseHeaders": "自訂回應 Headers",
"customResponseHeadersDescription": "回傳給客戶端的回應標頭。每行一個:Header-名稱:值",
"headersValidationError": "Header 必須是格式:Header 名稱:值。",
"saveHealthCheck": "保存健康檢查",
"healthCheckSaved": "健康檢查已保存",
@@ -2424,7 +2426,7 @@
"sitesTableViewPublicResources": "檢視公共資源",
"sitesTableViewPrivateResources": "檢視私有資源",
"siteInstallKubernetesDocsDescription": "有關最新的 Kubernetes 安裝資訊,請參閱<docsLink>docs.pangolin.net/manage/sites/install-kubernetes</docsLink>。",
"siteInstallAdvantechDocsDescription": "有關 Advantech 數據機安裝說明,請參閱<docsLink>docs.pangolin.net/manage/sites/install-advantech</docsLink>。",
"siteInstallAdvantechDocsDescription": "有關 Advantech 數據機安裝說明,請參閱<docsLink>docs.pangolin.net/manage/sites/install-newt#advantech-router-app</docsLink>。",
"siteRestartTitle": "重新啟動站台",
"siteRestartDescription": "重新啟動此站台的WireGuard隧道。此操作將暫時中斷連線。",
"siteRestartBody": "如果站台隧道無法正常工作,並且您希望在不重新啟動主機的情況下強制重新連線,請使用此選項。",
+77 -48
View File
@@ -4,42 +4,18 @@
"iPad2,2": "iPad 2",
"iPad2,3": "iPad 2",
"iPad2,4": "iPad 2",
"iPad3,1": "iPad 3rd Gen",
"iPad3,3": "iPad 3rd Gen",
"iPad3,2": "iPad 3rd Gen",
"iPad3,4": "iPad 4th Gen",
"iPad3,5": "iPad 4th Gen",
"iPad3,6": "iPad 4th Gen",
"iPad6,11": "iPad 9.7 5th Gen",
"iPad6,12": "iPad 9.7 5th Gen",
"iPad7,5": "iPad 9.7 6th Gen",
"iPad7,6": "iPad 9.7 6th Gen",
"iPad7,11": "iPad 10.2 7th Gen",
"iPad7,12": "iPad 10.2 7th Gen",
"iPad11,6": "iPad 10.2 8th Gen",
"iPad11,7": "iPad 10.2 8th Gen",
"iPad12,1": "iPad 10.2 9th Gen",
"iPad12,2": "iPad 10.2 9th Gen",
"iPad13,18": "iPad 10.9 10th Gen",
"iPad13,19": "iPad 10.9 10th Gen",
"iPad4,1": "iPad Air",
"iPad4,2": "iPad Air",
"iPad4,3": "iPad Air",
"iPad5,3": "iPad Air 2",
"iPad5,4": "iPad Air 2",
"iPad11,3": "iPad Air 3rd Gen",
"iPad11,4": "iPad Air 3rd Gen",
"iPad13,1": "iPad Air 4th Gen",
"iPad13,2": "iPad Air 4th Gen",
"iPad13,16": "iPad Air 5th Gen",
"iPad13,17": "iPad Air 5th Gen",
"iPad14,8": "iPad Air M2 11",
"iPad14,9": "iPad Air M2 11",
"iPad14,10": "iPad Air M2 13",
"iPad14,11": "iPad Air M2 13",
"iPad2,5": "iPad mini",
"iPad2,6": "iPad mini",
"iPad2,7": "iPad mini",
"iPad3,1": "iPad 3rd Gen",
"iPad3,2": "iPad 3rd Gen",
"iPad3,3": "iPad 3rd Gen",
"iPad3,4": "iPad 4th Gen",
"iPad3,5": "iPad 4th Gen",
"iPad3,6": "iPad 4th Gen",
"iPad4,1": "iPad Air",
"iPad4,2": "iPad Air",
"iPad4,3": "iPad Air",
"iPad4,4": "iPad mini 2",
"iPad4,5": "iPad mini 2",
"iPad4,6": "iPad mini 2",
@@ -48,18 +24,22 @@
"iPad4,9": "iPad mini 3",
"iPad5,1": "iPad mini 4",
"iPad5,2": "iPad mini 4",
"iPad11,1": "iPad mini 5th Gen",
"iPad11,2": "iPad mini 5th Gen",
"iPad14,1": "iPad mini 6th Gen",
"iPad14,2": "iPad mini 6th Gen",
"iPad6,7": "iPad Pro 12.9",
"iPad6,8": "iPad Pro 12.9",
"iPad5,3": "iPad Air 2",
"iPad5,4": "iPad Air 2",
"iPad6,3": "iPad Pro 9.7",
"iPad6,4": "iPad Pro 9.7",
"iPad7,3": "iPad Pro 10.5",
"iPad7,4": "iPad Pro 10.5",
"iPad6,7": "iPad Pro 12.9",
"iPad6,8": "iPad Pro 12.9",
"iPad6,11": "iPad 9.7 5th Gen",
"iPad6,12": "iPad 9.7 5th Gen",
"iPad7,1": "iPad Pro 12.9",
"iPad7,2": "iPad Pro 12.9",
"iPad7,3": "iPad Pro 10.5",
"iPad7,4": "iPad Pro 10.5",
"iPad7,5": "iPad 9.7 6th Gen",
"iPad7,6": "iPad 9.7 6th Gen",
"iPad7,11": "iPad 10.2 7th Gen",
"iPad7,12": "iPad 10.2 7th Gen",
"iPad8,1": "iPad Pro 11",
"iPad8,2": "iPad Pro 11",
"iPad8,3": "iPad Pro 11",
@@ -72,6 +52,16 @@
"iPad8,10": "iPad Pro 11",
"iPad8,11": "iPad Pro 12.9",
"iPad8,12": "iPad Pro 12.9",
"iPad11,1": "iPad mini 5th Gen",
"iPad11,2": "iPad mini 5th Gen",
"iPad11,3": "iPad Air 3rd Gen",
"iPad11,4": "iPad Air 3rd Gen",
"iPad11,6": "iPad 10.2 8th Gen",
"iPad11,7": "iPad 10.2 8th Gen",
"iPad12,1": "iPad 10.2 9th Gen",
"iPad12,2": "iPad 10.2 9th Gen",
"iPad13,1": "iPad Air 4th Gen",
"iPad13,2": "iPad Air 4th Gen",
"iPad13,4": "iPad Pro 11",
"iPad13,5": "iPad Pro 11",
"iPad13,6": "iPad Pro 11",
@@ -80,14 +70,40 @@
"iPad13,9": "iPad Pro 12.9",
"iPad13,10": "iPad Pro 12.9",
"iPad13,11": "iPad Pro 12.9",
"iPad13,16": "iPad Air M1 5th Gen",
"iPad13,17": "iPad Air M1 5th Gen",
"iPad13,18": "iPad 10.9 10th Gen",
"iPad13,19": "iPad 10.9 10th Gen",
"iPad14,1": "iPad mini 6th Gen",
"iPad14,2": "iPad mini 6th Gen",
"iPad14,3": "iPad Pro 11",
"iPad14,4": "iPad Pro 11",
"iPad14,5": "iPad Pro 12.9",
"iPad14,6": "iPad Pro 12.9",
"iPad14,8": "iPad Air M2 11",
"iPad14,9": "iPad Air M2 11",
"iPad14,10": "iPad Air M2 13",
"iPad14,11": "iPad Air M2 13",
"iPad15,3": "iPad Air M3 11",
"iPad15,4": "iPad Air M3 11",
"iPad15,5": "iPad Air M3 13",
"iPad15,6": "iPad Air M3 13",
"iPad15,7": "iPad A16 - 11th Gen",
"iPad15,8": "iPad A16 - 11th Gen",
"iPad16,1": "iPad mini A17 Pro - 7th Gen",
"iPad16,2": "iPad mini A17 Pro - 7th Gen",
"iPad16,3": "iPad Pro M4 11",
"iPad16,4": "iPad Pro M4 11",
"iPad16,5": "iPad Pro M4 13",
"iPad16,6": "iPad Pro M4 13",
"iPad16,8": "iPad Air M4 11",
"iPad16,9": "iPad Air M4 11",
"iPad16,10": "iPad Air M4 13",
"iPad16,11": "iPad Air M4 13",
"iPad17,1": "iPad Pro M5 11",
"iPad17,2": "iPad Pro M5 11",
"iPad17,3": "iPad Pro M5 13",
"iPad17,4": "iPad Pro M5 13",
"iPhone1,1": "iPhone",
"iPhone1,2": "iPhone 3G",
"iPhone2,1": "iPhone 3GS",
@@ -101,20 +117,20 @@
"iPhone5,4": "iPhone 5c",
"iPhone6,1": "iPhone 5s",
"iPhone6,2": "iPhone 5s",
"iPhone7,2": "iPhone 6",
"iPhone7,1": "iPhone 6 Plus",
"iPhone7,2": "iPhone 6",
"iPhone8,1": "iPhone 6s",
"iPhone8,2": "iPhone 6s Plus",
"iPhone8,4": "iPhone SE",
"iPhone9,1": "iPhone 7",
"iPhone9,3": "iPhone 7",
"iPhone9,2": "iPhone 7 Plus",
"iPhone9,3": "iPhone 7",
"iPhone9,4": "iPhone 7 Plus",
"iPhone10,1": "iPhone 8",
"iPhone10,4": "iPhone 8",
"iPhone10,2": "iPhone 8 Plus",
"iPhone10,5": "iPhone 8 Plus",
"iPhone10,3": "iPhone X",
"iPhone10,4": "iPhone 8",
"iPhone10,5": "iPhone 8 Plus",
"iPhone10,6": "iPhone X",
"iPhone11,2": "iPhone Xs",
"iPhone11,6": "iPhone Xs Max",
@@ -127,10 +143,10 @@
"iPhone13,2": "iPhone 12",
"iPhone13,3": "iPhone 12 Pro",
"iPhone13,4": "iPhone 12 Pro Max",
"iPhone14,4": "iPhone 13 mini",
"iPhone14,5": "iPhone 13",
"iPhone14,2": "iPhone 13 Pro",
"iPhone14,3": "iPhone 13 Pro Max",
"iPhone14,4": "iPhone 13 mini",
"iPhone14,5": "iPhone 13",
"iPhone14,6": "iPhone SE",
"iPhone14,7": "iPhone 14",
"iPhone14,8": "iPhone 14 Plus",
@@ -140,6 +156,19 @@
"iPhone15,5": "iPhone 15 Plus",
"iPhone16,1": "iPhone 15 Pro",
"iPhone16,2": "iPhone 15 Pro Max",
"iPhone17,1": "iPhone 16 Pro",
"iPhone17,2": "iPhone 16 Pro Max",
"iPhone17,3": "iPhone 16",
"iPhone17,4": "iPhone 16 Plus",
"iPhone17,5": "iPhone 16e",
"iPhone18,1": "iPhone 17 Pro",
"iPhone18,2": "iPhone 17 Pro Max",
"iPhone18,3": "iPhone 17",
"iPhone18,4": "iPhone Air",
"iPhone18,5": "iPhone 17e",
"iPhone19,2": "iPhone 18 Pro",
"iPhone19,3": "iPhone 18 Pro Max",
"iPhone19,7": "iPhone 18 Pro Max",
"iPod1,1": "iPod touch Original",
"iPod2,1": "iPod touch 2nd",
"iPod3,1": "iPod touch 3rd Gen",
@@ -147,4 +176,4 @@
"iPod5,1": "iPod touch 5th",
"iPod7,1": "iPod touch 6th Gen",
"iPod9,1": "iPod touch 7th Gen"
}
}
+6 -2
View File
@@ -38,6 +38,9 @@
"Mac16,7": "MacBook Pro",
"Mac16,8": "MacBook Pro",
"Mac16,9": "Mac Studio",
"Mac17,14": "Mac Studio",
"Mac17,15": "Mac Studio",
"Mac17,16": "Mac mini",
"Mac17,2": "MacBook Pro",
"Mac17,3": "MacBook Air",
"Mac17,4": "MacBook Air",
@@ -46,6 +49,7 @@
"Mac17,7": "MacBook Pro",
"Mac17,8": "MacBook Pro",
"Mac17,9": "MacBook Pro",
"Mac18,5": "Mac mini",
"MacBook1,1": "MacBook",
"MacBook10,1": "MacBook",
"MacBook2,1": "MacBook",
@@ -173,7 +177,7 @@
"PowerMac12,1": "iMac",
"PowerMac2,1": "iMac",
"PowerMac2,2": "iMac",
"PowerMac3,1": "Mac Server",
"PowerMac3,1": "Power Macintosh",
"PowerMac3,3": "Power Macintosh",
"PowerMac3,4": "Power Macintosh",
"PowerMac3,5": "Power Macintosh",
@@ -232,4 +236,4 @@
"iMac8,1": "iMac",
"iMac9,1": "iMac",
"iMacPro1,1": "iMac Pro"
}
}
+8 -4
View File
@@ -78,7 +78,8 @@ export const orgs = pgTable("orgs", {
"settingsEnableGlobalNewtAutoUpdate"
)
.notNull()
.default(false)
.default(false),
settingsJitModeLimit: integer("settingsJitModeLimit").notNull().default(250)
});
export const orgDomains = pgTable("orgDomains", {
@@ -186,7 +187,8 @@ export const resources = pgTable(
skipToIdpId: integer("skipToIdpId").references(() => idp.idpId, {
onDelete: "set null"
}),
headers: text("headers"), // comma-separated list of headers to add to the request
requestHeaders: text("requestHeaders"),
responseHeaders: text("responseHeaders"),
proxyProtocol: boolean("proxyProtocol").notNull().default(false),
proxyProtocolVersion: integer("proxyProtocolVersion").default(1),
maintenanceModeEnabled: boolean("maintenanceModeEnabled")
@@ -490,8 +492,8 @@ export const siteResources = pgTable(
name: varchar("name").notNull(),
ssl: boolean("ssl").notNull().default(false),
mode: varchar("mode")
.$type<"host" | "cidr" | "http" | "ssh" | "inference">()
.notNull(), // "host" | "cidr" | "http"
.$type<"host" | "cidr" | "http" | "ssh" | "inference" | "gateway">()
.notNull(),
scheme: varchar("scheme").$type<"http" | "https">(), // only for when we are doing https or http mode
proxyPort: integer("proxyPort"), // only for port mode
destinationPort: integer("destinationPort"), // only for port mode
@@ -1137,6 +1139,7 @@ export const resourceRules = pgTable("resourceRules", {
| "COUNTRY_IS_NOT"
| "ASN"
| "REGION"
| "METHOD"
>()
.notNull(), // CIDR, PATH, IP
value: varchar("value").notNull()
@@ -1161,6 +1164,7 @@ export const resourcePolicyRules = pgTable("resourcePolicyRules", {
| "COUNTRY_IS_NOT"
| "ASN"
| "REGION"
| "METHOD"
>()
.notNull(),
value: varchar("value").notNull()
+8 -4
View File
@@ -78,7 +78,8 @@ export const orgs = sqliteTable("orgs", {
{ mode: "boolean" }
)
.notNull()
.default(false)
.default(false),
settingsJitModeLimit: integer("settingsJitModeLimit").notNull().default(250)
});
export const userDomains = sqliteTable("userDomains", {
@@ -202,7 +203,8 @@ export const resources = sqliteTable(
skipToIdpId: integer("skipToIdpId").references(() => idp.idpId, {
onDelete: "set null"
}),
headers: text("headers"), // comma-separated list of headers to add to the request
requestHeaders: text("requestHeaders"),
responseHeaders: text("responseHeaders"),
proxyProtocol: integer("proxyProtocol", { mode: "boolean" })
.notNull()
.default(false),
@@ -511,8 +513,8 @@ export const siteResources = sqliteTable("siteResources", {
name: text("name").notNull(),
ssl: integer("ssl", { mode: "boolean" }).notNull().default(false),
mode: text("mode")
.$type<"host" | "cidr" | "http" | "ssh" | "inference">()
.notNull(), // "host" | "cidr" | "http"
.$type<"host" | "cidr" | "http" | "ssh" | "inference" | "gateway">()
.notNull(),
scheme: text("scheme").$type<"http" | "https">(), // only for when we are doing https or http mode
proxyPort: integer("proxyPort"), // only for port mode
destinationPort: integer("destinationPort"), // only for port mode
@@ -1409,6 +1411,7 @@ export const resourceRules = sqliteTable("resourceRules", {
| "COUNTRY_IS_NOT"
| "ASN"
| "REGION"
| "METHOD"
>()
.notNull(), // CIDR, PATH, IP
value: text("value").notNull()
@@ -1465,6 +1468,7 @@ export const resourcePolicyRules = sqliteTable("resourcePolicyRules", {
| "COUNTRY_IS_NOT"
| "ASN"
| "REGION"
| "METHOD"
>()
.notNull(),
value: text("value").notNull()
@@ -235,7 +235,7 @@ export const AlertNotification = (props: AlertNotificationProps) => {
}
]
: []),
{ label: "Time", value: new Date().toUTCString() },
{ label: "Time (UTC)", value: new Date().toUTCString() },
...dataItems
];
@@ -265,8 +265,8 @@ export const AlertNotification = (props: AlertNotificationProps) => {
</EmailText>
{isTestAlert && (
<EmailText>
This is a test alert. No action is required,
and no real event has occurred.
This is a test alert. No action is required, and
no real event has occurred.
</EmailText>
)}
+1
View File
@@ -3,3 +3,4 @@ export * from "./features";
export * from "./limitsService";
export * from "./getOrgTierData";
export * from "./createCustomer";
export * from "./linkEmailOrg";
+6
View File
@@ -0,0 +1,6 @@
export async function linkEmailOrg(
orgId: string,
email: string | null | undefined
): Promise<void> {
return;
}
+36 -16
View File
@@ -259,6 +259,11 @@ export async function updatePrivateResources(
}
const isInference = resourceData.mode === "inference";
const isGateway = resourceData.mode === "gateway";
// gateway resources always route the whole subnet with everything open
const effectiveDestination = isGateway
? "0.0.0.0/0"
: resourceData.destination;
// Update existing resource
const [updatedResource] = await trx
@@ -268,23 +273,28 @@ export async function updatePrivateResources(
mode: resourceData.mode,
ssl: resourceSsl,
scheme: resourceData.scheme,
destination: resourceData.destination,
destination: effectiveDestination,
destinationPort: resourceData["destination-port"],
enabled: resourceEnabled,
alias: resourceData.alias || null,
disableIcmp:
resourceData["disable-icmp"] ||
(resourceData.mode == "http" || isInference
? true
: false), // default to true for http/inference resources, otherwise false
disableIcmp: isGateway
? false // gateway always allows icmp
: resourceData["disable-icmp"] ||
(resourceData.mode == "http" || isInference
? true
: false), // default to true for http/inference resources, otherwise false
tcpPortRangeString:
resourceData.mode == "http" || isInference
? "443,80"
: resourceData["tcp-ports"],
: isGateway
? "*"
: resourceData["tcp-ports"],
udpPortRangeString:
resourceData.mode == "http" || isInference
? ""
: resourceData["udp-ports"],
: isGateway
? "*"
: resourceData["udp-ports"],
fullDomain: resourceData["full-domain"] || null,
subdomain: domainInfo ? domainInfo.subdomain : null,
domainId: domainInfo ? domainInfo.domainId : null,
@@ -529,6 +539,11 @@ export async function updatePrivateResources(
}
const isInference = resourceData.mode === "inference";
const isGateway = resourceData.mode === "gateway";
// gateway resources always route the whole subnet with everything open
const effectiveDestination = isGateway
? "0.0.0.0/0"
: resourceData.destination;
let domainInfo:
| { subdomain: string | null; domainId: string }
@@ -590,24 +605,29 @@ export async function updatePrivateResources(
mode: resourceData.mode,
ssl: resourceSsl,
scheme: resourceData.scheme,
destination: resourceData.destination,
destination: effectiveDestination,
destinationPort: resourceData["destination-port"],
enabled: resourceEnabled,
alias: resourceData.alias || null,
aliasAddress: aliasAddress,
disableIcmp:
resourceData["disable-icmp"] ||
(resourceData.mode == "http" || isInference
? true
: false), // default to true for http/inference resources, otherwise false
disableIcmp: isGateway
? false // gateway always allows icmp
: resourceData["disable-icmp"] ||
(resourceData.mode == "http" || isInference
? true
: false), // default to true for http/inference resources, otherwise false
tcpPortRangeString:
resourceData.mode == "http" || isInference
? "443,80"
: resourceData["tcp-ports"],
: isGateway
? "*"
: resourceData["tcp-ports"],
udpPortRangeString:
resourceData.mode == "http" || isInference
? ""
: resourceData["udp-ports"],
: isGateway
? "*"
: resourceData["udp-ports"],
fullDomain: resourceData["full-domain"] || null,
subdomain: domainInfo ? domainInfo.subdomain : null,
domainId: domainInfo ? domainInfo.domainId : null,
+33 -8
View File
@@ -48,7 +48,13 @@ import { defaultRoleAllowedActions } from "@server/routers/role/createRole";
import { pickPort } from "@server/routers/target/helpers";
import { and, asc, eq, isNotNull, ne } from "drizzle-orm";
import { tierMatrix } from "../billing/tierMatrix";
import { isValidCIDR, isValidIP, isValidUrlGlobPattern } from "../validators";
import {
isValidCIDR,
isValidHttpMethodList,
isValidIP,
isValidUrlGlobPattern,
parseHttpMethodList
} from "../validators";
import { Config, isTargetsOnlyResource, TargetData } from "./types";
import { getOrCreateLabelIds, syncResourceLabels } from "./labels";
import { findOrgUsersByIdentifier } from "./findOrgUser";
@@ -255,10 +261,18 @@ export async function updatePublicResources(
resourceData.ssl == undefined || resourceData.ssl == null
? true
: resourceData.ssl;
let headers = "";
if (resourceData.headers) {
headers = JSON.stringify(resourceData.headers);
}
// `headers` is a deprecated alias for `requestHeaders`
const mergedRequestHeaders = [
...(resourceData.headers ?? []),
...(resourceData.requestHeaders ?? [])
];
const requestHeaders =
mergedRequestHeaders.length > 0
? JSON.stringify(mergedRequestHeaders)
: null;
const responseHeaders = resourceData.responseHeaders?.length
? JSON.stringify(resourceData.responseHeaders)
: null;
if (resourceData.policy) {
const isLicensed = await isLicensedOrSubscribed(
@@ -397,7 +411,8 @@ export async function updatePublicResources(
? resourceData.auth["whitelist-users"].length >
0
: false,
headers: headers || null,
requestHeaders,
responseHeaders,
applyRules:
resourceData.rules &&
resourceData.rules.length > 0,
@@ -593,7 +608,8 @@ export async function updatePublicResources(
setHostHeader: resourceData["host-header"] || null,
tlsServerName:
resourceData["tls-server-name"] || null,
headers: headers || null,
requestHeaders,
responseHeaders,
maintenanceModeEnabled:
resourceData.maintenance?.enabled,
maintenanceModeType: resourceData.maintenance?.type,
@@ -1216,7 +1232,8 @@ export async function updatePublicResources(
setHostHeader: resourceData["host-header"] || null,
tlsServerName: resourceData["tls-server-name"] || null,
ssl: resourceSsl,
headers: headers || null,
requestHeaders,
responseHeaders,
applyRules:
resourceData.rules && resourceData.rules.length > 0,
pamMode: resourceData["auth-daemon"]?.pam || "passthrough",
@@ -1453,6 +1470,10 @@ function getRuleValue(match: string, value: string) {
if (match === "COUNTRY" || match === "COUNTRY_IS_NOT") {
return value.toUpperCase();
}
// normalize the method list so it is stored as "POST,PUT"
if (match === "METHOD") {
return parseHttpMethodList(value).join(",");
}
return value;
}
@@ -1473,6 +1494,10 @@ function validateRule(rule: any) {
if (!isValidRegionId(rule.value)) {
throw new Error(`Invalid region ID provided: ${rule.value}`);
}
} else if (rule.match === "method") {
if (!isValidHttpMethodList(rule.value)) {
throw new Error(`Invalid HTTP method provided: ${rule.value}`);
}
}
}
+16 -12
View File
@@ -19,7 +19,13 @@ import logger from "@server/logger";
import { getUniqueResourcePolicyName } from "@server/db/names";
import { hashPassword } from "@server/auth/password";
import { idpExistsForOrg } from "@server/lib/idp/idpExistsForOrg";
import { isValidCIDR, isValidIP, isValidUrlGlobPattern } from "../validators";
import {
isValidCIDR,
isValidHttpMethodList,
isValidIP,
isValidUrlGlobPattern,
ResourceRuleMatchType
} from "../validators";
import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed";
import { tierMatrix } from "../billing/tierMatrix";
import { findOrgUsersByIdentifier } from "./findOrgUser";
@@ -66,6 +72,13 @@ export async function updateResourcePolicies(
throw new Error(
`Invalid URL glob pattern provided in resource policy '${policyNiceId}': ${rule.value}`
);
} else if (
rule.match === "method" &&
!isValidHttpMethodList(rule.value)
) {
throw new Error(
`Invalid HTTP method provided in resource policy '${policyNiceId}': ${rule.value}`
);
}
}
@@ -339,17 +352,8 @@ function getRuleAction(input: string): "ACCEPT" | "DROP" | "PASS" {
return "PASS";
}
function getRuleMatch(
input: string
): "CIDR" | "IP" | "PATH" | "COUNTRY" | "COUNTRY_IS_NOT" | "ASN" | "REGION" {
return input.toUpperCase() as
| "CIDR"
| "IP"
| "PATH"
| "COUNTRY"
| "COUNTRY_IS_NOT"
| "ASN"
| "REGION";
function getRuleMatch(input: string): ResourceRuleMatchType {
return input.toUpperCase() as ResourceRuleMatchType;
}
async function syncRolePolicies(
+33 -11
View File
@@ -3,6 +3,7 @@ import { existsSync } from "node:fs";
import { portRangeStringSchema } from "@server/lib/ip";
import { MaintenanceSchema } from "#dynamic/lib/blueprints/MaintenanceSchema";
import { isValidRegionId } from "@server/db/regions";
import { isValidHttpMethodList } from "@server/lib/validators";
import { wildcardSubdomainSchema } from "@server/lib/schemas";
import config from "@server/lib/config";
import {
@@ -127,7 +128,16 @@ export const AuthSchema = z.object({
export const RuleSchema = z
.object({
action: z.enum(["allow", "deny", "pass"]),
match: z.enum(["cidr", "path", "ip", "country", "country_is_not", "asn", "region"]),
match: z.enum([
"cidr",
"path",
"ip",
"country",
"country_is_not",
"asn",
"region",
"method"
]),
value: z.coerce.string(),
priority: z.int().optional(),
enabled: z.boolean().optional().default(true)
@@ -207,6 +217,19 @@ export const RuleSchema = z
message:
"Value must be a valid UN M.49 region or subregion ID when match is 'region'"
}
)
.refine(
(rule) => {
if (rule.match === "method") {
return isValidHttpMethodList(rule.value);
}
return true;
},
{
path: ["value"],
message:
"Value must be a comma-separated list of HTTP methods when match is 'method', e.g. 'POST,PUT'"
}
);
export const HeaderSchema = z.object({
@@ -303,7 +326,9 @@ export const PublicResourceSchema = z
auth: AuthSchema.optional(),
"host-header": z.string().optional(),
"tls-server-name": z.string().optional(),
headers: z.array(HeaderSchema).optional(),
headers: z.array(HeaderSchema).optional(), // deprecated alias for requestHeaders
requestHeaders: z.array(HeaderSchema).optional(),
responseHeaders: z.array(HeaderSchema).optional(),
rules: z.array(RuleSchema).optional(),
maintenance: MaintenanceSchema.optional(),
"auth-daemon": AuthDaemonSchema.optional(),
@@ -587,7 +612,7 @@ export function isTargetsOnlyResource(resource: any): boolean {
export const PrivateResourceSchema = z
.object({
name: z.string().min(1).max(255),
mode: z.enum(["host", "cidr", "http", "ssh", "inference"]),
mode: z.enum(["host", "cidr", "http", "ssh", "inference", "gateway"]),
site: z.string().optional(), // DEPRECATED IN FAVOR OF sites
sites: z.array(z.string()).optional().default([]),
// protocol: z.enum(["tcp", "udp"]).optional(),
@@ -627,13 +652,15 @@ export const PrivateResourceSchema = z
})
.refine(
(data) => {
// destination is optional only for ssh+native or inference; required for everything else
// destination is optional only for ssh+native, inference, or gateway
// (gateway always routes the whole subnet, so destination is ignored); required for everything else
const isNativeSSH =
data.mode === "ssh" &&
(data["auth-daemon"] === undefined ||
data["auth-daemon"].mode === "native");
if (
data.mode !== "inference" &&
data.mode !== "gateway" &&
!isNativeSSH &&
!data.destination
) {
@@ -644,7 +671,7 @@ export const PrivateResourceSchema = z
{
path: ["destination"],
message:
"destination is required unless mode is 'ssh' with auth-daemon mode 'native', or mode is 'inference'"
"destination is required unless mode is 'ssh' with auth-daemon mode 'native', 'inference', or 'gateway'"
}
)
.refine(
@@ -791,25 +818,20 @@ export const ConfigSchema = z
.object({
"proxy-resources": z
.record(z.string(), PublicResourceSchema)
.optional()
.prefault({}),
"public-resources": z
.record(z.string(), PublicResourceSchema)
.optional()
.prefault({}),
"client-resources": z
.record(z.string(), PrivateResourceSchema)
.optional()
.prefault({}),
"private-resources": z
.record(z.string(), PrivateResourceSchema)
.optional()
.prefault({}),
"public-policies": z
.record(z.string(), ResourcePolicySchema)
.optional()
.prefault({}),
sites: z.record(z.string(), SiteSchema).optional().prefault({})
sites: z.record(z.string(), SiteSchema).prefault({})
})
.transform((data) => {
// Merge public-resources into proxy-resources
@@ -17,7 +17,6 @@ import {
performDeleteSiteResources,
runSiteResourceDeleteSideEffects
} from "@server/lib/deleteSiteResource";
import logger from "@server/logger";
export const MAX_SITE_ASSOCIATED_RESOURCES_FOR_BULK_DELETE = 250;
+2 -1
View File
@@ -500,6 +500,7 @@ export function generateRemoteSubnets(
if (!sr.enabled) return false;
if (!sr.destination) return false;
// we purposely filter out the gateway resource here because we add it manually on the client
if (sr.mode === "cidr") {
// check if its a valid CIDR using zod
const cidrSchema = z.union([z.cidrv4(), z.cidrv6()]);
@@ -808,7 +809,7 @@ export async function generateSubnetProxyTargetV2(
resourceId: siteResource.siteResourceId
});
}
} else if (siteResource.mode == "cidr") {
} else if (siteResource.mode == "cidr" || siteResource.mode == "gateway") {
targets.push({
sourcePrefixes: [],
destPrefix: siteResource.destination!,
+3 -30
View File
@@ -149,6 +149,8 @@ export const configSchema = z
})
.optional(),
trust_proxy: z.int().gte(0).optional().default(1),
trust_ips: z.array(z.string()).optional().default([]),
custom_ip_header: z.string().optional().default(""),
// Opt-in: have Traefik/Badger stamp the resolved client IP
// into a dedicated header (X-Pangolin-Client-Ip) on the
// site-resource AI gateway route, so it survives an
@@ -174,36 +176,7 @@ export const configSchema = z
maxmind_db_path: z.string().optional(),
maxmind_asn_path: z.string().optional()
})
.optional()
.default({
integration_port: 3003,
external_port: 3000,
internal_port: 3001,
ai_gateway_port: 3005,
next_port: 3002,
internal_hostname: "pangolin",
session_cookie_name: "p_session_token",
resource_access_token_param: "p_token",
resource_access_token_headers: {
id: "P-Access-Token-Id",
token: "P-Access-Token"
},
remote_headers: {
user_id: "Remote-User-Id",
virtual_api_key_id: "Remote-Virtual-Api-Key-Id",
user: "Remote-User",
email: "Remote-Email",
name: "Remote-Name",
role: "Remote-Role"
},
resource_session_request_param:
"resource_session_request_param",
dashboard_session_length_hours: 720,
resource_session_length_hours: 720,
trust_proxy: 1,
enable_ai_gateway_client_ip_header: false,
secret: undefined
}),
.prefault({}),
postgres: z
.object({
connection_string: z.string().optional(),
+95 -9
View File
@@ -17,11 +17,16 @@ import {
sites,
Transaction,
userOrgRoles,
userSiteResources
userSiteResources,
orgs
} from "@server/db";
import { and, count, eq, inArray, isNotNull, ne } from "drizzle-orm";
import { deletePeersBatch as newtDeletePeersBatch } from "@server/routers/newt/peers";
import {
sendGatewayDisable,
sendGatewaySitesUpdate
} from "@server/routers/olm/gateway";
import {
initPeerAddHandshakeBatch,
deletePeersBatch as olmDeletePeersBatch
@@ -234,7 +239,8 @@ export async function getClientSiteResourceAccess(
.select({
clientId: clients.clientId,
pubKey: clients.pubKey,
subnet: clients.subnet
subnet: clients.subnet,
orgId: clients.orgId
})
.from(clients)
.where(
@@ -260,7 +266,8 @@ export async function getClientSiteResourceAccess(
.select({
clientId: clients.clientId,
pubKey: clients.pubKey,
subnet: clients.subnet
subnet: clients.subnet,
orgId: clients.orgId
})
.from(clients)
.where(
@@ -463,7 +470,8 @@ async function rebuildClientAssociationsFromSiteResourceImpl(
.select({
clientId: clients.clientId,
pubKey: clients.pubKey,
subnet: clients.subnet
subnet: clients.subnet,
orgId: clients.orgId
})
.from(clients)
.where(
@@ -532,6 +540,19 @@ async function rebuildClientAssociationsFromSiteResourceImpl(
);
}
// A client that loses access to a gateway resource (it was deleted, or the
// client's roles/users/machines no longer include it) can't keep using it
// as its gateway. The olm ignores this unless it selected this resource.
if (
siteResource.mode === "gateway" &&
clientSiteResourcesToRemove.length > 0
) {
await sendGatewayDisable(
clientSiteResourcesToRemove,
siteResource.siteResourceId
);
}
/////////// process the client-site associations ///////////
logger.debug(
@@ -568,7 +589,8 @@ async function rebuildClientAssociationsFromSiteResourceImpl(
.select({
clientId: clients.clientId,
pubKey: clients.pubKey,
subnet: clients.subnet
subnet: clients.subnet,
orgId: clients.orgId
})
.from(clients)
.where(
@@ -720,11 +742,13 @@ async function handleMessagesForSiteClients(
clientId: number;
pubKey: string | null;
subnet: string | null;
orgId: string;
}[],
existingClients: {
clientId: number;
pubKey: string | null;
subnet: string | null;
orgId: string;
}[],
clientSitesToAdd: number[],
clientSitesToRemove: number[],
@@ -805,6 +829,7 @@ async function handleMessagesForSiteClients(
clientId: number;
pubKey: string | null;
subnet: string | null;
orgId: string;
}
>();
@@ -860,6 +885,22 @@ async function handleMessagesForSiteClients(
.map((r) => [r.clientId as number, r.olmId])
);
// Batch-fetch the orgs for all clients we need to process so we don't
// issue a redundant query per client in the loop below
const orgIdsToProcess = Array.from(
new Set(
Array.from(clientsToProcess.values()).map((client) => client.orgId)
)
);
const orgRows =
orgIdsToProcess.length > 0
? await trx
.select()
.from(orgs)
.where(inArray(orgs.orgId, orgIdsToProcess))
: [];
const orgByOrgId = new Map(orgRows.map((org) => [org.orgId, org]));
for (const client of clientsToProcess.values()) {
// UPDATE THE NEWT
if (!client.subnet || !client.pubKey) {
@@ -899,7 +940,14 @@ async function handleMessagesForSiteClients(
}
if (isAdd) {
if (clientSiteCounts[client.clientId] > 250) {
const org = orgByOrgId.get(client.orgId);
if (!org) {
logger.warn(`Client ${client.clientId} org not found`);
continue;
}
if (clientSiteCounts[client.clientId] > org.settingsJitModeLimit) {
// skip adding the peer if we have more than 250 sites because we are in jit mode anyway
logger.info(
`rebuildClientAssociations: Client ${client.clientId} has ${clientSiteCounts[client.clientId]} sites so skipping adding peer to newt and olm because it is likely in jit mode`
@@ -1570,7 +1618,8 @@ export async function handleMessagingForUpdatedSiteResource(
.select({
clientId: clientSiteResourcesAssociationsCache.clientId,
pubKey: clients.pubKey,
subnet: clients.subnet
subnet: clients.subnet,
orgId: clients.orgId
})
.from(clientSiteResourcesAssociationsCache)
.innerJoin(
@@ -2024,6 +2073,29 @@ export async function handleMessagingForUpdatedSiteResource(
);
}
// The olm only knows which gateway resource it selected and the sites it
// is currently using for it, so tell the clients that have access to this
// one what changed. Clients that lost access are handled by the rebuild.
if (existingSiteResource?.mode === "gateway") {
const clientIds = mergedAllClients.map((c) => c.clientId);
if (
updatedSiteResource.mode !== "gateway" ||
!updatedSiteResource.enabled
) {
await sendGatewayDisable(
clientIds,
updatedSiteResource.siteResourceId
);
} else {
await sendGatewaySitesUpdate(
clientIds,
updatedSiteResource.siteResourceId,
addedSiteIds,
removedSiteIds
);
}
}
logger.debug(
`handleMessagingForUpdatedSiteResource: DONE siteResourceId=${updatedSiteResource.siteResourceId}`
);
@@ -2391,6 +2463,19 @@ async function handleMessagesForClientSites(
.where(eq(clientSitesAssociationsCache.clientId, client.clientId))
.then((rows) => Number(rows[0].count));
// client.orgId is constant for this call, so fetch the org once
// instead of re-querying it for every site in the loop below
const [org] = await trx
.select()
.from(orgs)
.where(eq(orgs.orgId, client.orgId))
.limit(1);
if (!org) {
logger.warn(`Client ${client.clientId} org not found`);
return;
}
for (const siteData of sitesData) {
const site = siteData.sites;
const exitNode = siteData.exitNodes;
@@ -2451,7 +2536,7 @@ async function handleMessagesForClientSites(
continue;
}
if (totalSitesOnClient > 250) {
if (totalSitesOnClient > org.settingsJitModeLimit) {
// skip adding the site if we have more than 250 because we are in jit mode anyway
logger.info(
`rebuildClientAssociations: Client ${client.clientId} has ${totalSitesOnClient} sites so skipping adding peer to newt and olm because it is likely in jit mode`
@@ -3061,7 +3146,8 @@ export async function cleanupSiteAssociations(
.select({
clientId: clients.clientId,
pubKey: clients.pubKey,
subnet: clients.subnet
subnet: clients.subnet,
orgId: clients.orgId
})
.from(clients)
.where(inArray(clients.clientId, cachedClientIds))
+6 -3
View File
@@ -96,7 +96,8 @@ export async function getTraefikConfig(
tlsServerName: resources.tlsServerName,
setHostHeader: resources.setHostHeader,
enableProxy: resources.enableProxy,
headers: resources.headers,
requestHeaders: resources.requestHeaders,
responseHeaders: resources.responseHeaders,
proxyProtocol: resources.proxyProtocol,
proxyProtocolVersion: resources.proxyProtocolVersion,
wildcard: resources.wildcard,
@@ -225,7 +226,8 @@ export async function getTraefikConfig(
setHostHeader: row.setHostHeader,
enableProxy: row.enableProxy,
targets: [],
headers: row.headers,
requestHeaders: row.requestHeaders,
responseHeaders: row.responseHeaders,
proxyProtocol: row.proxyProtocol,
proxyProtocolVersion: row.proxyProtocolVersion ?? 1,
path: row.path, // the targets will all have the same path
@@ -405,7 +407,8 @@ export async function getTraefikConfig(
// Handle custom headers middleware
const customHeadersMiddleware = buildCustomHeadersMiddleware(
resource.headers,
resource.requestHeaders,
resource.responseHeaders,
resource.setHostHeader,
resource.resourceId
);
+57 -25
View File
@@ -1,46 +1,78 @@
import logger from "@server/logger";
function parseHeaders(
headers: string,
label: string,
resourceId: number
): { name: string; value: string }[] {
try {
return JSON.parse(headers) as {
name: string;
value: string;
}[];
} catch (e) {
logger.warn(
`Failed to parse ${label} for resource ${resourceId}: ${e}`
);
return [];
}
}
/**
* Build the customRequestHeaders middleware definition for a resource's
* custom headers + setHostHeader config. Returns null when there are no
* headers to set, so the caller can skip attaching the middleware.
* Build the custom headers middleware definition for a resource's
* custom request/response headers + setHostHeader config. Returns null when
* there are no headers to set, so the caller can skip attaching the
* middleware.
*/
export function buildCustomHeadersMiddleware(
headers: string | null | undefined,
requestHeaders: string | null | undefined,
responseHeaders: string | null | undefined,
setHostHeader: string | null | undefined,
resourceId: number
): { headers: { customRequestHeaders: { [key: string]: string } } } | null {
const headersObj: { [key: string]: string } = {};
): {
headers: {
customRequestHeaders?: { [key: string]: string };
customResponseHeaders?: { [key: string]: string };
};
} | null {
const requestHeadersObj: { [key: string]: string } = {};
const responseHeadersObj: { [key: string]: string } = {};
if (headers) {
let headersArr: { name: string; value: string }[] = [];
try {
headersArr = JSON.parse(headers) as {
name: string;
value: string;
}[];
} catch (e) {
logger.warn(
`Failed to parse headers for resource ${resourceId}: ${e}`
);
}
headersArr.forEach((header) => {
headersObj[header.name] = header.value;
});
if (requestHeaders) {
parseHeaders(requestHeaders, "requestHeaders", resourceId).forEach(
(header) => {
requestHeadersObj[header.name] = header.value;
}
);
}
if (setHostHeader) {
headersObj["Host"] = setHostHeader;
requestHeadersObj["Host"] = setHostHeader;
}
if (Object.keys(headersObj).length === 0) {
if (responseHeaders) {
parseHeaders(responseHeaders, "responseHeaders", resourceId).forEach(
(header) => {
responseHeadersObj[header.name] = header.value;
}
);
}
const hasRequestHeaders = Object.keys(requestHeadersObj).length > 0;
const hasResponseHeaders = Object.keys(responseHeadersObj).length > 0;
if (!hasRequestHeaders && !hasResponseHeaders) {
return null;
}
return {
headers: {
customRequestHeaders: headersObj
...(hasRequestHeaders && {
customRequestHeaders: requestHeadersObj
}),
...(hasResponseHeaders && {
customResponseHeaders: responseHeadersObj
})
}
};
}
+41 -2
View File
@@ -1,9 +1,10 @@
import {
getResourceRuleValueValidationError,
isValidDomain,
isValidUrlGlobPattern
isValidUrlGlobPattern,
parseHttpMethodList
} from "./validators";
import { assertEquals } from "@test/assert";
import { assertEquals, assertEqualsObj } from "@test/assert";
function runTests() {
console.log("Running domain validation tests...");
@@ -295,6 +296,44 @@ function runTests() {
"Invalid ASN should return an error"
);
// HTTP method validation tests
assertEquals(
getResourceRuleValueValidationError("METHOD", "POST"),
null,
"Single HTTP method should be valid"
);
assertEquals(
getResourceRuleValueValidationError("METHOD", " post , Put "),
null,
"Method list should be valid with mixed case and whitespace"
);
assertEquals(
getResourceRuleValueValidationError("METHOD", "PROPFIND"),
null,
"Extension methods such as the WebDAV verbs should be valid"
);
assertEquals(
getResourceRuleValueValidationError("METHOD", ""),
"Invalid HTTP method provided",
"Empty method list should return an error"
);
assertEquals(
getResourceRuleValueValidationError("METHOD", ",,"),
"Invalid HTTP method provided",
"Method list of only separators should return an error"
);
assertEquals(
getResourceRuleValueValidationError("METHOD", "GET POST"),
"Invalid HTTP method provided",
"Space separated methods should return an error"
);
assertEqualsObj(
parseHttpMethodList(" get ,post, "),
["GET", "POST"],
"Method list should be normalized to uppercase without empty entries"
);
console.log("All tests passed!");
}
+42 -1
View File
@@ -76,9 +76,46 @@ export const RESOURCE_RULE_MATCH_TYPES = [
"COUNTRY",
"COUNTRY_IS_NOT",
"ASN",
"REGION"
"REGION",
"METHOD"
] as const;
// The methods offered in the UI: the eight from RFC 9110 plus PATCH (RFC 5789)
// and QUERY (RFC 10008). A METHOD rule is not limited to these, since
// isValidHttpMethodList accepts any method token, so blueprints and the API can
// also target extension methods such as the WebDAV verbs.
export const HTTP_METHODS = [
"GET",
"HEAD",
"POST",
"PUT",
"PATCH",
"DELETE",
"OPTIONS",
"TRACE",
"CONNECT",
"QUERY"
] as const;
// RFC 9110 token, minus the characters that would collide with the
// comma-separated list encoding.
const HTTP_METHOD_REGEX = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
export function parseHttpMethodList(value: string): string[] {
return value
.split(",")
.map((method) => method.trim().toUpperCase())
.filter((method) => method.length > 0);
}
export function isValidHttpMethodList(value: string): boolean {
const methods = parseHttpMethodList(value);
return (
methods.length > 0 &&
methods.every((method) => HTTP_METHOD_REGEX.test(method))
);
}
export type ResourceRuleMatchType = (typeof RESOURCE_RULE_MATCH_TYPES)[number];
export function getResourceRuleValueValidationError(
@@ -101,6 +138,10 @@ export function getResourceRuleValueValidationError(
return COUNTRIES.some((country) => country.code === value)
? null
: "Invalid country code provided";
case "METHOD":
return isValidHttpMethodList(value)
? null
: "Invalid HTTP method provided";
case "ASN":
const normalizedValue = value.trim().toUpperCase();
return /^AS\d+$/.test(normalizedValue) ||
+1
View File
@@ -13,3 +13,4 @@
export * from "./getOrgTierData";
export * from "./createCustomer";
export * from "./linkEmailOrg";
@@ -0,0 +1,56 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025-2026 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import logger from "@server/logger";
import privateConfig from "#private/lib/config";
import { build } from "@server/build";
export async function linkEmailOrg(
orgId: string,
email: string | null | undefined
): Promise<void> {
if (build !== "saas") {
return;
}
if (!email) {
return;
}
try {
const response = await fetch(
`${privateConfig.getRawPrivateConfig().server.fossorial_api}/api/v1/license-internal/enterprise/link-email-org`,
{
method: "POST",
headers: {
"api-key":
privateConfig.getRawPrivateConfig().server
.fossorial_api_key!,
"Content-Type": "application/json"
},
body: JSON.stringify({ email, orgId })
}
);
if (!response.ok && response.status !== 404) {
logger.error(
`Fossorial API returned ${response.status} when linking email ${email} to orgId ${orgId}: ${await response.text()}`
);
}
} catch (error) {
logger.error(
`Error notifying Fossorial API of email/org link for orgId ${orgId}:`,
error
);
}
}
+34 -11
View File
@@ -384,7 +384,8 @@ export class AuthoritativeDNSServer {
// Get records from cache or database
const records = await this.getResourceRecordsByFullDomain(
queryName,
queryType
queryType,
baseDomain!
);
if (records.length > 0) {
@@ -475,15 +476,30 @@ export class AuthoritativeDNSServer {
const labels = queryName.replace(/\.$/, "").split(".");
// Fast path: O(1) in-memory Set lookup — no DB or network I/O
if (this.allDomains.size > 0) {
for (let i = 0; i < labels.length; i++) {
const candidate = labels.slice(i).join(".");
if (this.allDomains.has(candidate)) {
this.authoritativeDomainCache.set(cacheKey, candidate);
return candidate;
}
// Infrastructure zone cuts (e.g. this deployment's own nameserver
// zone, cname/site extension zones) that this server is
// authoritative for regardless of the customer `domains` table.
// Static config, so always available - checked alongside allDomains
// below rather than gating a separate fast path on it.
const configuredZones = (config.getRawConfig().dns?.zones ?? []).map(
(z) => z.toLowerCase()
);
// Fast path: O(1) in-memory Set/array lookup — no DB or network I/O
for (let i = 0; i < labels.length; i++) {
const candidate = labels.slice(i).join(".");
if (
this.allDomains.has(candidate) ||
configuredZones.includes(candidate)
) {
this.authoritativeDomainCache.set(cacheKey, candidate);
return candidate;
}
}
// Once the in-memory customer-domain set has loaded, the checks
// above are conclusive - no DB fallback needed.
if (this.allDomains.size > 0) {
this.authoritativeDomainCache.set(cacheKey, null);
return null;
}
@@ -582,7 +598,8 @@ export class AuthoritativeDNSServer {
private async getResourceRecordsByFullDomain(
name: string,
queryType: dns.RecordType
queryType: dns.RecordType,
baseDomain: string
): Promise<DNSRecord[]> {
const cacheKey = `resourceRecords:${name}:${queryType}`;
@@ -630,8 +647,14 @@ export class AuthoritativeDNSServer {
if (resourceRows.length === 0) {
// Resource doesn't exist at all — also pre-populate the domainExists
// cache so the subsequent domainExists() call hits memory, not the DB.
// Skip that pre-population when `name` is the zone apex itself: the
// apex always exists (it owns the SOA) even with no resource row, and
// caching `false` here would make domainExists() return that stale
// false instead of ever reaching its own apex check.
logger.debug(`No resource found for domain: ${name}`);
this.cache.set(`exists:${name}`, false, 60);
if (name.replace(/\.$/, "") !== baseDomain) {
this.cache.set(`exists:${name}`, false, 60);
}
this.cache.set(cacheKey, [], 60);
return [];
}
+10
View File
@@ -109,6 +109,16 @@ export const privateConfigSchema = z
.array(z.string())
.optional()
.default([]),
// Zone names (zone cuts) this server is authoritative for
// beyond the customer domains stored in the `domains` table -
// e.g. a self-hosted deployment's own nameserver zone or
// cname/site extension zones. Any query landing on one of
// these names, or an empty non-terminal beneath one, that
// doesn't match a more specific record gets NOERROR/NODATA +
// SOA (not NXDOMAIN), so QNAME-minimising resolvers (RFC
// 9156) don't treat the ancestor as proof nothing exists
// below it (RFC 8020). Left for the user to populate.
zones: z.array(z.string()).optional().default([]),
rate_limit: z
.object({
enabled: z.boolean().optional().default(true),
@@ -133,7 +133,8 @@ export async function getTraefikConfig(
tlsServerName: resources.tlsServerName,
setHostHeader: resources.setHostHeader,
enableProxy: resources.enableProxy,
headers: resources.headers,
requestHeaders: resources.requestHeaders,
responseHeaders: resources.responseHeaders,
proxyProtocol: resources.proxyProtocol,
proxyProtocolVersion: resources.proxyProtocolVersion,
wildcard: resources.wildcard,
@@ -275,7 +276,8 @@ export async function getTraefikConfig(
setHostHeader: row.setHostHeader,
enableProxy: row.enableProxy,
targets: [],
headers: row.headers,
requestHeaders: row.requestHeaders,
responseHeaders: row.responseHeaders,
proxyProtocol: row.proxyProtocol,
proxyProtocolVersion: row.proxyProtocolVersion ?? 1,
path: row.path, // the targets will all have the same path
@@ -712,7 +714,8 @@ export async function getTraefikConfig(
);
const customHeadersMiddleware = buildCustomHeadersMiddleware(
resource.headers,
resource.requestHeaders,
resource.responseHeaders,
resource.setHostHeader,
resource.resourceId
);
+79 -2
View File
@@ -50,6 +50,27 @@ type ValidateLicenseAPIResponse = {
status: number;
};
// Ranks license tiers so that when multiple license keys are active, the
// highest tier among them wins. Order: personal < tier1 < tier2 < ... <
// tier[n] < enterprise. Tier numbers are parsed so this scales to any
// tier[n] without needing updates here.
function tierRank(tier?: LicenseKeyTier): number {
if (!tier) {
return -1;
}
if (tier === "enterprise") {
return Number.MAX_SAFE_INTEGER;
}
if (tier === "personal") {
return 0;
}
const match = /^tier(\d+)$/.exec(tier);
if (match) {
return parseInt(match[1], 10);
}
return 0;
}
type TokenPayload = {
valid: boolean;
type: LicenseKeyType;
@@ -276,6 +297,11 @@ LQIDAQAB
if (!apiResponse?.success) {
throw new Error(apiResponse?.error);
}
logger.debug(
`License server response: ${JSON.stringify(apiResponse)}`
);
// Reset failure count on success
this.phoneHomeFailureCount = 0;
} catch (e) {
@@ -338,6 +364,11 @@ LQIDAQAB
licenseKeyRes,
this.publicKey
);
logger.debug(
`Decoded license key ${key.licenseKey}: ${JSON.stringify(payload)}`
);
cached.valid = payload.valid;
cached.type = payload.type;
cached.tier = payload.tier;
@@ -370,13 +401,52 @@ LQIDAQAB
}
}
// Personal-tier licenses cannot coexist with a paid tier: if any
// valid host key is above personal, personal-tier keys are
// invalidated so they don't contribute to the totals below.
const hasHigherTierValidKey = keys.some((key) => {
const cached = newCache.get(key.licenseKey)!;
return (
cached.type === "host" &&
cached.valid &&
tierRank(cached.tier) > tierRank("personal")
);
});
if (hasHigherTierValidKey) {
for (const key of keys) {
const cached = newCache.get(key.licenseKey)!;
if (
cached.type === "host" &&
cached.valid &&
cached.tier === "personal"
) {
logger.debug(
`Invalidating personal license key ${key.licenseKey} because a higher tier license is present`
);
cached.valid = false;
newCache.set(key.licenseKey, cached);
}
}
}
// Compute host status: quantity = users, quantity_2 = sites
// When multiple host keys are active, prefer a valid key over an
// invalid one, and among equally-valid keys prefer the highest tier.
let selectedHostKey: LicenseKeyCache | undefined;
for (const key of keys) {
const cached = newCache.get(key.licenseKey)!;
if (cached.type === "host") {
status.isLicenseValid = cached.valid;
status.tier = cached.tier;
if (
!selectedHostKey ||
(cached.valid && !selectedHostKey.valid) ||
(cached.valid === selectedHostKey.valid &&
tierRank(cached.tier) >
tierRank(selectedHostKey.tier))
) {
selectedHostKey = cached;
}
}
if (!cached.valid) {
@@ -393,6 +463,11 @@ LQIDAQAB
}
}
if (selectedHostKey) {
status.isLicenseValid = selectedHostKey.valid;
status.tier = selectedHostKey.tier;
}
// Invalidate license if over user or site limits
if (
(status.maxSites !== undefined &&
@@ -415,6 +490,8 @@ LQIDAQAB
this.checkInProgress = false;
}
logger.debug(`Computed license status: ${JSON.stringify(status)}`);
this.statusCache.set(this.statusKey, status, 0);
return status;
}
+89 -5
View File
@@ -40,6 +40,7 @@ import {
import config from "@server/lib/config";
import { isIpInCidr, stripPortFromHost } from "@server/lib/ip";
import { isPathAllowed } from "@server/lib/pathMatch";
import { parseHttpMethodList } from "@server/lib/validators";
import { response } from "@server/lib/response";
import logger from "@server/logger";
import HttpCode from "@server/types/HttpCode";
@@ -161,6 +162,7 @@ export async function verifyResourceSession(
originalRequestURL,
requestIp,
path,
method,
headers,
query,
badgerVersion
@@ -169,8 +171,7 @@ export async function verifyResourceSession(
// Extract HTTP Basic Auth credentials if present
const clientHeaderAuth = extractBasicAuth(headers);
const clientUserAgent =
headers?.["user-agent"] || headers?.["User-Agent"];
const clientUserAgent = getClientHeader(headers, "user-agent");
const clientIsBrowser = isBrowserUserAgent(clientUserAgent);
const clientIp = requestIp
@@ -293,7 +294,8 @@ export async function verifyResourceSession(
clientIp,
path,
ipCC,
ipAsn
ipAsn,
method
);
if (action == "ACCEPT") {
@@ -453,7 +455,15 @@ export async function verifyResourceSession(
// Browsers go to the resource auth / API key page. API clients get
// a capability-shaped JSON auth error instead of a redirect.
if (clientIsBrowser) {
// Never redirect programmatic API calls (non-GET, or a known AI
// capability path): HTTP clients such as the OpenAI Python SDK
// (httpx) don't follow 302s on POST, so a redirect surfaces as
// an opaque failure with nothing logged in aiSessionLog since
// the request never reaches the gateway.
if (
clientIsBrowser &&
!isProgrammaticApiRequest(path, method, headers)
) {
return notAllowed(res, redirectPath, resource.orgId);
}
@@ -1429,7 +1439,8 @@ async function checkRules(
clientIp: string | undefined,
path: string | undefined,
ipCC?: string,
ipAsn?: number
ipAsn?: number,
method?: string
): Promise<"ACCEPT" | "DROP" | "PASS" | undefined> {
const ruleCacheKey = `rules:${resourceId}`;
@@ -1504,12 +1515,24 @@ async function checkRules(
(await isIpInRegion(ipCC, rule.value))
) {
return rule.action as any;
} else if (
method &&
rule.match == "METHOD" &&
isMethodAllowed(rule.value, method)
) {
return rule.action as any;
}
}
return;
}
// rule.value holds a comma-separated list of HTTP methods, e.g. "POST,PUT".
function isMethodAllowed(ruleValue: string, method: string): boolean {
const requestMethod = method.toUpperCase();
return parseHttpMethodList(ruleValue).includes(requestMethod);
}
export { isPathAllowed };
async function isIpInGeoIP(
@@ -1661,14 +1684,29 @@ const NON_BROWSER_USER_AGENT_PATTERNS = [
/wget/,
/python-requests/,
/python-urllib/,
/python-httpx/,
/httpx/,
/httpcore/,
/aiohttp/,
/urllib3/,
/openai\//,
/anthropic/,
/go-http-client/,
/okhttp/,
/axios/,
/node-fetch/,
/undici/,
/postmanruntime/,
/insomnia/,
/libwww-perl/,
/java\//,
/\bjava\b/,
/jakarta/,
/jersey/,
/netty/,
/jetty/,
/eclipse/,
/dbeaver/,
/ruby/,
/php/,
/bot/,
@@ -1693,6 +1731,52 @@ function isBrowserUserAgent(userAgent: string | undefined): boolean {
return !NON_BROWSER_USER_AGENT_PATTERNS.some((pattern) => pattern.test(ua));
}
function getClientHeader(
headers: Record<string, string> | undefined,
name: string
): string | undefined {
if (!headers) {
return undefined;
}
const lower = name.toLowerCase();
for (const [key, value] of Object.entries(headers)) {
if (key.toLowerCase() === lower) {
return value;
}
}
return undefined;
}
// True for programmatic API calls that can't complete an interactive login,
// even if the User-Agent looks like a browser (some SDKs reuse browser-ish
// strings or omit a distinctive token). Badger turns a redirectUrl into a
// 302, which HTTP clients don't follow on POST, so these must get a JSON
// auth error instead.
function isProgrammaticApiRequest(
path: string | undefined,
method: string | undefined,
headers: Record<string, string> | undefined
): boolean {
if (method && method.toUpperCase() !== "GET") {
return true;
}
if (path && resolveAiCapabilityFromPath(path) !== null) {
return true;
}
const accept = getClientHeader(headers, "accept");
if (accept && !accept.toLowerCase().includes("text/html")) {
return true;
}
const secFetchMode = getClientHeader(headers, "sec-fetch-mode");
if (
secFetchMode &&
!["navigate", "document"].includes(secFetchMode.toLowerCase())
) {
return true;
}
return false;
}
function extractBasicAuth(
headers: Record<string, string> | undefined
): string | undefined {
+20 -3
View File
@@ -8,7 +8,8 @@ import {
sites,
clientSitesAssociationsCache,
exitNodes,
ExitNode
ExitNode,
orgs
} from "@server/db";
import { db } from "@server/db";
import { eq, and, inArray } from "drizzle-orm";
@@ -112,7 +113,12 @@ export async function updateHolePunch(
destinations: destinations
});
} catch (error) {
if (!(error instanceof Error && error.message === "Exit node not allowed")) {
if (
!(
error instanceof Error &&
error.message === "Exit node not allowed"
)
) {
logger.error(error);
}
return next(
@@ -460,7 +466,18 @@ async function handleClientEndpointChange(
return;
}
if (sitesWithNewtsToUpdate.length > 250) {
const [org] = await db
.select()
.from(orgs)
.where(eq(orgs.orgId, client.orgId))
.limit(1);
if (!org) {
logger.warn(`Client ${clientId} org not found`);
return;
}
if (sitesWithNewtsToUpdate.length > org.settingsJitModeLimit) {
logger.warn(
`Client ${clientId} has ${sitesWithNewtsToUpdate.length} connected sites so the client will be in jit mode anyway, skipping endpoint updates`
);
+1 -1
View File
@@ -96,7 +96,7 @@ export async function buildClientConfigurationForNewtClient(
await updatePeer(client.clients.clientId, {
siteId: site.siteId,
endpoint: site.endpoint!,
relayEndpoint: `${exitNode.endpoint}:${config.getRawConfig().gerbil.clients_start_port}`,
relayEndpoint: formatEndpoint(exitNode.endpoint, config.getRawConfig().gerbil.clients_start_port),
publicKey: site.publicKey!,
serverIP: site.address,
serverPort: site.listenPort
+24
View File
@@ -0,0 +1,24 @@
import { sendToClient } from "#dynamic/routers/ws";
// Error codes for registration failures
export const NewtErrorCodes = {
NO_AVAILABLE_SUBNET: {
code: "NO_AVAILABLE_SUBNET",
message:
"No available subnet could be assigned to this site on its exit node. Please contact your administrator to increase the available address space for this exit node's subnet."
}
} as const;
// Helper function to send registration error
export async function sendNewtError(
error: (typeof NewtErrorCodes)[keyof typeof NewtErrorCodes],
newtId: string
) {
sendToClient(newtId, {
type: "newt/error",
data: {
code: error.code,
message: error.message
}
});
}
@@ -14,6 +14,8 @@ import { getUniqueSubnetForExitNode } from "@server/lib/exitNodes";
import { fetchContainers } from "./dockerSocket";
import { buildTargetConfigurationForNewtClient } from "./buildConfiguration";
import { canCompress } from "@server/lib/clientVersionChecks";
import { NewtErrorCodes, sendNewtError } from "./error";
import { formatEndpoint } from "@server/lib/ip";
export const handleNewtRegisterMessage: MessageHandler = async (context) => {
const { message, client, sendToClient } = context;
@@ -116,6 +118,7 @@ export const handleNewtRegisterMessage: MessageHandler = async (context) => {
logger.error(
`No available subnets found for the new exit node id ${exitNodeId} and site id ${siteId}`
);
sendNewtError(NewtErrorCodes.NO_AVAILABLE_SUBNET, newt.newtId);
return;
}
@@ -222,7 +225,7 @@ export const handleNewtRegisterMessage: MessageHandler = async (context) => {
message: {
type: "newt/wg/connect",
data: {
endpoint: `${exitNode.endpoint}:${exitNode.listenPort}`,
endpoint: formatEndpoint(exitNode.endpoint, exitNode.listenPort),
relayPort: config.getRawConfig().gerbil.clients_start_port,
publicKey: exitNode.publicKey,
serverIP: exitNode.address.split("/")[0],
+34
View File
@@ -127,6 +127,40 @@ export async function deletePeersBatch(
logger.info(`Deleted ${peers.length} peer(s) from newts (batch)`);
}
export async function updatePeersBatch(
peers: {
siteId: number;
publicKey: string;
newtId: string;
peer: {
allowedIps?: string[];
endpoint?: string;
};
}[]
) {
if (peers.length === 0) {
return;
}
await sendToClientsBatch(
peers.map((peer) => ({
clientId: peer.newtId,
message: {
type: "newt/wg/peer/update",
data: {
publicKey: peer.publicKey,
...peer.peer
}
},
options: { incrementConfigVersion: true }
}))
).catch((error) => {
logger.warn(`Error sending batched newt peer updates:`, error);
});
logger.info(`Updated ${peers.length} peer(s) on newts (batch)`);
}
export async function updatePeer(
siteId: number,
publicKey: string,
+3 -6
View File
@@ -4,6 +4,7 @@ import logger from "@server/logger";
import { canCompress } from "@server/lib/clientVersionChecks";
import { decrypt } from "@server/lib/crypto";
import config from "@server/lib/config";
import { formatEndpoint } from "@server/lib/ip";
export async function addTargets(
newtId: string,
@@ -14,9 +15,7 @@ export async function addTargets(
) {
//create a list of udp and tcp targets
const payloadTargets = targets.map((target) => {
return `${target.internalPort ? target.internalPort + ":" : ""}${
target.ip
}:${target.port}`;
return `${target.internalPort ? target.internalPort + ":" : ""}${formatEndpoint(target.ip, target.port)}`;
});
if (payloadTargets.length > 0) {
@@ -208,9 +207,7 @@ export async function removeTargets(
) {
//create a list of udp and tcp targets
const payloadTargets = targets.map((target) => {
return `${target.internalPort ? target.internalPort + ":" : ""}${
target.ip
}:${target.port}`;
return `${target.internalPort ? target.internalPort + ":" : ""}${formatEndpoint(target.ip, target.port)}`;
});
if (payloadTargets.length > 0) {
+55
View File
@@ -0,0 +1,55 @@
// Shared parsing for the olm relay/unrelay/local/unlocal websocket messages, which accept
// either a single siteId or a batched siteIds array (with a parallel chainIds array), so
// olm clients with many sites can coalesce decisions into one message instead of sending
// one message per site. Older olm clients that only ever send the singular form are handled
// identically to a batch of one, and the reply mirrors whichever form the request used.
import { db, newts } from "@server/db";
import { inArray } from "drizzle-orm";
// Resolves the newtId for each of the given siteIds in a single query, for batching the
// resulting newt/wg/peer/update pushes instead of looking each one up individually.
export async function resolveNewtIdsBySite(
siteIds: number[]
): Promise<Map<number, string>> {
if (siteIds.length === 0) {
return new Map();
}
const rows = await db
.select({ siteId: newts.siteId, newtId: newts.newtId })
.from(newts)
.where(inArray(newts.siteId, siteIds));
const map = new Map<number, string>();
for (const row of rows) {
if (row.siteId != null) {
map.set(row.siteId, row.newtId);
}
}
return map;
}
export type SiteChainBatch = {
siteIds: number[];
chainIds: (string | undefined)[];
isBatch: boolean;
};
export function parseSiteChainBatch(data: any): SiteChainBatch {
if (Array.isArray(data?.siteIds)) {
const siteIds: number[] = data.siteIds;
const chainIds: (string | undefined)[] =
Array.isArray(data.chainIds) &&
data.chainIds.length === siteIds.length
? data.chainIds
: siteIds.map(() => data.chainId);
return { siteIds, chainIds, isBatch: true };
}
return {
siteIds: data?.siteId !== undefined ? [data.siteId] : [],
chainIds: [data?.chainId],
isBatch: false
};
}
+1 -1
View File
@@ -231,7 +231,7 @@ export async function buildSiteConfigurationForOlmClient(
publicKey: site.publicKey,
serverIP: site.address,
serverPort: site.listenPort,
remoteSubnets: generateRemoteSubnets(allSiteResources),
remoteSubnets: generateRemoteSubnets(allSiteResources), // we dont add the gateway resources here
aliases: generateAliasConfig(allSiteResources)
});
}
+5
View File
@@ -94,6 +94,11 @@ export const OlmErrorCodes = {
HOLEPUNCH_MISSING: {
code: "HOLEPUNCH_MISSING",
message: `Unable to coordinate client P2P connection. Please ensure your client can reach the server on UDP port ${udpPort} and try registering again.`
},
NO_AVAILABLE_SUBNET: {
code: "NO_AVAILABLE_SUBNET",
message:
"No available subnet could be assigned to this client on the selected exit node. Please contact your administrator to increase the available address space for this exit node's subnet."
}
} as const;
+82
View File
@@ -0,0 +1,82 @@
import { sendToClientsBatch } from "#dynamic/routers/ws";
import { db, olms } from "@server/db";
import { canCompress } from "@server/lib/clientVersionChecks";
import logger from "@server/logger";
import { inArray } from "drizzle-orm";
// The olm only tracks which gateway (exit node) site resource it selected, by
// its numeric siteResourceId, and the site IDs that resource currently
// resolves to. So all the server has to push is what changed for that one
// resource; the olm ignores a message whose siteResourceId isn't the one it
// selected, which stops a site added to some other gateway resource from
// being pulled into the client's gateway set. (Creates aren't pushed: a
// client has to select a gateway resource before it can be using it.)
async function sendGatewayMessageToClients(
clientIds: number[],
type: string,
data: Record<string, unknown>
): Promise<void> {
const uniqueClientIds = Array.from(new Set(clientIds));
if (uniqueClientIds.length === 0) {
return;
}
const olmRows = await db
.select({
olmId: olms.olmId,
version: olms.version
})
.from(olms)
.where(inArray(olms.clientId, uniqueClientIds));
const payloads = olmRows.map((olm) => ({
clientId: olm.olmId,
message: { type, data },
options: {
compress: canCompress(olm.version, "olm"),
incrementConfigVersion: true
}
}));
if (payloads.length === 0) {
return;
}
await sendToClientsBatch(payloads).catch((error) => {
logger.error(`Error sending ${type} messages to olms:`, error);
});
}
// Tells the olms of the given clients that sites were added to / removed from
// the gateway site resource, so those that selected it can adjust the set of
// sites they use as the gateway.
export async function sendGatewaySitesUpdate(
clientIds: number[],
siteResourceId: number,
addedSiteIds: number[],
removedSiteIds: number[]
): Promise<void> {
if (addedSiteIds.length === 0 && removedSiteIds.length === 0) {
return;
}
await sendGatewayMessageToClients(
clientIds,
"olm/wg/gateway/sites/update",
{ siteResourceId, addedSiteIds, removedSiteIds }
);
}
// Tells the olms of the given clients that the gateway site resource can no
// longer be used as a gateway (it was deleted, disabled, changed to another
// mode, or the client lost access to it), so those that selected it drop out
// of gateway mode.
export async function sendGatewayDisable(
clientIds: number[],
siteResourceId: number
): Promise<void> {
await sendGatewayMessageToClients(clientIds, "olm/wg/gateway/disable", {
siteResourceId
});
}
+19 -2
View File
@@ -8,7 +8,8 @@ import {
ExitNode,
exitNodes,
sites,
clientSitesAssociationsCache
clientSitesAssociationsCache,
orgs
} from "@server/db";
import { olms } from "@server/db";
import HttpCode from "@server/types/HttpCode";
@@ -225,7 +226,23 @@ export async function getOlmToken(
)
.where(eq(clientSitesAssociationsCache.clientId, clientIdToUse!));
if (clientSites.length > 250 && build == "saas") {
const [org] = await db
.select()
.from(orgs)
.where(eq(orgs.orgId, orgIdToUse))
.limit(1);
if (!org) {
logger.warn(`Client ${clientIdToUse} org not found`);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Client's org not found"
)
);
}
if (clientSites.length > org.settingsJitModeLimit && build == "saas") {
// set all of the cache rows isJitMode to true
await db
.update(clientSitesAssociationsCache)
+69 -19
View File
@@ -1,9 +1,10 @@
import { db, sites } from "@server/db";
import { MessageHandler } from "@server/routers/ws";
import { clients, Olm } from "@server/db";
import { and, eq } from "drizzle-orm";
import { updatePeer as newtUpdatePeer } from "../newt/peers";
import { eq, inArray } from "drizzle-orm";
import { updatePeersBatch } from "../newt/peers";
import logger from "@server/logger";
import { parseSiteChainBatch, resolveNewtIdsBySite } from "./batchUtils";
export const handleOlmLocalMessage: MessageHandler = async (context) => {
const { message, client: c, sendToClient } = context;
@@ -40,33 +41,82 @@ export const handleOlmLocalMessage: MessageHandler = async (context) => {
return;
}
const { siteId, chainId } = message.data;
const { siteIds, chainIds, isBatch } = parseSiteChainBatch(message.data);
// Get the site
const [site] = await db
.select()
.from(sites)
.where(eq(sites.siteId, siteId))
.limit(1);
if (!site || !site.exitNodeId) {
logger.warn("Site not found or has no exit node");
if (siteIds.length === 0) {
logger.warn("Local message has no siteId(s)");
return;
}
// update the peer on the newt
await newtUpdatePeer(siteId, client.pubKey, {
endpoint: "" // this removes the endpoint so the newt knows to accept local
// Get the sites
const siteRows = await db
.select()
.from(sites)
.where(inArray(sites.siteId, siteIds));
const sitesById = new Map(siteRows.map((s) => [s.siteId, s]));
const valid: { siteId: number; chainId?: string }[] = [];
for (let i = 0; i < siteIds.length; i++) {
const siteId = siteIds[i];
const site = sitesById.get(siteId);
if (!site || !site.exitNodeId) {
logger.warn(`Site ${siteId} not found or has no exit node`);
continue;
}
valid.push({ siteId, chainId: chainIds[i] });
}
if (valid.length === 0) {
return;
}
// Only ack sites we can actually tell their newt to accept local
const newtIdBySiteId = await resolveNewtIdsBySite(valid.map((v) => v.siteId));
const pushable = valid.filter((v) => {
if (!newtIdBySiteId.has(v.siteId)) {
logger.warn(`Newt not found for site ${v.siteId}`);
return false;
}
return true;
});
if (pushable.length === 0) {
return;
}
// update the peer on each newt to accept local
await updatePeersBatch(
pushable.map((v) => ({
siteId: v.siteId,
publicKey: client.pubKey!,
newtId: newtIdBySiteId.get(v.siteId)!,
peer: { endpoint: "" } // this removes the endpoint so the newt knows to accept local
}))
);
// Just ack the message, we don't keep sending it
if (isBatch) {
return {
message: {
type: "olm/wg/peer/local",
data: {
siteIds: pushable.map((v) => v.siteId),
chainIds: pushable.map((v) => v.chainId)
}
},
broadcast: false,
excludeSender: false
};
}
const single = pushable[0];
return {
message: {
type: "olm/wg/peer/local",
data: {
siteId: siteId,
chainId
}
data: { siteId: single.siteId, chainId: single.chainId }
},
broadcast: false,
excludeSender: false
@@ -30,6 +30,7 @@ import {
} from "#dynamic/lib/exitNodes";
import { getUniqueSubnetForExitNode } from "@server/lib/exitNodes";
import { addPeer, deletePeer } from "../gerbil/peers";
import { formatEndpoint } from "@server/lib/ip";
const HOLEPUNCH_STALE_CHAIN_THRESHOLD = 18;
const HOLEPUNCH_STALE_CHAIN_TTL_SECONDS = 1800;
@@ -277,7 +278,7 @@ export const handleOlmRegisterMessage: MessageHandler = async (context) => {
);
let jitMode = false;
if (sitesCount > 250 && build == "saas") {
if (sitesCount > org.settingsJitModeLimit && build == "saas") {
// THIS IS THE MAX ON THE BUSINESS TIER
// we have too many sites
// If we have too many sites we need to drop into fully JIT mode by not sending any of the sites
@@ -347,6 +348,7 @@ export const handleOlmRegisterMessage: MessageHandler = async (context) => {
`[handleOlmRegisterMessage] No available subnets found for exit node id ${exitNodeId} and client id ${client.clientId}`,
{ orgId: client.orgId, clientId: client.clientId }
);
sendOlmError(OlmErrorCodes.NO_AVAILABLE_SUBNET, olm.olmId);
return;
}
@@ -507,7 +509,7 @@ export const handleOlmRegisterMessage: MessageHandler = async (context) => {
? {
aliases: exitNodeAliases,
connect: exitNodeAliases.length > 0, // we do not need to connect to the exit node if we do not have inference resources and right now all site resources on the exit node have an alias
endpoint: `${exitNode.endpoint}:${exitNode.listenPort}`,
endpoint: formatEndpoint(exitNode.endpoint, exitNode.listenPort),
publicKey: exitNode.publicKey,
serverIP: exitNode.address.split("/")[0],
tunnelIP: `${clientSubnet.split("/")[0]}/${exitNode.address.split("/")[1]}` // we need to use the exit node's subnet mask here because the client will be using the exit node's subnet mask for its routing table so we can address it
+106 -27
View File
@@ -1,10 +1,11 @@
import { db, exitNodes, sites } from "@server/db";
import { MessageHandler } from "@server/routers/ws";
import { clients, clientSitesAssociationsCache, Olm } from "@server/db";
import { and, eq } from "drizzle-orm";
import { updatePeer as newtUpdatePeer } from "../newt/peers";
import { and, eq, inArray } from "drizzle-orm";
import { updatePeersBatch } from "../newt/peers";
import logger from "@server/logger";
import config from "@server/lib/config";
import { parseSiteChainBatch, resolveNewtIdsBySite } from "./batchUtils";
export const handleOlmRelayMessage: MessageHandler = async (context) => {
const { message, client: c, sendToClient } = context;
@@ -41,29 +42,66 @@ export const handleOlmRelayMessage: MessageHandler = async (context) => {
return;
}
const { siteId, chainId } = message.data;
const { siteIds, chainIds, isBatch } = parseSiteChainBatch(message.data);
// Get the site
const [site] = await db
.select()
.from(sites)
.where(eq(sites.siteId, siteId))
.limit(1);
if (!site || !site.exitNodeId) {
logger.warn("Site not found or has no exit node");
if (siteIds.length === 0) {
logger.warn("Relay message has no siteId(s)");
return;
}
// get the site's exit node
const [exitNode] = await db
// Get the sites
const siteRows = await db
.select()
.from(exitNodes)
.where(eq(exitNodes.exitNodeId, site.exitNodeId))
.limit(1);
.from(sites)
.where(inArray(sites.siteId, siteIds));
const sitesById = new Map(siteRows.map((s) => [s.siteId, s]));
if (!exitNode) {
logger.warn("Exit node not found for site");
const exitNodeIds = [
...new Set(
siteRows
.map((s) => s.exitNodeId)
.filter((id): id is number => id != null)
)
];
// Get the sites' exit nodes
const exitNodeRows = exitNodeIds.length
? await db
.select()
.from(exitNodes)
.where(inArray(exitNodes.exitNodeId, exitNodeIds))
: [];
const exitNodesById = new Map(exitNodeRows.map((e) => [e.exitNodeId, e]));
const valid: {
siteId: number;
chainId?: string;
relayEndpoint: string;
}[] = [];
for (let i = 0; i < siteIds.length; i++) {
const siteId = siteIds[i];
const site = sitesById.get(siteId);
if (!site || !site.exitNodeId) {
logger.warn(`Site ${siteId} not found or has no exit node`);
continue;
}
const exitNode = exitNodesById.get(site.exitNodeId);
if (!exitNode) {
logger.warn(`Exit node not found for site ${siteId}`);
continue;
}
valid.push({
siteId,
chainId: chainIds[i],
relayEndpoint: exitNode.endpoint
});
}
if (valid.length === 0) {
return;
}
@@ -75,23 +113,64 @@ export const handleOlmRelayMessage: MessageHandler = async (context) => {
.where(
and(
eq(clientSitesAssociationsCache.clientId, olm.clientId),
eq(clientSitesAssociationsCache.siteId, siteId)
inArray(
clientSitesAssociationsCache.siteId,
valid.map((v) => v.siteId)
)
)
);
// update the peer on the newt
await newtUpdatePeer(siteId, client.pubKey, {
endpoint: "" // this removes the endpoint so the newt knows to relay
// Only ack sites we can actually tell their newt to relay for
const newtIdBySiteId = await resolveNewtIdsBySite(valid.map((v) => v.siteId));
const pushable = valid.filter((v) => {
if (!newtIdBySiteId.has(v.siteId)) {
logger.warn(`Newt not found for site ${v.siteId}`);
return false;
}
return true;
});
if (pushable.length === 0) {
return;
}
// update the peer on each newt so it knows to relay
await updatePeersBatch(
pushable.map((v) => ({
siteId: v.siteId,
publicKey: client.pubKey!,
newtId: newtIdBySiteId.get(v.siteId)!,
peer: { endpoint: "" } // this removes the endpoint so the newt knows to relay
}))
);
const relayPort = config.getRawConfig().gerbil.clients_start_port;
if (isBatch) {
return {
message: {
type: "olm/wg/peer/relay",
data: {
siteIds: pushable.map((v) => v.siteId),
relayEndpoints: pushable.map((v) => v.relayEndpoint),
relayPort,
chainIds: pushable.map((v) => v.chainId)
}
},
broadcast: false,
excludeSender: false
};
}
const single = pushable[0];
return {
message: {
type: "olm/wg/peer/relay",
data: {
siteId: siteId,
relayEndpoint: exitNode.endpoint,
relayPort: config.getRawConfig().gerbil.clients_start_port,
chainId
siteId: single.siteId,
relayEndpoint: single.relayEndpoint,
relayPort,
chainId: single.chainId
}
},
broadcast: false,
+89 -31
View File
@@ -1,9 +1,10 @@
import { db, exitNodes, sites } from "@server/db";
import { db, sites } from "@server/db";
import { MessageHandler } from "@server/routers/ws";
import { clients, clientSitesAssociationsCache, Olm } from "@server/db";
import { and, eq } from "drizzle-orm";
import { updatePeer as newtUpdatePeer } from "../newt/peers";
import { and, eq, inArray } from "drizzle-orm";
import { updatePeersBatch } from "../newt/peers";
import logger from "@server/logger";
import { parseSiteChainBatch, resolveNewtIdsBySite } from "./batchUtils";
export const handleOlmUnLocalMessage: MessageHandler = async (context) => {
const { message, client: c, sendToClient } = context;
@@ -40,54 +41,111 @@ export const handleOlmUnLocalMessage: MessageHandler = async (context) => {
return;
}
const { siteId, chainId } = message.data;
const { siteIds, chainIds, isBatch } = parseSiteChainBatch(message.data);
// Get the site
const [site] = await db
.select()
.from(sites)
.where(eq(sites.siteId, siteId))
.limit(1);
if (!site) {
logger.warn("Site not found or has no exit node");
if (siteIds.length === 0) {
logger.warn("Unlocal message has no siteId(s)");
return;
}
const [clientSiteAssociation] = await db
// Get the sites
const siteRows = await db
.select()
.from(sites)
.where(inArray(sites.siteId, siteIds));
const sitesById = new Map(siteRows.map((s) => [s.siteId, s]));
const assocRows = await db
.select()
.from(clientSitesAssociationsCache)
.where(
and(
eq(clientSitesAssociationsCache.clientId, olm.clientId),
eq(clientSitesAssociationsCache.siteId, siteId)
inArray(clientSitesAssociationsCache.siteId, siteIds)
)
);
const assocBySiteId = new Map(assocRows.map((a) => [a.siteId, a]));
if (!clientSiteAssociation) {
logger.warn("Client-Site association not found");
const valid: { siteId: number; chainId?: string; endpoint: string }[] = [];
for (let i = 0; i < siteIds.length; i++) {
const siteId = siteIds[i];
const site = sitesById.get(siteId);
if (!site) {
logger.warn(`Site ${siteId} not found or has no exit node`);
continue;
}
const clientSiteAssociation = assocBySiteId.get(siteId);
if (!clientSiteAssociation) {
logger.warn(`Client-Site association not found for site ${siteId}`);
continue;
}
if (!clientSiteAssociation.endpoint) {
logger.warn(
`Client-Site association has no endpoint, cannot unrelay site ${siteId}`
);
continue;
}
valid.push({
siteId,
chainId: chainIds[i],
endpoint: clientSiteAssociation.isRelayed
? ""
: clientSiteAssociation.endpoint // this is the endpoint of the client to connect directly to the newt
});
}
if (valid.length === 0) {
return;
}
if (!clientSiteAssociation.endpoint) {
logger.warn("Client-Site association has no endpoint, cannot unrelay");
return;
}
// update the peer on the newt
await newtUpdatePeer(siteId, client.pubKey, {
endpoint: clientSiteAssociation.isRelayed
? ""
: clientSiteAssociation.endpoint // this is the endpoint of the client to connect directly to the newt
// Only ack sites we can actually push to their newt
const newtIdBySiteId = await resolveNewtIdsBySite(valid.map((v) => v.siteId));
const pushable = valid.filter((v) => {
if (!newtIdBySiteId.has(v.siteId)) {
logger.warn(`Newt not found for site ${v.siteId}`);
return false;
}
return true;
});
if (pushable.length === 0) {
return;
}
// update the peer on each newt
await updatePeersBatch(
pushable.map((v) => ({
siteId: v.siteId,
publicKey: client.pubKey!,
newtId: newtIdBySiteId.get(v.siteId)!,
peer: { endpoint: v.endpoint }
}))
);
if (isBatch) {
return {
message: {
type: "olm/wg/peer/unlocal",
data: {
siteIds: pushable.map((v) => v.siteId),
chainIds: pushable.map((v) => v.chainId)
}
},
broadcast: false,
excludeSender: false
};
}
const single = pushable[0];
return {
message: {
type: "olm/wg/peer/unlocal",
data: {
siteId: siteId,
chainId
}
data: { siteId: single.siteId, chainId: single.chainId }
},
broadcast: false,
excludeSender: false
+95 -27
View File
@@ -1,9 +1,10 @@
import { db, exitNodes, sites } from "@server/db";
import { MessageHandler } from "@server/routers/ws";
import { clients, clientSitesAssociationsCache, Olm } from "@server/db";
import { and, eq } from "drizzle-orm";
import { updatePeer as newtUpdatePeer } from "../newt/peers";
import { and, eq, inArray } from "drizzle-orm";
import { updatePeersBatch } from "../newt/peers";
import logger from "@server/logger";
import { parseSiteChainBatch, resolveNewtIdsBySite } from "./batchUtils";
export const handleOlmUnRelayMessage: MessageHandler = async (context) => {
const { message, client: c, sendToClient } = context;
@@ -40,21 +41,21 @@ export const handleOlmUnRelayMessage: MessageHandler = async (context) => {
return;
}
const { siteId, chainId } = message.data;
const { siteIds, chainIds, isBatch } = parseSiteChainBatch(message.data);
// Get the site
const [site] = await db
.select()
.from(sites)
.where(eq(sites.siteId, siteId))
.limit(1);
if (!site) {
logger.warn("Site not found or has no exit node");
if (siteIds.length === 0) {
logger.warn("Unrelay message has no siteId(s)");
return;
}
const [clientSiteAssociation] = await db
// Get the sites
const siteRows = await db
.select()
.from(sites)
.where(inArray(sites.siteId, siteIds));
const sitesById = new Map(siteRows.map((s) => [s.siteId, s]));
const assocRows = await db
.update(clientSitesAssociationsCache)
.set({
isRelayed: false
@@ -62,33 +63,100 @@ export const handleOlmUnRelayMessage: MessageHandler = async (context) => {
.where(
and(
eq(clientSitesAssociationsCache.clientId, olm.clientId),
eq(clientSitesAssociationsCache.siteId, siteId)
inArray(clientSitesAssociationsCache.siteId, siteIds)
)
)
.returning();
const assocBySiteId = new Map(assocRows.map((a) => [a.siteId, a]));
if (!clientSiteAssociation) {
logger.warn("Client-Site association not found");
const valid: {
siteId: number;
chainId?: string;
endpoint: string;
clientEndpoint: string;
}[] = [];
for (let i = 0; i < siteIds.length; i++) {
const siteId = siteIds[i];
const site = sitesById.get(siteId);
if (!site) {
logger.warn(`Site ${siteId} not found or has no exit node`);
continue;
}
const clientSiteAssociation = assocBySiteId.get(siteId);
if (!clientSiteAssociation) {
logger.warn(`Client-Site association not found for site ${siteId}`);
continue;
}
if (!clientSiteAssociation.endpoint) {
logger.warn(
`Client-Site association has no endpoint, cannot unrelay site ${siteId}`
);
continue;
}
valid.push({
siteId,
chainId: chainIds[i],
endpoint: site.endpoint ?? "",
clientEndpoint: clientSiteAssociation.endpoint
});
}
if (valid.length === 0) {
return;
}
if (!clientSiteAssociation.endpoint) {
logger.warn("Client-Site association has no endpoint, cannot unrelay");
return;
}
// update the peer on the newt
await newtUpdatePeer(siteId, client.pubKey, {
endpoint: clientSiteAssociation.endpoint // this is the endpoint of the client to connect directly to the newt
// Only ack sites we can actually tell their newt to connect directly
const newtIdBySiteId = await resolveNewtIdsBySite(valid.map((v) => v.siteId));
const pushable = valid.filter((v) => {
if (!newtIdBySiteId.has(v.siteId)) {
logger.warn(`Newt not found for site ${v.siteId}`);
return false;
}
return true;
});
if (pushable.length === 0) {
return;
}
// update the peer on each newt to connect directly to the client
await updatePeersBatch(
pushable.map((v) => ({
siteId: v.siteId,
publicKey: client.pubKey!,
newtId: newtIdBySiteId.get(v.siteId)!,
peer: { endpoint: v.clientEndpoint } // this is the endpoint of the client to connect directly to the newt
}))
);
if (isBatch) {
return {
message: {
type: "olm/wg/peer/unrelay",
data: {
siteIds: pushable.map((v) => v.siteId),
endpoints: pushable.map((v) => v.endpoint),
chainIds: pushable.map((v) => v.chainId)
}
},
broadcast: false,
excludeSender: false
};
}
const single = pushable[0];
return {
message: {
type: "olm/wg/peer/unrelay",
data: {
siteId: siteId,
endpoint: site.endpoint,
chainId
siteId: single.siteId,
endpoint: single.endpoint,
chainId: single.chainId
}
},
broadcast: false,
+14 -2
View File
@@ -5,7 +5,8 @@ import {
exitNodes,
Olm,
sites,
clientSitesAssociationsCache
clientSitesAssociationsCache,
orgs
} from "@server/db";
import { buildSiteConfigurationForOlmClient } from "./buildConfiguration";
import { sendToClient } from "#dynamic/routers/ws";
@@ -36,8 +37,19 @@ export async function sendOlmSyncMessage(olm: Olm, client: Client) {
{ orgId: client.orgId }
);
const [org] = await db
.select()
.from(orgs)
.where(eq(orgs.orgId, client.orgId))
.limit(1);
if (!org) {
logger.warn(`Client ${client.clientId} org not found`);
return;
}
let jitMode = false;
if (sitesCount > 250 && build == "saas") {
if (sitesCount > org.settingsJitModeLimit && build == "saas") {
// THIS IS THE MAX ON THE BUSINESS TIER
// we have too many sites
// If we have too many sites we need to drop into fully JIT mode by not sending any of the sites
+2 -1
View File
@@ -25,7 +25,7 @@ import { fromError } from "zod-validation-error";
import { defaultRoleAllowedActions } from "../role";
import { OpenAPITags, registry } from "@server/openApi";
import { isValidCIDR } from "@server/lib/validators";
import { createCustomer } from "#dynamic/lib/billing";
import { createCustomer, linkEmailOrg } from "#dynamic/lib/billing";
import { usageService } from "@server/lib/billing/usageService";
import { LimitId, limitsService, freeLimitSet } from "@server/lib/billing";
import { build } from "@server/build";
@@ -425,6 +425,7 @@ export async function createOrg(
customerId
); // Only 1 because we are creating the org
}
await linkEmailOrg(orgId, req.user?.email);
}
if (numOrgs) {
+9 -5
View File
@@ -53,9 +53,10 @@ async function queryInlinePolicy(resourcePolicyId: number) {
export type GetResourceResponse = Omit<
NonNullable<Awaited<ReturnType<typeof query>>>,
"headers"
"requestHeaders" | "responseHeaders"
> & {
headers: { name: string; value: string }[] | null;
requestHeaders: { name: string; value: string }[] | null;
responseHeaders: { name: string; value: string }[] | null;
};
registry.registerPath({
@@ -186,9 +187,12 @@ export async function getResource(
return response<GetResourceResponse>(res, {
data: {
...returnData,
headers: returnData.headers
? JSON.parse(returnData.headers)
: returnData.headers
requestHeaders: returnData.requestHeaders
? JSON.parse(returnData.requestHeaders)
: returnData.requestHeaders,
responseHeaders: returnData.responseHeaders
? JSON.parse(returnData.responseHeaders)
: returnData.responseHeaders
},
success: true,
error: false,
+59 -31
View File
@@ -100,6 +100,14 @@ const updateHttpResourceBodySchema = z
"When no shared resource policy is assigned (resourcePolicyId is null), updates the resource's inline policy. When a shared policy is assigned, this value overrides the shared policy for this resource."
),
headers: z
.array(z.strictObject({ name: z.string(), value: z.string() }))
.nullable()
.optional(), // deprecated alias for requestHeaders
requestHeaders: z
.array(z.strictObject({ name: z.string(), value: z.string() }))
.nullable()
.optional(),
responseHeaders: z
.array(z.strictObject({ name: z.string(), value: z.string() }))
.nullable()
.optional(),
@@ -163,12 +171,13 @@ const updateHttpResourceBodySchema = z
)
.refine(
(data) => {
if (data.headers) {
// HTTP header names must be valid token characters (RFC 7230)
const validHeaderName = /^[a-zA-Z0-9!#$%&'*+\-.^_`|~]+$/;
return data.headers.every((h) => validHeaderName.test(h.name));
}
return true;
const validHeaderName = /^[a-zA-Z0-9!#$%&'*+\-.^_`|~]+$/;
const allHeaders = [
...(data.headers ?? []),
...(data.requestHeaders ?? []),
...(data.responseHeaders ?? [])
];
return allHeaders.every((h) => validHeaderName.test(h.name));
},
{
error: "Header names may only contain valid HTTP token characters (letters, digits, and !#$%&'*+-.^_`|~)."
@@ -176,14 +185,13 @@ const updateHttpResourceBodySchema = z
)
.refine(
(data) => {
if (data.headers) {
// HTTP header values must be visible ASCII or horizontal whitespace, no control chars (RFC 7230)
const validHeaderValue = /^[\t\x20-\x7E]*$/;
return data.headers.every((h) =>
validHeaderValue.test(h.value)
);
}
return true;
const validHeaderValue = /^[\t\x20-\x7E]*$/;
const allHeaders = [
...(data.headers ?? []),
...(data.requestHeaders ?? []),
...(data.responseHeaders ?? [])
];
return allHeaders.every((h) => validHeaderValue.test(h.value));
},
{
error: "Header values may only contain printable ASCII characters and horizontal whitespace."
@@ -191,16 +199,17 @@ const updateHttpResourceBodySchema = z
)
.refine(
(data) => {
if (data.headers) {
// Reject Traefik template syntax {{word}} in names or values
const templatePattern = /\{\{[^}]+\}\}/;
return data.headers.every(
(h) =>
!templatePattern.test(h.name) &&
!templatePattern.test(h.value)
);
}
return true;
const templatePattern = /\{\{[^}]+\}\}/;
const allHeaders = [
...(data.headers ?? []),
...(data.requestHeaders ?? []),
...(data.responseHeaders ?? [])
];
return allHeaders.every(
(h) =>
!templatePattern.test(h.name) &&
!templatePattern.test(h.value)
);
},
{
error: "Header names and values must not contain template expressions such as {{value}}."
@@ -696,13 +705,32 @@ async function updateHttpResource(
await createCertificate(domainId, fullDomain, db);
}
let headers = undefined;
if (updateData.headers) {
headers = JSON.stringify(updateData.headers);
} else if (updateData.headers === null) {
headers = null;
let requestHeaders = undefined;
const mergedRequestHeaders = [
...(updateData.headers ?? []),
...(updateData.requestHeaders ?? [])
];
if (
updateData.headers !== undefined ||
updateData.requestHeaders !== undefined
) {
requestHeaders =
mergedRequestHeaders.length > 0
? JSON.stringify(mergedRequestHeaders)
: null;
}
let responseHeaders = undefined;
if (updateData.responseHeaders) {
responseHeaders = JSON.stringify(updateData.responseHeaders);
} else if (updateData.responseHeaders === null) {
responseHeaders = null;
}
updateData.headers = undefined;
updateData.requestHeaders = undefined;
updateData.responseHeaders = undefined;
if (!isLicensed) {
updateData.maintenanceModeEnabled = undefined;
updateData.maintenanceModeType = undefined;
@@ -755,7 +783,7 @@ async function updateHttpResource(
const updatedResource = await db
.update(resources)
.set({ ...resourceOnlyData, headers })
.set({ ...resourceOnlyData, requestHeaders, responseHeaders })
.where(eq(resources.resourceId, resource.resourceId))
.returning();
@@ -779,7 +807,7 @@ async function updateHttpResource(
const updatedResource = await db
.update(resources)
.set({ ...updateData, headers })
.set({ ...updateData, requestHeaders, responseHeaders })
.where(eq(resources.resourceId, resource.resourceId))
.returning();
@@ -53,7 +53,7 @@ const createSiteResourceSchema = z
name: z.string().min(1).max(255),
niceId: z.string().optional(),
// protocol: z.enum(["tcp", "udp"]).optional(),
mode: z.enum(["host", "cidr", "http", "ssh", "inference"]),
mode: z.enum(["host", "cidr", "http", "ssh", "inference", "gateway"]),
ssl: z.boolean().optional(), // only used for http mode
scheme: z.enum(["http", "https"]).optional(),
siteIds: z.array(z.int()).optional(),
@@ -165,10 +165,11 @@ const createSiteResourceSchema = z
)
.refine(
(data) => {
// destination is only optional for ssh mode with native authDaemonMode or inference
// destination is only optional for ssh mode with native authDaemonMode, inference, or gateway
if (
(data.mode === "ssh" && data.authDaemonMode === "native") ||
data.mode == "inference"
data.mode == "inference" ||
data.mode == "gateway"
) {
return true;
}
@@ -179,7 +180,7 @@ const createSiteResourceSchema = z
},
{
message:
"Destination is required unless mode is ssh with authDaemonMode native or inference"
"Destination is required unless mode is ssh with authDaemonMode native, inference, or gateway"
}
)
.refine(
@@ -447,14 +448,18 @@ export async function createSiteResource(
);
}
// gateway resources always route the whole subnet with everything open
const effectiveDestination =
mode === "gateway" ? "0.0.0.0/0" : destination;
// Only check if destination is an IP address
const isIp = z
.union([z.ipv4(), z.ipv6()])
.safeParse(destination).success;
.safeParse(effectiveDestination).success;
if (
isIp &&
(isIpInCidr(destination!, org.subnet) ||
isIpInCidr(destination!, org.utilitySubnet))
(isIpInCidr(effectiveDestination!, org.subnet) ||
isIpInCidr(effectiveDestination!, org.utilitySubnet))
) {
return next(
createHttpError(
@@ -584,6 +589,32 @@ export async function createSiteResource(
tcpPortRangeStringAdjusted = destinationPort
? destinationPort.toString()
: "22";
} else if (mode === "gateway") {
tcpPortRangeStringAdjusted = "*";
}
let udpPortRangeStringAdjusted = udpPortRangeString;
if (mode === "gateway") {
udpPortRangeStringAdjusted = "*";
} else if (
mode === "http" ||
mode === "ssh" ||
mode === "inference"
) {
udpPortRangeStringAdjusted = "";
}
// default to true for http/ssh/inference, false otherwise;
// gateway always allows icmp
let disableIcmpAdjusted = disableIcmp ?? false;
if (mode === "gateway") {
disableIcmpAdjusted = false;
} else if (
mode === "http" ||
mode === "ssh" ||
mode === "inference"
) {
disableIcmpAdjusted = true;
}
// Create the site resource
@@ -594,21 +625,14 @@ export async function createSiteResource(
mode,
ssl,
networkId: network ? network.networkId : null,
destination: destination, // the ssh can be null
destination: effectiveDestination, // the ssh can be null
scheme,
destinationPort,
alias: alias ? alias.trim() : null,
aliasAddress,
tcpPortRangeString: tcpPortRangeStringAdjusted,
udpPortRangeString:
mode == "http" || mode == "ssh" || mode == "inference"
? ""
: udpPortRangeString,
disableIcmp:
disableIcmp ||
(mode == "http" || mode == "ssh" || mode == "inference"
? true
: false), // default to true for http resources, otherwise false
udpPortRangeString: udpPortRangeStringAdjusted,
disableIcmp: disableIcmpAdjusted,
domainId,
subdomain: finalSubdomain,
fullDomain,
@@ -51,7 +51,9 @@ const updateSiteResourceSchema = z
)
.optional(),
// mode: z.enum(["host", "cidr", "port"]).optional(),
mode: z.enum(["host", "cidr", "http", "ssh", "inference"]).optional(),
mode: z
.enum(["host", "cidr", "http", "ssh", "inference", "gateway"])
.optional(),
ssl: z.boolean().optional(),
scheme: z.enum(["http", "https"]).nullish(),
destinationPort: z.int().positive().nullish(),
@@ -158,10 +160,11 @@ const updateSiteResourceSchema = z
if (data.mode === undefined && data.destination === undefined) {
return true;
}
// destination is only optional for ssh mode with native authDaemonMode or inference
// destination is only optional for ssh mode with native authDaemonMode, inference, or gateway
if (
(data.mode === "ssh" && data.authDaemonMode === "native") ||
data.mode == "inference"
data.mode == "inference" ||
data.mode == "gateway"
) {
return true;
}
@@ -172,7 +175,7 @@ const updateSiteResourceSchema = z
},
{
message:
"Destination is required unless mode is ssh with authDaemonMode native or inference"
"Destination is required unless mode is ssh with authDaemonMode native, inference, or gateway"
}
)
.refine(
@@ -409,14 +412,18 @@ export async function updateSiteResource(
}
}
// gateway resources always route the whole subnet with everything open
const effectiveDestination =
mode === "gateway" ? "0.0.0.0/0" : destination;
// Only check if destination is an IP address
const isIp = z
.union([z.ipv4(), z.ipv6()])
.safeParse(destination).success;
.safeParse(effectiveDestination).success;
if (
isIp &&
(isIpInCidr(destination!, org.subnet) ||
isIpInCidr(destination!, org.utilitySubnet))
(isIpInCidr(effectiveDestination!, org.subnet) ||
isIpInCidr(effectiveDestination!, org.utilitySubnet))
) {
return next(
createHttpError(
@@ -542,6 +549,34 @@ export async function updateSiteResource(
tcpPortRangeStringAdjusted = destinationPort
? destinationPort.toString()
: "22";
} else if (mode === "gateway") {
tcpPortRangeStringAdjusted = "*";
}
// undefined means "leave unchanged" (partial update); only
// adjusted when the mode is explicitly being changed
let udpPortRangeStringAdjusted = udpPortRangeString;
if (mode === "gateway") {
udpPortRangeStringAdjusted = "*";
} else if (
mode === "http" ||
mode === "ssh" ||
mode === "inference"
) {
udpPortRangeStringAdjusted = "";
}
let disableIcmpAdjusted = disableIcmp;
if (mode === "gateway") {
disableIcmpAdjusted = false;
} else if (
mode === "http" ||
mode === "ssh" ||
mode === "inference"
) {
disableIcmpAdjusted = true;
} else if (mode !== undefined) {
disableIcmpAdjusted = disableIcmp ?? false;
}
[updatedSiteResource] = await trx
@@ -552,7 +587,8 @@ export async function updateSiteResource(
mode: mode,
scheme,
ssl,
destination: destination,
destination:
mode === "gateway" ? effectiveDestination : destination,
destinationPort: destinationPort,
enabled: enabled,
alias:
@@ -562,19 +598,8 @@ export async function updateSiteResource(
: null
: undefined,
tcpPortRangeString: tcpPortRangeStringAdjusted,
udpPortRangeString:
mode == "http" || mode == "ssh" || mode == "inference"
? ""
: udpPortRangeString,
disableIcmp:
mode !== undefined
? disableIcmp ||
(mode == "http" ||
mode == "ssh" ||
mode == "inference"
? true
: false)
: disableIcmp,
udpPortRangeString: udpPortRangeStringAdjusted,
disableIcmp: disableIcmpAdjusted,
domainId,
subdomain: finalSubdomain,
fullDomain,
@@ -51,6 +51,10 @@ export async function traefikConfigProvider(
.internal_hostname
}:${config.getRawConfig().server.internal_port}`
).href,
disableDefaultCFIPs: config.getRawConfig().server.trust_ips.length > 0,
customIPHeader: config.getRawConfig().server.custom_ip_header,
trustip: config.getRawConfig().server.trust_ips,
userSessionCookieName:
config.getRawConfig().server.session_cookie_name,
+3 -1
View File
@@ -30,6 +30,7 @@ import m21 from "./scriptsPg/1.20.0";
import m22 from "./scriptsPg/1.21.0";
import m23 from "./scriptsPg/1.22.0";
import m24 from "./scriptsPg/1.23.0";
import m25 from "./scriptsPg/1.24.0";
// THIS CANNOT IMPORT ANYTHING FROM THE SERVER
// EXCEPT FOR THE DATABASE AND THE SCHEMA
@@ -59,7 +60,8 @@ const migrations = [
{ version: "1.20.0", run: m21 },
{ version: "1.21.0", run: m22 },
{ version: "1.22.0", run: m23 },
{ version: "1.23.0", run: m24 }
{ version: "1.23.0", run: m24 },
{ version: "1.24.0", run: m25 }
// Add new migrations here as they are created
] as {
version: string;
+3 -1
View File
@@ -50,6 +50,7 @@ import m43 from "./scriptsSqlite/1.20.0";
import m44 from "./scriptsSqlite/1.21.0";
import m45 from "./scriptsSqlite/1.22.0";
import m46 from "./scriptsSqlite/1.23.0";
import m47 from "./scriptsSqlite/1.24.0";
// THIS CANNOT IMPORT ANYTHING FROM THE SERVER
// EXCEPT FOR THE DATABASE AND THE SCHEMA
@@ -96,7 +97,8 @@ const migrations = [
{ version: "1.20.0", run: m43 },
{ version: "1.21.0", run: m44 },
{ version: "1.22.0", run: m45 },
{ version: "1.23.0", run: m46 }
{ version: "1.23.0", run: m46 },
{ version: "1.24.0", run: m47 }
// Add new migrations here as they are created
] as const;
+34
View File
@@ -0,0 +1,34 @@
import { db } from "@server/db/pg/driver";
import { sql } from "drizzle-orm";
const version = "1.24.0";
export default async function migration() {
console.log(`Running setup script ${version}...`);
try {
await db.execute(sql`BEGIN`);
await db.execute(sql`
ALTER TABLE "resources" RENAME COLUMN "headers" TO "requestHeaders"
`);
await db.execute(sql`
ALTER TABLE "orgs" ADD COLUMN "settingsJitModeLimit" integer DEFAULT 250 NOT NULL;
`);
await db.execute(sql`
ALTER TABLE "resources" ADD COLUMN "responseHeaders" text;
`);
await db.execute(sql`COMMIT`);
console.log("Migrated database");
} catch (e) {
await db.execute(sql`ROLLBACK`);
console.log("Unable to migrate database");
console.log(e);
throw e;
}
console.log(`${version} migration complete`);
}
+45
View File
@@ -0,0 +1,45 @@
import { APP_PATH } from "@server/lib/consts";
import Database from "better-sqlite3";
import path from "path";
const version = "1.24.0";
export default async function migration() {
console.log(`Running setup script ${version}...`);
const location = path.join(APP_PATH, "db", "db.sqlite");
const db = new Database(location);
try {
db.pragma("foreign_keys = OFF");
db.transaction(() => {
db.prepare(
`
ALTER TABLE 'resources' RENAME COLUMN "headers" TO "requestHeaders";
`
).run();
db.prepare(
`
ALTER TABLE 'resources' ADD 'responseHeaders' text;
`
).run();
db.prepare(
`
ALTER TABLE 'orgs' ADD 'settingsJitModeLimit' integer DEFAULT 250 NOT NULL;
`
).run();
})();
db.pragma("foreign_keys = ON");
console.log("Migrated database");
} catch (e) {
console.log("Failed to migrate db:", e);
throw e;
}
console.log(`${version} migration complete`);
}
@@ -524,6 +524,7 @@ export default function BillingPage() {
};
const currentPlanId = getCurrentPlanId();
const currentPlan = planOptions.find((p) => p.id === currentPlanId);
const visiblePlanOptions = planOptions.filter(
(plan) => plan.id !== "home" || currentPlanId === "home"
@@ -873,10 +874,8 @@ export default function BillingPage() {
{/* Trial Banner */}
{isTrial && (
<TrialBillingBanner
tierName={currentPlan?.name ?? "Business"}
onUpgrade={() => {
const currentPlan = planOptions.find(
(p) => p.id === currentPlanId
);
if (currentPlan?.tierType) {
handleStartSubscription(currentPlan.tierType);
}
@@ -0,0 +1,106 @@
"use client";
import {
SettingsContainer,
SettingsFormCell,
SettingsFormGrid,
SettingsSection,
SettingsSectionBody,
SettingsSectionDescription,
SettingsSectionFooter,
SettingsSectionForm,
SettingsSectionHeader,
SettingsSectionTitle
} from "@app/components/Settings";
import { Button } from "@app/components/ui/button";
import { Form } from "@app/components/ui/form";
import { createGatewayFormSchema } from "@app/lib/privateResourceForm";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslations } from "next-intl";
import { useActionState, useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { PrivateResourceSitesField } from "@app/components/PrivateResourceSitesField";
import { useSaveSiteResource } from "@app/hooks/useSaveSiteResource";
import { buildSelectedSitesForResource } from "@app/lib/privateResourceUtils";
export default function PrivateResourceGatewayPage() {
const t = useTranslations();
const { save, siteResource } = useSaveSiteResource();
const [selectedSites, setSelectedSites] = useState(() =>
buildSelectedSitesForResource(siteResource)
);
const formSchema = useMemo(() => createGatewayFormSchema(t), [t]);
type FormValues = z.infer<typeof formSchema>;
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
siteIds: siteResource.siteIds,
mode: "gateway"
}
});
const [, formAction, saveLoading] = useActionState(async () => {
const isValid = await form.trigger();
if (!isValid) return;
const data = form.getValues();
await save({
siteIds: data.siteIds,
mode: "gateway"
});
}, null);
return (
<SettingsContainer>
<SettingsSection>
<SettingsSectionHeader>
<SettingsSectionTitle>
{t("gatewaySettings")}
</SettingsSectionTitle>
<SettingsSectionDescription>
{t(
"editInternalResourceDialogDestinationGatewayDescription"
)}
</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsSectionBody>
<SettingsSectionForm variant="half">
<Form {...form}>
<form
action={formAction}
id="private-resource-gateway-form"
>
<SettingsFormGrid>
<SettingsFormCell span="half">
<PrivateResourceSitesField
control={form.control}
orgId={siteResource.orgId}
selectedSites={selectedSites}
onSelectedSitesChange={
setSelectedSites
}
/>
</SettingsFormCell>
</SettingsFormGrid>
</form>
</Form>
</SettingsSectionForm>
</SettingsSectionBody>
<SettingsSectionFooter>
<Button
type="submit"
form="private-resource-gateway-form"
loading={saveLoading}
>
{t("saveSettings")}
</Button>
</SettingsSectionFooter>
</SettingsSection>
</SettingsContainer>
);
}
@@ -53,7 +53,8 @@ export default async function PrivateResourceLayout(
| "cidrSettings"
| "httpSettings"
| "sshSettings"
| "inferenceSettings";
| "inferenceSettings"
| "gatewaySettings";
const navItems = [
{
@@ -24,7 +24,7 @@ import { useActionState, useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { PrivateResourceSshFields } from "@app/components/PrivateResourceSshFields";
import type { Selectedsite } from "@app/components/site-selector";
import type { SelectedSite } from "@app/components/site-selector";
import { useSaveSiteResource } from "@app/hooks/useSaveSiteResource";
import {
asAnyControl,
@@ -84,7 +84,7 @@ export default function PrivateResourceSshPage() {
setSelectedSites(first);
form.setValue(
"siteIds",
first.map((s: Selectedsite) => s.siteId),
first.map((s: SelectedSite) => s.siteId),
{ shouldValidate: true }
);
}
@@ -27,7 +27,7 @@ import {
FormMessage
} from "@app/components/ui/form";
import { Input } from "@app/components/ui/input";
import type { Selectedsite } from "@app/components/site-selector";
import type { SelectedSite } from "@app/components/site-selector";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { toast } from "@app/hooks/useToast";
import { createApiClient, formatAxiosError } from "@app/lib/api";
@@ -83,7 +83,7 @@ export default function CreatePrivateResourcePage() {
? Number(siteIdParam)
: null;
const [selectedSites, setSelectedSites] = useState<Selectedsite[]>([]);
const [selectedSites, setSelectedSites] = useState<SelectedSite[]>([]);
const [selectedProviders, setSelectedProviders] = useState<
SelectedAiProvider[]
>([]);
@@ -124,10 +124,10 @@ export default function CreatePrivateResourcePage() {
.then((res) => {
const site = res.data.data;
if (!site || site.orgId !== orgId) return;
const selected: Selectedsite = {
const selected: SelectedSite = {
siteId: site.siteId,
name: site.name,
type: site.type as Selectedsite["type"]
type: site.type as SelectedSite["type"]
};
setSelectedSites([selected]);
form.setValue("siteIds", [site.siteId]);
@@ -164,6 +164,11 @@ export default function CreatePrivateResourcePage() {
value: "inference" as const,
title: t("createInternalResourceDialogModeInference"),
description: t("resourceTypeInferenceDescription")
},
{
value: "gateway" as const,
title: t("createInternalResourceDialogModeGateway"),
description: t("resourceTypeGatewayDescription")
}
];
@@ -560,6 +565,38 @@ export default function CreatePrivateResourcePage() {
</SettingsSection>
)}
{/* Gateway destination */}
{mode === "gateway" && (
<SettingsSection>
<SettingsSectionHeader>
<SettingsSectionTitle>
{t("gatewaySettings")}
</SettingsSectionTitle>
<SettingsSectionDescription>
{t(
"editInternalResourceDialogDestinationGatewayDescription"
)}
</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsSectionBody>
<SettingsSectionForm variant="half">
<SettingsFormGrid>
<SettingsFormCell span="half">
<PrivateResourceSitesField
control={form.control}
orgId={orgId}
selectedSites={selectedSites}
onSelectedSitesChange={
setSelectedSites
}
/>
</SettingsFormCell>
</SettingsFormGrid>
</SettingsSectionForm>
</SettingsSectionBody>
</SettingsSection>
)}
{/* HTTP configuration */}
{mode === "http" && (
<SettingsSection>
@@ -119,7 +119,10 @@ function ProxyResourceHttpForm({
message: t("proxyErrorInvalidHeader")
}
),
headers: z
requestHeaders: z
.array(z.object({ name: z.string(), value: z.string() }))
.nullable(),
responseHeaders: z
.array(z.object({ name: z.string(), value: z.string() }))
.nullable()
});
@@ -131,19 +134,21 @@ function ProxyResourceHttpForm({
ssl: resource.ssl,
tlsServerName: resource.tlsServerName || "",
setHostHeader: resource.setHostHeader || "",
headers: resource.headers
requestHeaders: resource.requestHeaders,
responseHeaders: resource.responseHeaders
},
mode: "onChange"
});
const [, formAction, saveLoading] = useActionState(onSubmit, null);
const [headersValid, setHeadersValid] = useState(true);
const [requestHeadersValid, setRequestHeadersValid] = useState(true);
const [responseHeadersValid, setResponseHeadersValid] = useState(true);
async function onSubmit() {
const isValid = await form.trigger();
if (!isValid) return;
if (!headersValid) {
if (!requestHeadersValid || !responseHeadersValid) {
toast({
variant: "destructive",
title: t("settingsErrorUpdate"),
@@ -162,7 +167,8 @@ function ProxyResourceHttpForm({
ssl: data.ssl,
tlsServerName: data.tlsServerName || null,
setHostHeader: data.setHostHeader || null,
headers: data.headers || null
requestHeaders: data.requestHeaders || null,
responseHeaders: data.responseHeaders || null
}
)
.catch((err) => {
@@ -183,7 +189,8 @@ function ProxyResourceHttpForm({
ssl: data.ssl,
tlsServerName: data.tlsServerName || null,
setHostHeader: data.setHostHeader || null,
headers: data.headers || null
requestHeaders: data.requestHeaders || null,
responseHeaders: data.responseHeaders || null
});
toast({
@@ -324,11 +331,11 @@ function ProxyResourceHttpForm({
<SettingsFormCell span="full">
<FormField
control={form.control}
name="headers"
name="requestHeaders"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("customHeaders")}
{t("customRequestHeaders")}
</FormLabel>
<FormControl>
<HeadersInput
@@ -337,14 +344,46 @@ function ProxyResourceHttpForm({
field.onChange
}
onValidityChange={
setHeadersValid
setRequestHeadersValid
}
rows={4}
/>
</FormControl>
<FormDescription>
{t(
"customHeadersDescription"
"customRequestHeadersDescription"
)}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</SettingsFormCell>
<SettingsFormCell span="full">
<FormField
control={form.control}
name="responseHeaders"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("customResponseHeaders")}
</FormLabel>
<FormControl>
<HeadersInput
value={field.value}
onChange={
field.onChange
}
onValidityChange={
setResponseHeadersValid
}
rows={4}
/>
</FormControl>
<FormDescription>
{t(
"customResponseHeadersDescription"
)}
</FormDescription>
<FormMessage />
@@ -362,7 +401,11 @@ function ProxyResourceHttpForm({
<Button
type="submit"
loading={saveLoading}
disabled={saveLoading || !headersValid}
disabled={
saveLoading ||
!requestHeadersValid ||
!responseHeadersValid
}
form="http-settings-form"
>
{t("saveSettings")}
@@ -113,7 +113,7 @@ function ProxyResourceProtocolForm({
message: t("proxyErrorInvalidHeader")
}
),
headers: z
requestHeaders: z
.array(z.object({ name: z.string(), value: z.string() }))
.nullable(),
proxyProtocol: z.boolean().optional(),
@@ -124,7 +124,7 @@ function ProxyResourceProtocolForm({
resolver: zodResolver(proxySettingsSchema),
defaultValues: {
setHostHeader: resource.setHostHeader || "",
headers: resource.headers,
requestHeaders: resource.requestHeaders,
proxyProtocol: resource.proxyProtocol || false,
proxyProtocolVersion: resource.proxyProtocolVersion || 1
}
@@ -28,7 +28,7 @@ import {
import { BrowserGatewayTargetForm } from "@app/components/BrowserGatewayTargetForm";
import {
SitesSelector,
type Selectedsite
type SelectedSite
} from "@app/components/site-selector";
import { Button } from "@app/components/ui/button";
import {
@@ -253,7 +253,7 @@ export default function Page() {
"site" | "remote"
>("site");
const [nativeSelectedSite, setNativeSelectedSite] =
useState<Selectedsite | null>(null);
useState<SelectedSite | null>(null);
const [nativeSiteOpen, setNativeSiteOpen] = useState(false);
useEffect(() => {
@@ -1226,6 +1226,7 @@ export default function Page() {
</PopoverTrigger>
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
<SitesSelector
filterTypes={["newt"]}
orgId={
orgId as string
}
+204 -64
View File
@@ -1,7 +1,7 @@
"use client";
import { useState, useEffect } from "react";
import { LicenseKeyCache } from "@server/license/license";
import { LicenseKeyCache, LicenseKeyTier } from "@server/license/license";
import { createApiClient } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { toast } from "@app/hooks/useToast";
@@ -41,6 +41,7 @@ import {
SettingsSectionHeader,
SettingsSectionFooter
} from "@app/components/Settings";
import { Progress } from "@app/components/ui/progress";
import SettingsSectionTitle from "@app/components/SettingsSectionTitle";
import {
ArrowRight,
@@ -48,6 +49,7 @@ import {
ExternalLink,
Heart,
InfoIcon,
ShoppingCart,
TicketCheck
} from "lucide-react";
import Link from "next/link";
@@ -63,12 +65,24 @@ import { useTranslations } from "next-intl";
const ENTERPRISE_DOCS_URL =
"https://docs.pangolin.net/self-host/enterprise-edition";
const ENTERPRISE_PRICING_URL = "https://pangolin.net/pricing#Self-Hosted";
const LICENSE_PORTAL_URL =
"https://app.pangolin.net/auth/login?internal_redirect=/settings/license?generate";
function obfuscateLicenseKey(key: string): string {
if (key.length <= 8) return key;
const firstPart = key.substring(0, 4);
const lastPart = key.substring(key.length - 4);
return `${firstPart}••••••••••••••••••••${lastPart}`;
function getTierLabel(
tier: LicenseKeyTier | undefined,
t: (key: string) => string
): string {
switch (tier) {
case "enterprise":
return t("licenseTierEnterprise");
case "tier1":
return t("licenseTierTier1");
case "tier2":
return t("licenseTierTier2");
case "personal":
default:
return t("licenseTierPersonal");
}
}
export default function LicensePage() {
@@ -80,7 +94,6 @@ export default function LicensePage() {
useState<LicenseKeyCache | null>(null);
const { licenseStatus, updateLicenseStatus } = useLicenseStatusContext();
const [hostLicense, setHostLicense] = useState<string | null>(null);
const [isPurchaseModalOpen, setIsPurchaseModalOpen] = useState(false);
const [purchaseMode, setPurchaseMode] = useState<"license">("license");
@@ -128,12 +141,6 @@ export default function LicensePage() {
);
const keys = response.data.data;
setRows(keys);
const hostKey = keys.find((key) => key.type === "host");
if (hostKey) {
setHostLicense(hostKey.licenseKey);
} else {
setHostLicense(null);
}
} catch (e) {
toast({
title: t("licenseErrorKeyLoad"),
@@ -388,6 +395,33 @@ export default function LicensePage() {
</DismissableBanner>
)}
{licenseStatus?.isLicenseValid && rows.length > 0 && (
<DismissableBanner
storageKey="license-upgrade-banner-dismissed"
version={1}
title={t("licenseUpgradeBannerTitle")}
titleIcon={
<ShoppingCart className="w-5 h-5 text-primary" />
}
description={t("licenseUpgradeBannerDescription")}
>
<Link
href={LICENSE_PORTAL_URL}
target="_blank"
rel="noopener noreferrer"
>
<Button
variant="outline"
size="sm"
className="gap-2 hover:bg-primary/10 hover:border-primary/50 transition-colors"
>
{t("licenseUpgradeBannerButton")}
<ExternalLink className="w-4 h-4" />
</Button>
</Link>
</DismissableBanner>
)}
{/* <Alert variant="neutral" className="mb-6"> */}
{/* <InfoIcon className="h-4 w-4" /> */}
{/* <AlertTitle className="font-semibold"> */}
@@ -399,62 +433,168 @@ export default function LicensePage() {
{/* </Alert> */}
<SettingsContainer>
<SettingsSection>
<SettingsSectionHeader>
<SSTitle>{t("licenseHost")}</SSTitle>
<SettingsSectionDescription>
{t("licenseHostDescription")}
</SettingsSectionDescription>
</SettingsSectionHeader>
<div className="space-y-4">
<div className="flex items-center space-x-4">
{licenseStatus?.isLicenseValid ? (
<div className="space-y-2 text-green-500">
<div className="text-2xl flex items-center gap-2">
<Check />
{t("licensed") +
`${licenseStatus?.tier === "personal" ? ` (${t("personalUseOnly")})` : ""}`}
</div>
<SettingsSectionGrid cols={2}>
<SettingsSection>
<SettingsSectionHeader>
<SSTitle>{t("licenseUsage")}</SSTitle>
<SettingsSectionDescription>
{t("licenseUsageDescription")}
</SettingsSectionDescription>
</SettingsSectionHeader>
<div className="space-y-6">
<div className="space-y-2">
<div className="text-sm font-medium">
{t("licenseUsageSites")}
</div>
) : (
<div className="text-2xl">
{t("unlicensed")}
{t("licenseSitesUsed", {
count: licenseStatus?.usedSites || 0
})}
</div>
{licenseStatus?.maxSites ? (
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">
{t("licenseSitesUsedMax", {
usedSites:
licenseStatus.usedSites ||
0,
maxSites:
licenseStatus.maxSites
})}
</span>
<span className="text-muted-foreground">
{Math.round(
((licenseStatus.usedSites ||
0) /
licenseStatus.maxSites) *
100
)}
%
</span>
</div>
<Progress
value={
((licenseStatus.usedSites ||
0) /
licenseStatus.maxSites) *
100
}
className="h-5"
/>
</div>
) : (
<div className="text-sm text-muted-foreground">
{t("licenseNoSiteLimit")}
</div>
)}
</div>
<div className="space-y-2">
<div className="text-sm font-medium">
{t("licenseUsageUsers")}
</div>
<div className="text-2xl">
{t("licenseUsersUsed", {
count: licenseStatus?.usedUsers || 0
})}
</div>
{licenseStatus?.maxUsers ? (
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">
{t("licenseUsersUsedMax", {
usedUsers:
licenseStatus.usedUsers ||
0,
maxUsers:
licenseStatus.maxUsers
})}
</span>
<span className="text-muted-foreground">
{Math.round(
((licenseStatus.usedUsers ||
0) /
licenseStatus.maxUsers) *
100
)}
%
</span>
</div>
<Progress
value={
((licenseStatus.usedUsers ||
0) /
licenseStatus.maxUsers) *
100
}
className="h-5"
/>
</div>
) : (
<div className="text-sm text-muted-foreground">
{t("licenseNoUserLimit")}
</div>
)}
</div>
</div>
</SettingsSection>
<SettingsSection>
<SettingsSectionHeader>
<SSTitle>{t("licenseHost")}</SSTitle>
<SettingsSectionDescription>
{t("licenseHostDescription")}
</SettingsSectionDescription>
</SettingsSectionHeader>
<div className="space-y-4">
<div className="flex items-center space-x-4">
{licenseStatus?.isLicenseValid ? (
<div className="space-y-2 text-green-500">
<div className="text-2xl flex items-center gap-2">
<Check />
{t("licensed") +
`${licenseStatus?.tier === "personal" ? ` (${t("personalUseOnly")})` : ""}`}
</div>
</div>
) : (
<div className="text-2xl">
{t("unlicensed")}
</div>
)}
</div>
<div className="space-y-2">
<div className="text-sm font-medium">
{t("licenseTierLabel")}
</div>
<div className="text-lg">
{getTierLabel(licenseStatus?.tier, t)}
</div>
{rows.length > 1 && (
<div className="text-sm text-muted-foreground">
{t("licenseMultipleKeysDescription")}
</div>
)}
</div>
{licenseStatus?.hostId && (
<div className="space-y-2">
<div className="text-sm font-medium">
{t("hostId")}
</div>
<CopyTextBox text={licenseStatus.hostId} />
</div>
)}
</div>
{licenseStatus?.hostId && (
<div className="space-y-2">
<div className="text-sm font-medium">
{t("hostId")}
</div>
<CopyTextBox text={licenseStatus.hostId} />
</div>
)}
{hostLicense && (
<div className="space-y-2">
<div className="text-sm font-medium">
{t("licenseKey")}
</div>
<CopyTextBox
text={hostLicense}
displayText={obfuscateLicenseKey(
hostLicense
)}
/>
</div>
)}
</div>
<SettingsSectionFooter>
<Button
variant="outline"
onClick={recheck}
disabled={isRecheckingLicense}
loading={isRecheckingLicense}
>
{t("licenseReckeckAll")}
</Button>
</SettingsSectionFooter>
</SettingsSection>
<SettingsSectionFooter>
<Button
variant="outline"
onClick={recheck}
disabled={isRecheckingLicense}
loading={isRecheckingLicense}
>
{t("licenseReckeckAll")}
</Button>
</SettingsSectionFooter>
</SettingsSection>
</SettingsSectionGrid>
<LicenseKeysDataTable
licenseKeys={rows}
onDelete={(key) => {
+22 -11
View File
@@ -122,11 +122,20 @@ export default async function ResourceAuthPage(props: {
if (searchParams.redirect) {
try {
const redirectTarget = new URL(searchParams.redirect);
const serverResourceHost = new URL(authInfo.url).host;
const redirectHost = new URL(searchParams.redirect).host;
const redirectPort = new URL(searchParams.redirect).port;
const redirectHost = redirectTarget.host;
const redirectPort = redirectTarget.port;
const serverResourceHostWithPort = `${serverResourceHost}:${redirectPort}`;
// URL parses a host out of any scheme that uses "//", so a target
// like javascript://resource-host/... matches the comparisons
// below. The target is later assigned to window.location, so only
// http(s) is accepted here.
const isHttpTarget =
redirectTarget.protocol === "http:" ||
redirectTarget.protocol === "https:";
const wildcardMatchesRedirect = (
wildcardDomain: string,
host: string
@@ -136,14 +145,16 @@ export default async function ResourceAuthPage(props: {
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)
if (
isHttpTarget &&
(serverResourceHost === redirectHost ||
serverResourceHostWithPort === redirectHost ||
(authInfo.wildcard &&
authInfo.fullDomain &&
wildcardMatchesRedirect(
authInfo.fullDomain,
redirectHost
)))
) {
redirectUrl = searchParams.redirect;
}
@@ -283,7 +294,7 @@ export default async function ResourceAuthPage(props: {
loginIdps = idpsRes.data.data.idps.map((idp) => ({
idpId: idp.idpId,
name: idp.name,
variant: idp.type
variant: idp.variant ?? idp.type
})) as LoginFormIDP[];
}
+10 -14
View File
@@ -10,7 +10,7 @@ import {
MultiSitesSelector,
formatMultiSitesSelectorLabel
} from "./multi-site-selector";
import { SitesSelector, type Selectedsite } from "./site-selector";
import { SitesSelector, type SelectedSite } from "./site-selector";
import { Button } from "./ui/button";
import {
FormControl,
@@ -42,8 +42,7 @@ type SingleSiteFormProps<T extends FieldValues> = BaseProps<T> & {
};
export type BrowserGatewayTargetFormProps<T extends FieldValues = FieldValues> =
| MultiSiteFormProps<T>
| SingleSiteFormProps<T>;
MultiSiteFormProps<T> | SingleSiteFormProps<T>;
export function BrowserGatewayTargetForm<T extends FieldValues>(
props: BrowserGatewayTargetFormProps<T>
@@ -90,7 +89,7 @@ export function BrowserGatewayTargetForm<T extends FieldValues>(
const showMultiSiteDisclaimer =
props.multiSite === true &&
((watchedSites as Selectedsite[] | undefined)?.length ?? 0) > 1;
((watchedSites as SelectedSite[] | undefined)?.length ?? 0) > 1;
return (
<div className="space-y-2">
@@ -112,7 +111,7 @@ export function BrowserGatewayTargetForm<T extends FieldValues>(
"aria-invalid:border-destructive aria-invalid:ring-destructive/20",
props.multiSite === true
? (
field.value as Selectedsite[]
field.value as SelectedSite[]
)?.length === 0 &&
"text-muted-foreground"
: !field.value &&
@@ -122,12 +121,12 @@ export function BrowserGatewayTargetForm<T extends FieldValues>(
<span className="truncate">
{props.multiSite === true
? formatMultiSitesSelectorLabel(
(field.value as Selectedsite[]) ??
(field.value as SelectedSite[]) ??
[],
t
)
: ((
field.value as Selectedsite | null
field.value as SelectedSite | null
)?.name ??
t("siteSelect"))}
</span>
@@ -140,7 +139,7 @@ export function BrowserGatewayTargetForm<T extends FieldValues>(
<MultiSitesSelector
orgId={props.orgId}
selectedSites={
(field.value as Selectedsite[]) ??
(field.value as SelectedSite[]) ??
[]
}
onSelectionChange={field.onChange}
@@ -150,7 +149,7 @@ export function BrowserGatewayTargetForm<T extends FieldValues>(
<SitesSelector
orgId={props.orgId}
selectedSite={
field.value as Selectedsite | null
field.value as SelectedSite | null
}
onSelectSite={(site) => {
field.onChange(site);
@@ -179,8 +178,7 @@ export function BrowserGatewayTargetForm<T extends FieldValues>(
onChange={field.onChange}
value={
(watchedDestination as
| string
| undefined) ?? ""
string | undefined) ?? ""
}
/>
</FormControl>
@@ -205,9 +203,7 @@ export function BrowserGatewayTargetForm<T extends FieldValues>(
onChange={field.onChange}
value={
(watchedDestinationPort as
| string
| number
| undefined) ?? ""
string | number | undefined) ?? ""
}
/>
</FormControl>
+7 -9
View File
@@ -46,7 +46,7 @@ import {
PopoverTrigger
} from "@/components/ui/popover";
import { SitesSelector } from "@app/components/site-selector";
import type { Selectedsite } 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";
@@ -144,7 +144,7 @@ export function HealthCheckCredenza(props: HealthCheckCredenzaProps) {
const t = useTranslations();
const api = createApiClient(useEnvContext());
const [loading, setLoading] = useState(false);
const [selectedSite, setSelectedSite] = useState<Selectedsite | null>(null);
const [selectedSite, setSelectedSite] = useState<SelectedSite | null>(null);
const healthCheckSchema = z
.object({
@@ -183,11 +183,9 @@ export function HealthCheckCredenza(props: HealthCheckCredenzaProps) {
{ message: t("healthCheckPortInvalid") }
),
hcFollowRedirects: z.boolean(),
hcHostname: z
.string()
.refine((val) => !/\s/.test(val), {
message: t("healthCheckHostnameInvalid")
}),
hcHostname: z.string().refine((val) => !/\s/.test(val), {
message: t("healthCheckHostnameInvalid")
}),
hcMode: z.string(),
hcUnhealthyInterval: z.int().positive().min(5),
hcTlsServerName: z.string(),
@@ -1355,7 +1353,7 @@ export function HealthCheckCredenza(props: HealthCheckCredenzaProps) {
<FormItem>
<FormLabel>
{t(
"customHeaders"
"customRequestHeaders"
)}
</FormLabel>
<FormControl>
@@ -1379,7 +1377,7 @@ export function HealthCheckCredenza(props: HealthCheckCredenzaProps) {
</FormControl>
<FormDescription>
{t(
"customHeadersDescription"
"customRequestHeadersDescription"
)}
</FormDescription>
<FormMessage />
+2 -2
View File
@@ -733,7 +733,7 @@ export function HealthCheckFormFields({
render={({ field }) => (
<FormItem>
<FormLabel>
{t("customHeaders")}
{t("customRequestHeaders")}
</FormLabel>
<FormControl>
<HeadersInput
@@ -750,7 +750,7 @@ export function HealthCheckFormFields({
</FormControl>
<FormDescription>
{t(
"customHeadersDescription"
"customRequestHeadersDescription"
)}
</FormDescription>
<FormMessage />
+4 -4
View File
@@ -28,7 +28,7 @@ import { Switch } from "@app/components/ui/switch";
import { toast } from "@app/hooks/useToast";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { createApiClient, formatAxiosError } from "@app/lib/api";
import { Selectedsite, SitesSelector } from "@app/components/site-selector";
import { SelectedSite, SitesSelector } from "@app/components/site-selector";
import {
ResourceSelector,
SelectedResource
@@ -59,7 +59,7 @@ type StandaloneHealthChecksTableProps = {
healthChecks: HealthCheckRow[];
rowCount: number;
pagination: PaginationState;
initialFilterSite?: Selectedsite | null;
initialFilterSite?: SelectedSite | null;
initialFilterResource?: SelectedResource | null;
};
@@ -117,7 +117,7 @@ export default function HealthChecksTable({
const siteIdQ = searchParams.get("siteId");
const siteIdNum = siteIdQ ? parseInt(siteIdQ, 10) : NaN;
const selectedSite: Selectedsite | null = useMemo(() => {
const selectedSite: SelectedSite | null = useMemo(() => {
if (!siteIdQ || !Number.isInteger(siteIdNum) || siteIdNum <= 0) {
return null;
}
@@ -227,7 +227,7 @@ export default function HealthChecksTable({
setResourceFilterOpen(false);
};
const onPickSite = (site: Selectedsite) => {
const onPickSite = (site: SelectedSite) => {
handleFilterChange("siteId", String(site.siteId));
setSiteFilterOpen(false);
};
+49
View File
@@ -112,6 +112,54 @@ export function LicenseKeysDataTable({
}
}
},
{
accessorKey: "quantity",
friendlyName: t("users"),
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() =>
column.toggleSorting(column.getIsSorted() === "asc")
}
>
{t("users")}
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
cell: ({ row }) => {
const quantity = row.original.quantity;
if (quantity === undefined) {
return "-";
}
return quantity < 0 ? t("licenseUnlimited") : quantity;
}
},
{
accessorKey: "quantity_2",
friendlyName: t("sites"),
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() =>
column.toggleSorting(column.getIsSorted() === "asc")
}
>
{t("sites")}
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
cell: ({ row }) => {
const quantity = row.original.quantity_2;
if (quantity === undefined) {
return "-";
}
return quantity < 0 ? t("licenseUnlimited") : quantity;
}
},
{
accessorKey: "terminateAt",
friendlyName: t("licenseTableValidUntil"),
@@ -158,6 +206,7 @@ export function LicenseKeysDataTable({
title={t("licenseKeys")}
searchPlaceholder={t("licenseKeySearch")}
searchColumn="licenseKey"
defaultSort={{ id: "terminateAt", desc: false }}
onAdd={onCreate}
addButtonText={t("licenseKeyAdd")}
enableColumnVisibility={true}
+23 -15
View File
@@ -93,7 +93,8 @@ export function PrivateResourceInfoSections({
cidr: t("editInternalResourceDialogModeCidr"),
http: t("editInternalResourceDialogModeHttp"),
ssh: t("editInternalResourceDialogModeSsh"),
inference: t("editInternalResourceDialogModeInference")
inference: t("editInternalResourceDialogModeInference"),
gateway: t("editInternalResourceDialogModeGateway")
};
const destination = formatSiteResourceDestinationDisplay({
@@ -107,15 +108,19 @@ export function PrivateResourceInfoSections({
tcpPortRangeString: siteResource.tcpPortRangeString ?? "*",
udpPortRangeString: siteResource.udpPortRangeString ?? "*"
});
const showAccess = siteResource.mode !== "gateway";
const showAlias =
siteResource.mode !== "cidr" &&
siteResource.mode !== "http" &&
siteResource.mode !== "inference";
siteResource.mode !== "inference" &&
siteResource.mode !== "gateway";
const showDestination =
!(
siteResource.mode === "ssh" &&
siteResource.authDaemonMode === "native"
) && siteResource.mode !== "inference";
) &&
siteResource.mode !== "inference" &&
siteResource.mode !== "gateway";
const showCertificate = !!(
(siteResource.mode === "http" || siteResource.mode === "inference") &&
siteResource.ssl &&
@@ -128,7 +133,8 @@ export function PrivateResourceInfoSections({
siteResource.mode !== "inference";
const numSections =
2 +
1 +
(showAccess ? 1 : 0) +
(showDestination ? 1 : 0) +
(showAlias ? 1 : 0) +
(showCertificate ? 1 : 0) +
@@ -143,17 +149,19 @@ export function PrivateResourceInfoSections({
</InfoSectionContent>
</InfoSection>
<InfoSection>
<InfoSectionTitle>{t("access")}</InfoSectionTitle>
<InfoSectionContent>
<AccessMethodContent
accessDisplay={access.accessDisplay}
accessCopyValue={access.accessCopyValue}
accessUrl={access.accessUrl}
className={accessClassName}
/>
</InfoSectionContent>
</InfoSection>
{showAccess ? (
<InfoSection>
<InfoSectionTitle>{t("access")}</InfoSectionTitle>
<InfoSectionContent>
<AccessMethodContent
accessDisplay={access.accessDisplay}
accessCopyValue={access.accessCopyValue}
accessUrl={access.accessUrl}
className={accessClassName}
/>
</InfoSectionContent>
</InfoSection>
) : null}
{showDestination ? (
<InfoSection>
+3 -3
View File
@@ -5,7 +5,7 @@ import {
formatMultiSitesSelectorLabel
} from "@app/components/multi-site-selector";
import { SitesSelector } from "@app/components/site-selector";
import type { Selectedsite } from "@app/components/site-selector";
import type { SelectedSite } from "@app/components/site-selector";
import { Button } from "@app/components/ui/button";
import {
FormControl,
@@ -28,8 +28,8 @@ import { PrivateResourceMultiSiteRoutingHelp } from "@app/components/PrivateReso
type PrivateResourceSitesFieldProps<T extends FieldValues> = {
control: Control<T>;
orgId: string;
selectedSites: Selectedsite[];
onSelectedSitesChange: (sites: Selectedsite[]) => void;
selectedSites: SelectedSite[];
onSelectedSitesChange: (sites: SelectedSite[]) => void;
siteIdsFieldName?: FieldPath<T>;
singleSite?: boolean;
};
+4 -4
View File
@@ -25,7 +25,7 @@ import { tierMatrix } from "@server/lib/billing/tierMatrix";
import { useTranslations } from "next-intl";
import { useState, type ReactNode } from "react";
import type { Control, UseFormSetValue, UseFormWatch } from "react-hook-form";
import type { Selectedsite } from "@app/components/site-selector";
import type { SelectedSite } from "@app/components/site-selector";
type PrivateResourceSshFieldsProps = {
control: Control<any>;
@@ -33,8 +33,8 @@ type PrivateResourceSshFieldsProps = {
watch: UseFormWatch<any>;
orgId?: string;
disabled?: boolean;
selectedSites: Selectedsite[];
onSelectedSitesChange: (sites: Selectedsite[]) => void;
selectedSites: SelectedSite[];
onSelectedSitesChange: (sites: SelectedSite[]) => void;
labelPrefix?: "create" | "edit";
showSshSettings?: boolean;
layout?: "default" | "wizard";
@@ -101,7 +101,7 @@ export function PrivateResourceSshFields({
onSelectedSitesChange(first);
setValue(
"siteIds",
first.map((s: Selectedsite) => s.siteId),
first.map((s: SelectedSite) => s.siteId),
{ shouldValidate: true }
);
}
+8 -3
View File
@@ -7,7 +7,7 @@ import {
ResourceSitesStatusCell,
type ResourceSiteRow
} from "@app/components/ResourceSitesStatusCell";
import { Selectedsite, SitesSelector } from "@app/components/site-selector";
import { SelectedSite, SitesSelector } from "@app/components/site-selector";
import { Badge } from "@app/components/ui/badge";
import { Button } from "@app/components/ui/button";
import { ExtendedColumnDef } from "@app/components/ui/data-table";
@@ -376,7 +376,8 @@ export default function PrivateResourcesTable({
cidr: t("editInternalResourceDialogModeCidr"),
http: t("editInternalResourceDialogModeHttp"),
ssh: t("editInternalResourceDialogModeSsh"),
inference: t("editInternalResourceDialogModeInference")
inference: t("editInternalResourceDialogModeInference"),
gateway: t("editInternalResourceDialogModeGateway")
};
return <span>{modeLabels[resourceRow.mode]}</span>;
}
@@ -392,7 +393,11 @@ export default function PrivateResourcesTable({
cell: ({ row }) => {
const resourceRow = row.original;
const display = formatDestinationDisplay(resourceRow);
if (resourceRow.destination) {
if (
resourceRow.destination &&
resourceRow.mode !== "gateway"
) {
// don't show the gateway resource destination which is 0.0.0.0/0 to not confuse people
return (
<CopyToClipboard
text={display}
+2 -2
View File
@@ -7,7 +7,7 @@ import {
ResourceSitesStatusCell,
type ResourceSiteRow
} from "@app/components/ResourceSitesStatusCell";
import { Selectedsite } from "@app/components/site-selector";
import { SelectedSite } from "@app/components/site-selector";
import { Button } from "@app/components/ui/button";
import { ExtendedColumnDef } from "@app/components/ui/data-table";
import {
@@ -105,7 +105,7 @@ type ProxyResourcesTableProps = {
orgId: string;
pagination: PaginationState;
rowCount: number;
initialFilterSite?: Selectedsite | null;
initialFilterSite?: SelectedSite | null;
/** Certificates prefetched on the server, keyed by full domain. */
initialCertificates?: GetBatchedCertificateResponse;
};
+2 -1
View File
@@ -71,7 +71,8 @@ function PrivateResourceMeta({ row }: { row: SiteResourceRow }) {
cidr: t("editInternalResourceDialogModeCidr"),
http: t("editInternalResourceDialogModeHttp"),
ssh: t("editInternalResourceDialogModeSsh"),
inference: t("editInternalResourceDialogModeInference")
inference: t("editInternalResourceDialogModeInference"),
gateway: t("editInternalResourceDialogModeGateway")
};
const dest = formatSiteResourceDestinationDisplay({
mode: row.mode,
+2 -2
View File
@@ -3,7 +3,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
import { cn } from "@app/lib/cn";
import { dataTableFilterPopoverContentClassName } from "@app/lib/dataTableFilterPopover";
import { CheckIcon, Funnel } from "lucide-react";
import { SiteOnlineStatus, type Selectedsite } from "./site-selector";
import { SiteOnlineStatus, type SelectedSite } from "./site-selector";
import { Button } from "./ui/button";
import { useTranslations } from "next-intl";
import { Badge } from "./ui/badge";
@@ -62,7 +62,7 @@ export function SitesColumnFilterButton({
// always include the selected site in the list of sites shown
const sitesShown = useMemo(() => {
const allSites: Array<Selectedsite> = [...sites];
const allSites: Array<SelectedSite> = [...sites];
if (
debouncedQuery.trim().length === 0 &&
selectedSite &&
+8 -3
View File
@@ -1,6 +1,5 @@
"use client";
import React from "react";
import { Button } from "@app/components/ui/button";
import { ClockIcon, ArrowRight } from "lucide-react";
import { useTranslations } from "next-intl";
@@ -8,9 +7,13 @@ import DismissableBanner from "./DismissableBanner";
type TrialBillingBannerProps = {
onUpgrade: () => void;
tierName: string;
};
export const TrialBillingBanner = ({ onUpgrade }: TrialBillingBannerProps) => {
export const TrialBillingBanner = ({
onUpgrade,
tierName
}: TrialBillingBannerProps) => {
const t = useTranslations();
return (
@@ -19,7 +22,9 @@ export const TrialBillingBanner = ({ onUpgrade }: TrialBillingBannerProps) => {
version={1}
title={t("billingTrialBannerTitle")}
titleIcon={<ClockIcon className="w-5 h-5 text-primary" />}
description={t("billingTrialBannerDescription")}
description={t("billingTrialBannerDescription", {
tier: tierName
})}
dismissable={false}
>
<Button
+5 -5
View File
@@ -12,12 +12,12 @@ import {
import { Checkbox } from "./ui/checkbox";
import { useTranslations } from "next-intl";
import { useDebounce } from "use-debounce";
import { SiteOnlineStatus, type Selectedsite } from "./site-selector";
import { SiteOnlineStatus, type SelectedSite } from "./site-selector";
export type MultiSitesSelectorProps = {
orgId: string;
selectedSites: Selectedsite[];
onSelectionChange: (sites: Selectedsite[]) => void;
selectedSites: SelectedSite[];
onSelectionChange: (sites: SelectedSite[]) => void;
filterTypes?: string[];
scope?: "org" | "launcher";
onClear?: () => void;
@@ -25,7 +25,7 @@ export type MultiSitesSelectorProps = {
};
export function formatMultiSitesSelectorLabel(
selectedSites: Selectedsite[],
selectedSites: SelectedSite[],
t: (key: string, values?: { count: number }) => string
): string {
if (selectedSites.length === 0) {
@@ -91,7 +91,7 @@ export function MultiSitesSelector({
[selectedSites]
);
const toggleSite = (site: Selectedsite) => {
const toggleSite = (site: SelectedSite) => {
if (selectedIds.has(site.siteId)) {
onSelectionChange(
selectedSites.filter((s) => s.siteId !== site.siteId)
+80 -2
View File
@@ -20,7 +20,7 @@ import {
FaWindows
} from "react-icons/fa";
import { Download, ExternalLink } from "lucide-react";
import { SiKubernetes, SiNixos } from "react-icons/si";
import { SiAlpinelinux, SiKubernetes, SiNixos } from "react-icons/si";
import { useEnvContext } from "@app/hooks/useEnvContext";
export type CommandItem =
@@ -30,6 +30,7 @@ export type CommandItem =
const PLATFORMS = [
"linux",
"alpine",
"macos",
"docker",
"kubernetes",
@@ -65,7 +66,8 @@ export function NewtSiteInstallCommands({
);
const showSiteConfiguration = platform !== "advantech";
const supportsSshOption = platform === "linux" || platform === "nixos";
const supportsSshOption =
platform === "linux" || platform === "nixos" || platform === "alpine";
const acceptClientsFlag = !acceptClients ? " --disable-clients" : "";
const acceptClientsEnv = !acceptClients
@@ -168,6 +170,76 @@ sudo systemctl enable --now pangolin-site`
}
]
},
alpine: {
Run: [
{
title: t("install"),
command: `curl -fsSL https://static.pangolin.net/get-cli.sh | bash`
},
{
title: t("run"),
command: `${runAsRootPrefix}pangolin up site --id ${id} --secret ${secret} --endpoint ${endpoint}${acceptClientsFlag}${disableSshFlag}`
}
],
"Manual OpenRC Service": [
{
title: t("install"),
command: `curl -fsSL https://static.pangolin.net/get-cli.sh | bash`
},
{
title: t("envFile"),
command: `sudo tee /etc/conf.d/pangolin-site > /dev/null << 'EOF'
export SITE_ID=${id}
export SITE_SECRET=${secret}
export PANGOLIN_ENDPOINT=${endpoint}${
!acceptClients
? `
export DISABLE_CLIENTS=true`
: ""
}${
!allowPangolinSsh
? `
export DISABLE_SSH=true`
: ""
}
EOF
sudo chmod 600 /etc/conf.d/pangolin-site`
},
{
title: t("serviceFile"),
command: `sudo tee /etc/init.d/pangolin-site > /dev/null << 'EOF'
#!/sbin/openrc-run
name="pangolin-site"
description="Pangolin Site"
command="/usr/local/bin/pangolin"
command_args="up site"
command_background="yes"
supervisor="supervise-daemon"
pidfile="/run/pangolin-site.pid"
output_log="/var/log/pangolin-site.log"
error_log="/var/log/pangolin-site.err"
depend() {
need net
after firewall
}
EOF
sudo chmod +x /etc/init.d/pangolin-site`
},
{
title: t("enableAndStart"),
command: `sudo rc-update add pangolin-site default
sudo rc-service pangolin-site start`
},
{
title: t("check"),
command: `sudo rc-service pangolin-site status`
}
]
},
macos: {
Run: [
{
@@ -478,6 +550,8 @@ function getPlatformIcon(platformName: Platform) {
return <FaWindows className="h-4 w-4 mr-2" />;
case "linux":
return <FaLinux className="h-4 w-4 mr-2" />;
case "alpine":
return <SiAlpinelinux className="h-4 w-4 mr-2" />;
case "macos":
return <FaApple className="h-4 w-4 mr-2" />;
case "docker":
@@ -501,6 +575,8 @@ function getPlatformName(platformName: Platform) {
return "Windows";
case "linux":
return "Linux";
case "alpine":
return "Alpine Linux";
case "macos":
return "macOS";
case "docker":
@@ -522,6 +598,8 @@ function getArchitectures(platform: Platform) {
switch (platform) {
case "linux":
return ["Run", "Systemd Service", "Manual Systemd Service"];
case "alpine":
return ["Run", "Manual OpenRC Service"];
case "macos":
return ["Run", "Service"];
case "windows":
@@ -23,13 +23,13 @@ import { useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { ChevronsUpDown, Funnel } from "lucide-react";
import { useMemo, useState } from "react";
import type { Selectedsite } from "@app/components/site-selector";
import type { SelectedSite } from "@app/components/site-selector";
type LauncherFilterPopoverProps = {
orgId: string;
selectedSites: Selectedsite[];
selectedSites: SelectedSite[];
selectedLabels: SelectedLabel[];
onSitesChange: (sites: Selectedsite[]) => void;
onSitesChange: (sites: SelectedSite[]) => void;
onLabelsChange: (labels: SelectedLabel[]) => void;
};
@@ -58,7 +58,7 @@ export function LauncherFilterPopover({
})
);
const resolvedSelectedSites: Selectedsite[] = useMemo(
const resolvedSelectedSites: SelectedSite[] = useMemo(
() =>
selectedSites.map((selected) => {
const found = sites.find(
@@ -63,7 +63,7 @@ import {
useTransition
} from "react";
import { useDebouncedCallback } from "use-debounce";
import type { Selectedsite } from "@app/components/site-selector";
import type { SelectedSite } from "@app/components/site-selector";
import type { SelectedLabel } from "@app/components/labels-selector";
import { useMediaQuery } from "@app/hooks/useMediaQuery";
import { cn } from "@app/lib/cn";
@@ -256,7 +256,7 @@ export default function ResourceLauncher({
(Boolean(defaultViewOverrides.personal) ||
(isAdmin && Boolean(defaultViewOverrides.orgWide)));
const selectedSites: Selectedsite[] = useMemo(
const selectedSites: SelectedSite[] = useMemo(
() =>
config.siteIds.map((siteId) => ({
siteId,
@@ -37,6 +37,7 @@ import { cn } from "@app/lib/cn";
import { MAJOR_ASNS } from "@server/db/asns";
import { COUNTRIES } from "@server/db/countries";
import { REGIONS, getRegionNameById } from "@server/db/regions";
import { HTTP_METHODS, parseHttpMethodList } from "@server/lib/validators";
import {
ColumnDef,
flexRender,
@@ -53,17 +54,22 @@ import {
GripVertical,
LockIcon
} from "lucide-react";
import { useCommandState } from "cmdk";
import { useTranslations } from "next-intl";
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ComponentProps,
type DragEvent,
type ReactNode
} from "react";
import {
validatePolicyRulePriority,
validatePolicyRuleValue
validatePolicyRuleValue,
type PolicyRuleMatchType
} from "./policy-access-rule-validation";
import {
buildDisplayPrioritiesForResourceOverlay,
@@ -112,6 +118,112 @@ function getColumnClassName(columnId: string) {
return "";
}
// cmdk keeps the list's scroll offset when the search text changes, so a
// filtered list can be left scrolled past its (few) matches and look empty.
// Jump back to the top whenever the search changes.
function ResettingCommandList(props: ComponentProps<typeof CommandList>) {
const search = useCommandState((state) => state.search);
const listRef = useRef<HTMLDivElement>(null);
useEffect(() => {
listRef.current?.scrollTo({ top: 0 });
}, [search]);
return <CommandList ref={listRef} {...props} />;
}
// Plain case-insensitive substring match on the country name or code, with
// prefix matches ranked first. cmdk's default fuzzy scorer matches unrelated
// countries (e.g. "Russia") and buries the exact one.
function filterCountry(value: string, search: string, keywords?: string[]) {
const query = search.trim().toLowerCase();
if (!query) {
return 1;
}
const name = value.toLowerCase();
const code = keywords?.[0]?.toLowerCase() ?? "";
if (name.startsWith(query) || code === query) {
return 1;
}
return name.includes(query) ? 0.5 : 0;
}
// A METHOD rule stores its methods as a comma-separated list in rule.value,
// e.g. "POST,PUT". Only the common methods are offered here; a value set
// through a blueprint or the API may contain other methods (the WebDAV verbs,
// for instance), so those are kept and shown rather than dropped on edit.
function RuleMethodSelect({
value,
disabled,
placeholder,
onChange
}: {
value: string;
disabled: boolean;
placeholder: string;
onChange: (value: string) => void;
}) {
const selected = parseHttpMethodList(value);
const knownMethods: readonly string[] = HTTP_METHODS;
const options = [
...knownMethods,
...selected.filter((method) => !knownMethods.includes(method))
];
function toggle(method: string) {
const next = selected.includes(method)
? selected.filter((m) => m !== method)
: [...selected, method];
// keep a stable order so the stored value does not churn on every edit
onChange(options.filter((m) => next.includes(m)).join(","));
}
return (
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
disabled={disabled}
className="w-full min-w-0 justify-between"
>
<span className="truncate">
{selected.length > 0
? selected.join(", ")
: placeholder}
</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="min-w-50 p-0">
<Command>
<CommandList>
<CommandGroup>
{options.map((method) => (
<CommandItem
key={method}
value={method}
onSelect={() => toggle(method)}
>
<Check
className={`mr-2 h-4 w-4 ${
selected.includes(method)
? "opacity-100"
: "opacity-0"
}`}
/>
{method}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
export function PolicyAccessRulesTable({
rules,
onRulesChange,
@@ -233,7 +345,8 @@ export function PolicyAccessRulesTable({
COUNTRY: t("country"),
COUNTRY_IS_NOT: t("countryIsNot"),
ASN: "ASN",
REGION: t("region")
REGION: t("region"),
METHOD: t("method")
}),
[t]
);
@@ -438,16 +551,7 @@ export function PolicyAccessRulesTable({
<Select
defaultValue={row.original.match}
disabled={readonly || isRuleLocked(row.original)}
onValueChange={(
value:
| "CIDR"
| "IP"
| "PATH"
| "COUNTRY"
| "COUNTRY_IS_NOT"
| "ASN"
| "REGION"
) =>
onValueChange={(value: PolicyRuleMatchType) =>
updateRule(row.original.ruleId, {
match: value,
value:
@@ -458,7 +562,9 @@ export function PolicyAccessRulesTable({
? "AS15169"
: value === "REGION"
? "021"
: row.original.value
: value === "METHOD"
? "GET"
: row.original.value
})
}
>
@@ -473,6 +579,9 @@ export function PolicyAccessRulesTable({
<SelectItem value="CIDR">
{RuleMatch.CIDR}
</SelectItem>
<SelectItem value="METHOD">
{RuleMatch.METHOD}
</SelectItem>
{isMaxmindAvailable && (
<>
<SelectItem value="COUNTRY">
@@ -543,11 +652,11 @@ export function PolicyAccessRulesTable({
</Button>
</PopoverTrigger>
<PopoverContent className="min-w-50 p-0">
<Command>
<Command filter={filterCountry}>
<CommandInput
placeholder={t("searchCountries")}
/>
<CommandList>
<ResettingCommandList>
<CommandEmpty>
{t("noCountryFound")}
</CommandEmpty>
@@ -556,6 +665,7 @@ export function PolicyAccessRulesTable({
<CommandItem
key={country.code}
value={country.name}
keywords={[country.code]}
onSelect={() =>
updateRule(
row.original.ruleId,
@@ -580,7 +690,7 @@ export function PolicyAccessRulesTable({
</CommandItem>
))}
</CommandGroup>
</CommandList>
</ResettingCommandList>
</Command>
</PopoverContent>
</Popover>
@@ -613,7 +723,7 @@ export function PolicyAccessRulesTable({
<PopoverContent className="min-w-50 p-0">
<Command>
<CommandInput placeholder="Search ASNs or enter custom..." />
<CommandList>
<ResettingCommandList>
<CommandEmpty>
No ASN found. Enter a custom ASN
below.
@@ -641,7 +751,7 @@ export function PolicyAccessRulesTable({
</CommandItem>
))}
</CommandGroup>
</CommandList>
</ResettingCommandList>
</Command>
<div className="border-t p-2">
<Input
@@ -702,7 +812,7 @@ export function PolicyAccessRulesTable({
<CommandInput
placeholder={t("searchRegions")}
/>
<CommandList>
<ResettingCommandList>
<CommandEmpty>
{t("noRegionFound")}
</CommandEmpty>
@@ -775,10 +885,19 @@ export function PolicyAccessRulesTable({
)}
</CommandGroup>
))}
</CommandList>
</ResettingCommandList>
</Command>
</PopoverContent>
</Popover>
) : row.original.match === "METHOD" ? (
<RuleMethodSelect
value={row.original.value}
disabled={readonly || isRuleLocked(row.original)}
placeholder={t("rulesSelectMethods")}
onChange={(value) =>
updateRule(row.original.ruleId, { value })
}
/>
) : (
<Input
defaultValue={row.original.value}
@@ -2,6 +2,7 @@ import { COUNTRIES } from "@server/db/countries";
import { isValidRegionId } from "@server/db/regions";
import {
isValidCIDR,
isValidHttpMethodList,
isValidIP,
isValidUrlGlobPattern
} from "@server/lib/validators";
@@ -19,7 +20,8 @@ export const POLICY_RULE_MATCH_TYPES = [
"COUNTRY",
"COUNTRY_IS_NOT",
"ASN",
"REGION"
"REGION",
"METHOD"
] as const;
export type PolicyRuleMatchType = (typeof POLICY_RULE_MATCH_TYPES)[number];
@@ -84,6 +86,10 @@ export function createPolicyRuleValueSchema(t: TranslateFn, match: string) {
(value) => COUNTRIES.some((country) => country.code === value),
{ message: t("rulesErrorInvalidCountryDescription") }
);
case "METHOD":
return required.refine(isValidHttpMethodList, {
message: t("rulesErrorInvalidMethodDescription")
});
case "ASN":
return required.refine(
(value) => {

Some files were not shown because too many files have changed in this diff Show More