diff --git a/.github/workflows/linting.yml b/.github/workflows/linting.yml index 4bd0d2a90..451d2eb45 100644 --- a/.github/workflows/linting.yml +++ b/.github/workflows/linting.yml @@ -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: diff --git a/messages/bg-BG.json b/messages/bg-BG.json index 790bdec85..63358e2e3 100644 --- a/messages/bg-BG.json +++ b/messages/bg-BG.json @@ -110,7 +110,7 @@ "siteInstallNewt": "Инсталирайте Newt", "siteInstallNewtDescription": "Пуснете Newt на вашата система", "siteInstallKubernetesDocsDescription": "За повече и актуална информация относно инсталацията на Kubernetes, вижте docs.pangolin.net/manage/sites/install-kubernetes.", - "siteInstallAdvantechDocsDescription": "За инструкции за инсталиране на Advantech модем, вижте docs.pangolin.net/manage/sites/install-advantech.", + "siteInstallAdvantechDocsDescription": "За инструкции за инсталиране на Advantech модем, вижте docs.pangolin.net/manage/sites/install-newt#advantech-router-app.", "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": "Проверка на здравето е запазена", diff --git a/messages/cs-CZ.json b/messages/cs-CZ.json index 7e660dd72..22f34ceb9 100644 --- a/messages/cs-CZ.json +++ b/messages/cs-CZ.json @@ -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 docs.pangolin.net/manage/sites/install-kubernetes.", - "siteInstallAdvantechDocsDescription": "Pro pokyny k instalaci modemu Advantech navštivte docs.pangolin.net/manage/sites/install-advantech.", + "siteInstallAdvantechDocsDescription": "Pro pokyny k instalaci modemu Advantech navštivte docs.pangolin.net/manage/sites/install-newt#advantech-router-app.", "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", diff --git a/messages/da-DK.json b/messages/da-DK.json index 9d12079b2..866853040 100644 --- a/messages/da-DK.json +++ b/messages/da-DK.json @@ -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 docs.pangolin.net/manage/sites/install-kubernetes.", - "siteInstallAdvantechDocsDescription": "For installationsvejledning til Advantech-modemmer, se docs.pangolin.net/manage/sites/install-advantech.", + "siteInstallAdvantechDocsDescription": "For installationsvejledning til Advantech-modemmer, se docs.pangolin.net/manage/sites/install-newt#advantech-router-app.", "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", diff --git a/messages/de-DE.json b/messages/de-DE.json index f26be1670..cf7c2ae6b 100644 --- a/messages/de-DE.json +++ b/messages/de-DE.json @@ -110,7 +110,7 @@ "siteInstallNewt": "Newt installieren", "siteInstallNewtDescription": "Installiere Newt auf deinem System.", "siteInstallKubernetesDocsDescription": "Für aktuelle Installationsinformationen zu Kubernetes, siehe docs.pangolin.net/manage/sites/install-kubernetes.", - "siteInstallAdvantechDocsDescription": "Für Installationsanweisungen für Advantech-Modems siehe docs.pangolin.net/manage/sites/install-advantech.", + "siteInstallAdvantechDocsDescription": "Für Installationsanweisungen für Advantech-Modems siehe docs.pangolin.net/manage/sites/install-newt#advantech-router-app.", "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", diff --git a/messages/en-US.json b/messages/en-US.json index 003595b7b..cfa151c90 100644 --- a/messages/en-US.json +++ b/messages/en-US.json @@ -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 docs.pangolin.net/manage/sites/install-kubernetes.", - "siteInstallAdvantechDocsDescription": "For Advantech modem installation instructions, see docs.pangolin.net/manage/sites/install-advantech.", + "siteInstallAdvantechDocsDescription": "For Advantech modem installation instructions, see docs.pangolin.net/manage/sites/install-newt#advantech-router-app.", "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 {name}? 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" } diff --git a/messages/es-ES.json b/messages/es-ES.json index 06b5b19a9..0407ad5bd 100644 --- a/messages/es-ES.json +++ b/messages/es-ES.json @@ -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 docs.pangolin.net/manage/sites/install-kubernetes.", - "siteInstallAdvantechDocsDescription": "Para instrucciones de instalación del módem Advantech, consulta docs.pangolin.net/manage/sites/install-advantech.", + "siteInstallAdvantechDocsDescription": "Para instrucciones de instalación del módem Advantech, consulta docs.pangolin.net/manage/sites/install-newt#advantech-router-app.", "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", diff --git a/messages/fr-FR.json b/messages/fr-FR.json index a2b7e933d..20ce80a58 100644 --- a/messages/fr-FR.json +++ b/messages/fr-FR.json @@ -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 docs.pangolin.net/manage/sites/install-kubernetes.", - "siteInstallAdvantechDocsDescription": "Pour les instructions d'installation du modem Advantech, voir docs.pangolin.net/manage/sites/install-advantech.", + "siteInstallAdvantechDocsDescription": "Pour les instructions d'installation du modem Advantech, voir docs.pangolin.net/manage/sites/install-newt#advantech-router-app.", "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", diff --git a/messages/it-IT.json b/messages/it-IT.json index 46c60a440..990552f71 100644 --- a/messages/it-IT.json +++ b/messages/it-IT.json @@ -110,7 +110,7 @@ "siteInstallNewt": "Installa Newt", "siteInstallNewtDescription": "Esegui Newt sul tuo sistema", "siteInstallKubernetesDocsDescription": "Per ulteriori informazioni aggiornate sull'installazione di Kubernetes, consulta docs.pangolin.net/manage/sites/install-kubernetes.", - "siteInstallAdvantechDocsDescription": "Per le istruzioni sull'installazione del modem Advantech, consulta docs.pangolin.net/manage/sites/install-advantech.", + "siteInstallAdvantechDocsDescription": "Per le istruzioni sull'installazione del modem Advantech, consulta docs.pangolin.net/manage/sites/install-newt#advantech-router-app.", "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", diff --git a/messages/ko-KR.json b/messages/ko-KR.json index 34fb31369..4981759ad 100644 --- a/messages/ko-KR.json +++ b/messages/ko-KR.json @@ -110,7 +110,7 @@ "siteInstallNewt": "Newt 설치", "siteInstallNewtDescription": "시스템에서 Newt 실행하기", "siteInstallKubernetesDocsDescription": "더 많은 정보와 최신의 쿠버네티스 설치 정보를 보려면 docs.pangolin.net/manage/sites/install-kubernetes를 참조하세요.", - "siteInstallAdvantechDocsDescription": "Advantech 모뎀 설치 지침은 docs.pangolin.net/manage/sites/install-advantech을 참조하세요.", + "siteInstallAdvantechDocsDescription": "Advantech 모뎀 설치 지침은 docs.pangolin.net/manage/sites/install-newt#advantech-router-app을 참조하세요.", "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": "상태 확인이 저장되었습니다.", diff --git a/messages/nb-NO.json b/messages/nb-NO.json index 0d042e03d..d3ed06b97 100644 --- a/messages/nb-NO.json +++ b/messages/nb-NO.json @@ -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 docs.pangolin.net/manage/sites/install-kubernetes.", - "siteInstallAdvantechDocsDescription": "For installasjonsinstruksjoner for Advantech-modem, se docs.pangolin.net/manage/sites/install-advantech.", + "siteInstallAdvantechDocsDescription": "For installasjonsinstruksjoner for Advantech-modem, se docs.pangolin.net/manage/sites/install-newt#advantech-router-app.", "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", diff --git a/messages/nl-NL.json b/messages/nl-NL.json index 9a92edddf..2e4b51096 100644 --- a/messages/nl-NL.json +++ b/messages/nl-NL.json @@ -110,7 +110,7 @@ "siteInstallNewt": "Installeer Newt", "siteInstallNewtDescription": "Laat Newt draaien op uw systeem", "siteInstallKubernetesDocsDescription": "Voor meer informatie over de installatie van Kubernetes, zie docs.pangolin.net/manage/sites/install-kubernetes.", - "siteInstallAdvantechDocsDescription": "Voor instructies voor de installatie van Advantech modems, zie docs.pangolin.net/manage/sites/install-advantech.", + "siteInstallAdvantechDocsDescription": "Voor instructies voor de installatie van Advantech modems, zie docs.pangolin.net/manage/sites/install-newt#advantech-router-app.", "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", diff --git a/messages/pl-PL.json b/messages/pl-PL.json index 4d291b0fe..4ada01cc9 100644 --- a/messages/pl-PL.json +++ b/messages/pl-PL.json @@ -110,7 +110,7 @@ "siteInstallNewt": "Zainstaluj Newt", "siteInstallNewtDescription": "Uruchom Newt w swoim systemie", "siteInstallKubernetesDocsDescription": "Aby uzyskać więcej aktualnych informacji o instalacji Kubernetes, zobacz docs.pangolin.net/manage/sites/install-kubernetes.", - "siteInstallAdvantechDocsDescription": "Aby uzyskać instrukcje dotyczące instalacji modemu Advantech, zobacz: docs.pangolin.net/manage/sites/install-advantech.", + "siteInstallAdvantechDocsDescription": "Aby uzyskać instrukcje dotyczące instalacji modemu Advantech, zobacz: docs.pangolin.net/manage/sites/install-newt#advantech-router-app.", "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", diff --git a/messages/pt-PT.json b/messages/pt-PT.json index c7cb6dac7..701c9a33e 100644 --- a/messages/pt-PT.json +++ b/messages/pt-PT.json @@ -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 docs.pangolin.net/manage/sites/install-kubernetes.", - "siteInstallAdvantechDocsDescription": "Para instruções de instalação do modem da Advantech, veja docs.pangolin.net/manage/sites/install-advantech.", + "siteInstallAdvantechDocsDescription": "Para instruções de instalação do modem da Advantech, veja docs.pangolin.net/manage/sites/install-newt#advantech-router-app.", "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", diff --git a/messages/ru-RU.json b/messages/ru-RU.json index 484b789eb..423778ccf 100644 --- a/messages/ru-RU.json +++ b/messages/ru-RU.json @@ -110,7 +110,7 @@ "siteInstallNewt": "Установить Newt", "siteInstallNewtDescription": "Запустите Newt в вашей системе", "siteInstallKubernetesDocsDescription": "Для получения дополнительной информации об установке Kubernetes, см. docs.pangolin.net/manage/sites/install-kubernetes.", - "siteInstallAdvantechDocsDescription": "Для инструкций по установке модема Advantech, см. docs.pangolin.net/manage/sites/install-advantech.", + "siteInstallAdvantechDocsDescription": "Для инструкций по установке модема Advantech, см. docs.pangolin.net/manage/sites/install-newt#advantech-router-app.", "WgConfiguration": "Конфигурация WireGuard", "WgConfigurationDescription": "Используйте следующую конфигурацию для подключения к сети", "operatingSystem": "Операционная система", @@ -2826,8 +2826,10 @@ "retryAttempts": "Количество попыток повторного запроса", "expectedResponseCodes": "Ожидаемые коды ответов", "expectedResponseCodesDescription": "HTTP-код состояния, указывающий на здоровое состояние. Если оставить пустым, 200-300 считается здоровым.", - "customHeaders": "Пользовательские заголовки", - "customHeadersDescription": "Заголовки новой строки, разделённые: название заголовка: значение", + "customRequestHeaders": "Пользовательские заголовки запроса", + "customRequestHeadersDescription": "Заголовки запроса, отправляемые целевым серверам. По одному в строке: Имя-Заголовка: значение", + "customResponseHeaders": "Пользовательские заголовки ответа", + "customResponseHeadersDescription": "Заголовки ответа, возвращаемые клиенту. По одному в строке: Имя-Заголовка: значение", "headersValidationError": "Заголовки должны быть в формате: Название заголовка: значение.", "saveHealthCheck": "Сохранить проверку здоровья", "healthCheckSaved": "Проверка здоровья сохранена", diff --git a/messages/tr-TR.json b/messages/tr-TR.json index 970fd6d28..8f18bbf6c 100644 --- a/messages/tr-TR.json +++ b/messages/tr-TR.json @@ -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 docs.pangolin.net/manage/sites/install-kubernetes adresini inceleyin.", - "siteInstallAdvantechDocsDescription": "Advantech modem kurulum talimatları için docs.pangolin.net/manage/sites/install-advantech adresini inceleyin.", + "siteInstallAdvantechDocsDescription": "Advantech modem kurulum talimatları için docs.pangolin.net/manage/sites/install-newt#advantech-router-app 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", diff --git a/messages/zh-CN.json b/messages/zh-CN.json index 804efda2b..2c7161ca9 100644 --- a/messages/zh-CN.json +++ b/messages/zh-CN.json @@ -110,7 +110,7 @@ "siteInstallNewt": "安装 Newt", "siteInstallNewtDescription": "在您的系统中运行 Newt", "siteInstallKubernetesDocsDescription": "有关最新的 Kubernetes 安装信息,请参阅docs.pangolin.net/manage/sites/install-kubernetes。", - "siteInstallAdvantechDocsDescription": "有关 Advantech 调制解调器安装说明,请参阅docs.pangolin.net/manage/sites/install-advantech。", + "siteInstallAdvantechDocsDescription": "有关 Advantech 调制解调器安装说明,请参阅docs.pangolin.net/manage/sites/install-newt#advantech-router-app。", "WgConfiguration": "WireGuard 配置", "WgConfigurationDescription": "使用以下配置连接到网络", "operatingSystem": "操作系统", @@ -2826,8 +2826,10 @@ "retryAttempts": "重试次数", "expectedResponseCodes": "期望响应代码", "expectedResponseCodesDescription": "HTTP 状态码表示健康状态。如留空,200-300 被视为健康。", - "customHeaders": "自定义标题", - "customHeadersDescription": "头部新行分隔:头部名称:值", + "customRequestHeaders": "自定义请求标头", + "customRequestHeadersDescription": "转发到目标的请求标头。每行一个:标头名称:值", + "customResponseHeaders": "自定义响应标头", + "customResponseHeadersDescription": "返回给客户端的响应标头。每行一个:标头名称:值", "headersValidationError": "头部必须是格式:头部名称:值。", "saveHealthCheck": "保存健康检查", "healthCheckSaved": "健康检查已保存", diff --git a/messages/zh-TW.json b/messages/zh-TW.json index 9e32a32f6..730e4dc66 100644 --- a/messages/zh-TW.json +++ b/messages/zh-TW.json @@ -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 安裝資訊,請參閱docs.pangolin.net/manage/sites/install-kubernetes。", - "siteInstallAdvantechDocsDescription": "有關 Advantech 數據機安裝說明,請參閱docs.pangolin.net/manage/sites/install-advantech。", + "siteInstallAdvantechDocsDescription": "有關 Advantech 數據機安裝說明,請參閱docs.pangolin.net/manage/sites/install-newt#advantech-router-app。", "siteRestartTitle": "重新啟動站台", "siteRestartDescription": "重新啟動此站台的WireGuard隧道。此操作將暫時中斷連線。", "siteRestartBody": "如果站台隧道無法正常工作,並且您希望在不重新啟動主機的情況下強制重新連線,請使用此選項。", diff --git a/server/db/ios_models.json b/server/db/ios_models.json index 99fcbea17..43dfe5687 100644 --- a/server/db/ios_models.json +++ b/server/db/ios_models.json @@ -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" -} \ No newline at end of file +} diff --git a/server/db/mac_models.json b/server/db/mac_models.json index 6d9b837d5..bb9621995 100644 --- a/server/db/mac_models.json +++ b/server/db/mac_models.json @@ -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" -} +} \ No newline at end of file diff --git a/server/db/pg/schema/schema.ts b/server/db/pg/schema/schema.ts index 744e88b98..a4210ab8e 100644 --- a/server/db/pg/schema/schema.ts +++ b/server/db/pg/schema/schema.ts @@ -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() diff --git a/server/db/sqlite/schema/schema.ts b/server/db/sqlite/schema/schema.ts index e30bc678e..a2c2339aa 100644 --- a/server/db/sqlite/schema/schema.ts +++ b/server/db/sqlite/schema/schema.ts @@ -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() diff --git a/server/emails/templates/AlertNotification.tsx b/server/emails/templates/AlertNotification.tsx index c81cf60da..dc6d60131 100644 --- a/server/emails/templates/AlertNotification.tsx +++ b/server/emails/templates/AlertNotification.tsx @@ -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) => { {isTestAlert && ( - 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. )} diff --git a/server/lib/billing/index.ts b/server/lib/billing/index.ts index 54c9ee2e0..1bc354f7e 100644 --- a/server/lib/billing/index.ts +++ b/server/lib/billing/index.ts @@ -3,3 +3,4 @@ export * from "./features"; export * from "./limitsService"; export * from "./getOrgTierData"; export * from "./createCustomer"; +export * from "./linkEmailOrg"; diff --git a/server/lib/billing/linkEmailOrg.ts b/server/lib/billing/linkEmailOrg.ts new file mode 100644 index 000000000..df67d2ed8 --- /dev/null +++ b/server/lib/billing/linkEmailOrg.ts @@ -0,0 +1,6 @@ +export async function linkEmailOrg( + orgId: string, + email: string | null | undefined +): Promise { + return; +} diff --git a/server/lib/blueprints/privateResources.ts b/server/lib/blueprints/privateResources.ts index 085fed836..55904492b 100644 --- a/server/lib/blueprints/privateResources.ts +++ b/server/lib/blueprints/privateResources.ts @@ -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, diff --git a/server/lib/blueprints/publicResources.ts b/server/lib/blueprints/publicResources.ts index 4bd42ed0b..719671d97 100644 --- a/server/lib/blueprints/publicResources.ts +++ b/server/lib/blueprints/publicResources.ts @@ -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}`); + } } } diff --git a/server/lib/blueprints/resourcePolicies.ts b/server/lib/blueprints/resourcePolicies.ts index d8c744cdb..babb1c10a 100644 --- a/server/lib/blueprints/resourcePolicies.ts +++ b/server/lib/blueprints/resourcePolicies.ts @@ -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( diff --git a/server/lib/blueprints/types.ts b/server/lib/blueprints/types.ts index 238ef49c4..a057eb745 100644 --- a/server/lib/blueprints/types.ts +++ b/server/lib/blueprints/types.ts @@ -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 diff --git a/server/lib/deleteSiteAssociatedResources.ts b/server/lib/deleteSiteAssociatedResources.ts index c0e520846..1ee2d0cf3 100644 --- a/server/lib/deleteSiteAssociatedResources.ts +++ b/server/lib/deleteSiteAssociatedResources.ts @@ -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; diff --git a/server/lib/ip.ts b/server/lib/ip.ts index 518bb36db..c3567b3ef 100644 --- a/server/lib/ip.ts +++ b/server/lib/ip.ts @@ -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!, diff --git a/server/lib/readConfigFile.ts b/server/lib/readConfigFile.ts index 9f433054d..0d8786f89 100644 --- a/server/lib/readConfigFile.ts +++ b/server/lib/readConfigFile.ts @@ -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(), diff --git a/server/lib/rebuildClientAssociations.ts b/server/lib/rebuildClientAssociations.ts index 045ca3927..02b84c993 100644 --- a/server/lib/rebuildClientAssociations.ts +++ b/server/lib/rebuildClientAssociations.ts @@ -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)) diff --git a/server/lib/traefik/getTraefikConfig.ts b/server/lib/traefik/getTraefikConfig.ts index ae8554597..47f665794 100644 --- a/server/lib/traefik/getTraefikConfig.ts +++ b/server/lib/traefik/getTraefikConfig.ts @@ -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 ); diff --git a/server/lib/traefik/headersMiddleware.ts b/server/lib/traefik/headersMiddleware.ts index 84f34dff4..20c775e23 100644 --- a/server/lib/traefik/headersMiddleware.ts +++ b/server/lib/traefik/headersMiddleware.ts @@ -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 + }) } }; } diff --git a/server/lib/validators.test.ts b/server/lib/validators.test.ts index 5ce95f45c..c17181c6a 100644 --- a/server/lib/validators.test.ts +++ b/server/lib/validators.test.ts @@ -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!"); } diff --git a/server/lib/validators.ts b/server/lib/validators.ts index 872ced221..d5bf5d2cc 100644 --- a/server/lib/validators.ts +++ b/server/lib/validators.ts @@ -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) || diff --git a/server/private/lib/billing/index.ts b/server/private/lib/billing/index.ts index 4d52668c0..0223b8aca 100644 --- a/server/private/lib/billing/index.ts +++ b/server/private/lib/billing/index.ts @@ -13,3 +13,4 @@ export * from "./getOrgTierData"; export * from "./createCustomer"; +export * from "./linkEmailOrg"; diff --git a/server/private/lib/billing/linkEmailOrg.ts b/server/private/lib/billing/linkEmailOrg.ts new file mode 100644 index 000000000..c14485a3d --- /dev/null +++ b/server/private/lib/billing/linkEmailOrg.ts @@ -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 { + 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 + ); + } +} diff --git a/server/private/lib/dns/server.ts b/server/private/lib/dns/server.ts index 10c46c358..4198f3d2e 100644 --- a/server/private/lib/dns/server.ts +++ b/server/private/lib/dns/server.ts @@ -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 { 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 []; } diff --git a/server/private/lib/readConfigFile.ts b/server/private/lib/readConfigFile.ts index db6999724..a78a16d3b 100644 --- a/server/private/lib/readConfigFile.ts +++ b/server/private/lib/readConfigFile.ts @@ -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), diff --git a/server/private/lib/traefik/getTraefikConfig.ts b/server/private/lib/traefik/getTraefikConfig.ts index 70a42b42f..a98368376 100644 --- a/server/private/lib/traefik/getTraefikConfig.ts +++ b/server/private/lib/traefik/getTraefikConfig.ts @@ -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 ); diff --git a/server/private/license/license.ts b/server/private/license/license.ts index 61ea23b48..16a62c042 100644 --- a/server/private/license/license.ts +++ b/server/private/license/license.ts @@ -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; } diff --git a/server/routers/badger/verifySession.ts b/server/routers/badger/verifySession.ts index 486feb2b7..4b6818d0e 100644 --- a/server/routers/badger/verifySession.ts +++ b/server/routers/badger/verifySession.ts @@ -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 | 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 | 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 | undefined ): string | undefined { diff --git a/server/routers/gerbil/updateHolePunch.ts b/server/routers/gerbil/updateHolePunch.ts index 54906e240..e6f6fbd95 100644 --- a/server/routers/gerbil/updateHolePunch.ts +++ b/server/routers/gerbil/updateHolePunch.ts @@ -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` ); diff --git a/server/routers/newt/buildConfiguration.ts b/server/routers/newt/buildConfiguration.ts index e1782fd40..6dece5dfa 100644 --- a/server/routers/newt/buildConfiguration.ts +++ b/server/routers/newt/buildConfiguration.ts @@ -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 diff --git a/server/routers/newt/error.ts b/server/routers/newt/error.ts new file mode 100644 index 000000000..d2ab8937c --- /dev/null +++ b/server/routers/newt/error.ts @@ -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 + } + }); +} diff --git a/server/routers/newt/handleNewtRegisterMessage.ts b/server/routers/newt/handleNewtRegisterMessage.ts index 7adc74a1b..4d90aa0aa 100644 --- a/server/routers/newt/handleNewtRegisterMessage.ts +++ b/server/routers/newt/handleNewtRegisterMessage.ts @@ -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], diff --git a/server/routers/newt/peers.ts b/server/routers/newt/peers.ts index bd11f03d0..cb69d7480 100644 --- a/server/routers/newt/peers.ts +++ b/server/routers/newt/peers.ts @@ -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, diff --git a/server/routers/newt/targets.ts b/server/routers/newt/targets.ts index 44aa34637..0dfac34c8 100644 --- a/server/routers/newt/targets.ts +++ b/server/routers/newt/targets.ts @@ -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) { diff --git a/server/routers/olm/batchUtils.ts b/server/routers/olm/batchUtils.ts new file mode 100644 index 000000000..681008e35 --- /dev/null +++ b/server/routers/olm/batchUtils.ts @@ -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> { + 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(); + 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 + }; +} diff --git a/server/routers/olm/buildConfiguration.ts b/server/routers/olm/buildConfiguration.ts index 6db0fa291..bd82e43ad 100644 --- a/server/routers/olm/buildConfiguration.ts +++ b/server/routers/olm/buildConfiguration.ts @@ -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) }); } diff --git a/server/routers/olm/error.ts b/server/routers/olm/error.ts index d9058a3f6..b0fd90993 100644 --- a/server/routers/olm/error.ts +++ b/server/routers/olm/error.ts @@ -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; diff --git a/server/routers/olm/gateway.ts b/server/routers/olm/gateway.ts new file mode 100644 index 000000000..d6a421c3e --- /dev/null +++ b/server/routers/olm/gateway.ts @@ -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 +): Promise { + 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 { + 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 { + await sendGatewayMessageToClients(clientIds, "olm/wg/gateway/disable", { + siteResourceId + }); +} diff --git a/server/routers/olm/getOlmToken.ts b/server/routers/olm/getOlmToken.ts index f7fdb81a8..c7c0c127b 100644 --- a/server/routers/olm/getOlmToken.ts +++ b/server/routers/olm/getOlmToken.ts @@ -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) diff --git a/server/routers/olm/handleOlmLocalMessage.ts b/server/routers/olm/handleOlmLocalMessage.ts index 83ef8cbf1..ca80fea06 100644 --- a/server/routers/olm/handleOlmLocalMessage.ts +++ b/server/routers/olm/handleOlmLocalMessage.ts @@ -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 diff --git a/server/routers/olm/handleOlmRegisterMessage.ts b/server/routers/olm/handleOlmRegisterMessage.ts index 693920950..f583729ef 100644 --- a/server/routers/olm/handleOlmRegisterMessage.ts +++ b/server/routers/olm/handleOlmRegisterMessage.ts @@ -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 diff --git a/server/routers/olm/handleOlmRelayMessage.ts b/server/routers/olm/handleOlmRelayMessage.ts index 406ed7bbb..1cd27912b 100644 --- a/server/routers/olm/handleOlmRelayMessage.ts +++ b/server/routers/olm/handleOlmRelayMessage.ts @@ -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, diff --git a/server/routers/olm/handleOlmUnLocalMessage.ts b/server/routers/olm/handleOlmUnLocalMessage.ts index 55d312815..f98aaf436 100644 --- a/server/routers/olm/handleOlmUnLocalMessage.ts +++ b/server/routers/olm/handleOlmUnLocalMessage.ts @@ -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 diff --git a/server/routers/olm/handleOlmUnRelayMessage.ts b/server/routers/olm/handleOlmUnRelayMessage.ts index 3f73a5834..a6e89852e 100644 --- a/server/routers/olm/handleOlmUnRelayMessage.ts +++ b/server/routers/olm/handleOlmUnRelayMessage.ts @@ -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, diff --git a/server/routers/olm/sync.ts b/server/routers/olm/sync.ts index 19d759769..5a681fef7 100644 --- a/server/routers/olm/sync.ts +++ b/server/routers/olm/sync.ts @@ -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 diff --git a/server/routers/org/createOrg.ts b/server/routers/org/createOrg.ts index a4efc991d..6abc589d6 100644 --- a/server/routers/org/createOrg.ts +++ b/server/routers/org/createOrg.ts @@ -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) { diff --git a/server/routers/resource/getResource.ts b/server/routers/resource/getResource.ts index b1f4108b3..90b949a33 100644 --- a/server/routers/resource/getResource.ts +++ b/server/routers/resource/getResource.ts @@ -53,9 +53,10 @@ async function queryInlinePolicy(resourcePolicyId: number) { export type GetResourceResponse = Omit< NonNullable>>, - "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(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, diff --git a/server/routers/resource/updateResource.ts b/server/routers/resource/updateResource.ts index 5716f3738..22ef89115 100644 --- a/server/routers/resource/updateResource.ts +++ b/server/routers/resource/updateResource.ts @@ -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(); diff --git a/server/routers/siteResource/createSiteResource.ts b/server/routers/siteResource/createSiteResource.ts index 4c3593f4c..ad978d530 100644 --- a/server/routers/siteResource/createSiteResource.ts +++ b/server/routers/siteResource/createSiteResource.ts @@ -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, diff --git a/server/routers/siteResource/updateSiteResource.ts b/server/routers/siteResource/updateSiteResource.ts index d5662eb16..aaae8a1e1 100644 --- a/server/routers/siteResource/updateSiteResource.ts +++ b/server/routers/siteResource/updateSiteResource.ts @@ -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, diff --git a/server/routers/traefik/traefikConfigProvider.ts b/server/routers/traefik/traefikConfigProvider.ts index 02e05f5e0..9643aa0b1 100644 --- a/server/routers/traefik/traefikConfigProvider.ts +++ b/server/routers/traefik/traefikConfigProvider.ts @@ -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, diff --git a/server/setup/migrationsPg.ts b/server/setup/migrationsPg.ts index c4eda0a0f..d65e09cfa 100644 --- a/server/setup/migrationsPg.ts +++ b/server/setup/migrationsPg.ts @@ -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; diff --git a/server/setup/migrationsSqlite.ts b/server/setup/migrationsSqlite.ts index eb2846610..b47e7989c 100644 --- a/server/setup/migrationsSqlite.ts +++ b/server/setup/migrationsSqlite.ts @@ -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; diff --git a/server/setup/scriptsPg/1.24.0.ts b/server/setup/scriptsPg/1.24.0.ts new file mode 100644 index 000000000..887c2651a --- /dev/null +++ b/server/setup/scriptsPg/1.24.0.ts @@ -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`); +} diff --git a/server/setup/scriptsSqlite/1.24.0.ts b/server/setup/scriptsSqlite/1.24.0.ts new file mode 100644 index 000000000..d2ce5d35e --- /dev/null +++ b/server/setup/scriptsSqlite/1.24.0.ts @@ -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`); +} diff --git a/src/app/[orgId]/settings/(private)/billing/page.tsx b/src/app/[orgId]/settings/(private)/billing/page.tsx index 7869374cd..d60f300d5 100644 --- a/src/app/[orgId]/settings/(private)/billing/page.tsx +++ b/src/app/[orgId]/settings/(private)/billing/page.tsx @@ -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 && ( { - const currentPlan = planOptions.find( - (p) => p.id === currentPlanId - ); if (currentPlan?.tierType) { handleStartSubscription(currentPlan.tierType); } diff --git a/src/app/[orgId]/settings/resources/private/[niceId]/gateway/page.tsx b/src/app/[orgId]/settings/resources/private/[niceId]/gateway/page.tsx new file mode 100644 index 000000000..1743ba3f8 --- /dev/null +++ b/src/app/[orgId]/settings/resources/private/[niceId]/gateway/page.tsx @@ -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; + + const form = useForm({ + 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 ( + + + + + {t("gatewaySettings")} + + + {t( + "editInternalResourceDialogDestinationGatewayDescription" + )} + + + + + +
+ + + + + + +
+ +
+
+ + + + +
+
+ ); +} diff --git a/src/app/[orgId]/settings/resources/private/[niceId]/layout.tsx b/src/app/[orgId]/settings/resources/private/[niceId]/layout.tsx index 735848d01..31fe7cfae 100644 --- a/src/app/[orgId]/settings/resources/private/[niceId]/layout.tsx +++ b/src/app/[orgId]/settings/resources/private/[niceId]/layout.tsx @@ -53,7 +53,8 @@ export default async function PrivateResourceLayout( | "cidrSettings" | "httpSettings" | "sshSettings" - | "inferenceSettings"; + | "inferenceSettings" + | "gatewaySettings"; const navItems = [ { diff --git a/src/app/[orgId]/settings/resources/private/[niceId]/ssh/page.tsx b/src/app/[orgId]/settings/resources/private/[niceId]/ssh/page.tsx index ba60e41e6..fbdecfa5c 100644 --- a/src/app/[orgId]/settings/resources/private/[niceId]/ssh/page.tsx +++ b/src/app/[orgId]/settings/resources/private/[niceId]/ssh/page.tsx @@ -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 } ); } diff --git a/src/app/[orgId]/settings/resources/private/create/page.tsx b/src/app/[orgId]/settings/resources/private/create/page.tsx index b895ff5a3..27ac06e3f 100644 --- a/src/app/[orgId]/settings/resources/private/create/page.tsx +++ b/src/app/[orgId]/settings/resources/private/create/page.tsx @@ -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([]); + const [selectedSites, setSelectedSites] = useState([]); 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() { )} + {/* Gateway destination */} + {mode === "gateway" && ( + + + + {t("gatewaySettings")} + + + {t( + "editInternalResourceDialogDestinationGatewayDescription" + )} + + + + + + + + + + + + + )} + {/* HTTP configuration */} {mode === "http" && ( diff --git a/src/app/[orgId]/settings/resources/public/[niceId]/http/page.tsx b/src/app/[orgId]/settings/resources/public/[niceId]/http/page.tsx index a38176210..40330e51b 100644 --- a/src/app/[orgId]/settings/resources/public/[niceId]/http/page.tsx +++ b/src/app/[orgId]/settings/resources/public/[niceId]/http/page.tsx @@ -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({ ( - {t("customHeaders")} + {t("customRequestHeaders")} {t( - "customHeadersDescription" + "customRequestHeadersDescription" + )} + + + + )} + /> + + + + ( + + + {t("customResponseHeaders")} + + + + + + {t( + "customResponseHeadersDescription" )} @@ -362,7 +401,11 @@ function ProxyResourceHttpForm({ + + + )} + {/* */} {/* */} {/* */} @@ -399,62 +433,168 @@ export default function LicensePage() { {/* */} - - - {t("licenseHost")} - - {t("licenseHostDescription")} - - -
-
- {licenseStatus?.isLicenseValid ? ( -
-
- - {t("licensed") + - `${licenseStatus?.tier === "personal" ? ` (${t("personalUseOnly")})` : ""}`} -
+ + + + {t("licenseUsage")} + + {t("licenseUsageDescription")} + + +
+
+
+ {t("licenseUsageSites")}
- ) : (
- {t("unlicensed")} + {t("licenseSitesUsed", { + count: licenseStatus?.usedSites || 0 + })} +
+ {licenseStatus?.maxSites ? ( +
+
+ + {t("licenseSitesUsedMax", { + usedSites: + licenseStatus.usedSites || + 0, + maxSites: + licenseStatus.maxSites + })} + + + {Math.round( + ((licenseStatus.usedSites || + 0) / + licenseStatus.maxSites) * + 100 + )} + % + +
+ +
+ ) : ( +
+ {t("licenseNoSiteLimit")} +
+ )} +
+
+
+ {t("licenseUsageUsers")} +
+
+ {t("licenseUsersUsed", { + count: licenseStatus?.usedUsers || 0 + })} +
+ {licenseStatus?.maxUsers ? ( +
+
+ + {t("licenseUsersUsedMax", { + usedUsers: + licenseStatus.usedUsers || + 0, + maxUsers: + licenseStatus.maxUsers + })} + + + {Math.round( + ((licenseStatus.usedUsers || + 0) / + licenseStatus.maxUsers) * + 100 + )} + % + +
+ +
+ ) : ( +
+ {t("licenseNoUserLimit")} +
+ )} +
+
+
+ + + {t("licenseHost")} + + {t("licenseHostDescription")} + + +
+
+ {licenseStatus?.isLicenseValid ? ( +
+
+ + {t("licensed") + + `${licenseStatus?.tier === "personal" ? ` (${t("personalUseOnly")})` : ""}`} +
+
+ ) : ( +
+ {t("unlicensed")} +
+ )} +
+
+
+ {t("licenseTierLabel")} +
+
+ {getTierLabel(licenseStatus?.tier, t)} +
+ {rows.length > 1 && ( +
+ {t("licenseMultipleKeysDescription")} +
+ )} +
+ {licenseStatus?.hostId && ( +
+
+ {t("hostId")} +
+
)}
- {licenseStatus?.hostId && ( -
-
- {t("hostId")} -
- -
- )} - {hostLicense && ( -
-
- {t("licenseKey")} -
- -
- )} -
- - - - + + + + + { diff --git a/src/app/auth/resource/[resourceGuid]/page.tsx b/src/app/auth/resource/[resourceGuid]/page.tsx index 318d63517..7f2ad6a27 100644 --- a/src/app/auth/resource/[resourceGuid]/page.tsx +++ b/src/app/auth/resource/[resourceGuid]/page.tsx @@ -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[]; } diff --git a/src/components/BrowserGatewayTargetForm.tsx b/src/components/BrowserGatewayTargetForm.tsx index 5b45f90d1..8410e9e9f 100644 --- a/src/components/BrowserGatewayTargetForm.tsx +++ b/src/components/BrowserGatewayTargetForm.tsx @@ -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 = BaseProps & { }; export type BrowserGatewayTargetFormProps = - | MultiSiteFormProps - | SingleSiteFormProps; + MultiSiteFormProps | SingleSiteFormProps; export function BrowserGatewayTargetForm( props: BrowserGatewayTargetFormProps @@ -90,7 +89,7 @@ export function BrowserGatewayTargetForm( const showMultiSiteDisclaimer = props.multiSite === true && - ((watchedSites as Selectedsite[] | undefined)?.length ?? 0) > 1; + ((watchedSites as SelectedSite[] | undefined)?.length ?? 0) > 1; return (
@@ -112,7 +111,7 @@ export function BrowserGatewayTargetForm( "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( {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"))} @@ -140,7 +139,7 @@ export function BrowserGatewayTargetForm( ( { field.onChange(site); @@ -179,8 +178,7 @@ export function BrowserGatewayTargetForm( onChange={field.onChange} value={ (watchedDestination as - | string - | undefined) ?? "" + string | undefined) ?? "" } /> @@ -205,9 +203,7 @@ export function BrowserGatewayTargetForm( onChange={field.onChange} value={ (watchedDestinationPort as - | string - | number - | undefined) ?? "" + string | number | undefined) ?? "" } /> diff --git a/src/components/HealthCheckCredenza.tsx b/src/components/HealthCheckCredenza.tsx index 43e39b9ae..aed14e58f 100644 --- a/src/components/HealthCheckCredenza.tsx +++ b/src/components/HealthCheckCredenza.tsx @@ -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(null); + const [selectedSite, setSelectedSite] = useState(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) { {t( - "customHeaders" + "customRequestHeaders" )} @@ -1379,7 +1377,7 @@ export function HealthCheckCredenza(props: HealthCheckCredenzaProps) { {t( - "customHeadersDescription" + "customRequestHeadersDescription" )} diff --git a/src/components/HealthCheckFormFields.tsx b/src/components/HealthCheckFormFields.tsx index 6f5d528db..5b43e8a59 100644 --- a/src/components/HealthCheckFormFields.tsx +++ b/src/components/HealthCheckFormFields.tsx @@ -733,7 +733,7 @@ export function HealthCheckFormFields({ render={({ field }) => ( - {t("customHeaders")} + {t("customRequestHeaders")} {t( - "customHeadersDescription" + "customRequestHeadersDescription" )} diff --git a/src/components/HealthChecksTable.tsx b/src/components/HealthChecksTable.tsx index b4f273e5a..1c73076a1 100644 --- a/src/components/HealthChecksTable.tsx +++ b/src/components/HealthChecksTable.tsx @@ -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); }; diff --git a/src/components/LicenseKeysDataTable.tsx b/src/components/LicenseKeysDataTable.tsx index 4b63a7b28..939686503 100644 --- a/src/components/LicenseKeysDataTable.tsx +++ b/src/components/LicenseKeysDataTable.tsx @@ -112,6 +112,54 @@ export function LicenseKeysDataTable({ } } }, + { + accessorKey: "quantity", + friendlyName: t("users"), + header: ({ column }) => { + return ( + + ); + }, + 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 ( + + ); + }, + 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} diff --git a/src/components/PrivateResourceInfoBox.tsx b/src/components/PrivateResourceInfoBox.tsx index a7add3e36..bec193bae 100644 --- a/src/components/PrivateResourceInfoBox.tsx +++ b/src/components/PrivateResourceInfoBox.tsx @@ -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({ - - {t("access")} - - - - + {showAccess ? ( + + {t("access")} + + + + + ) : null} {showDestination ? ( diff --git a/src/components/PrivateResourceSitesField.tsx b/src/components/PrivateResourceSitesField.tsx index 0b0b930cb..5b1e0af31 100644 --- a/src/components/PrivateResourceSitesField.tsx +++ b/src/components/PrivateResourceSitesField.tsx @@ -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 = { control: Control; orgId: string; - selectedSites: Selectedsite[]; - onSelectedSitesChange: (sites: Selectedsite[]) => void; + selectedSites: SelectedSite[]; + onSelectedSitesChange: (sites: SelectedSite[]) => void; siteIdsFieldName?: FieldPath; singleSite?: boolean; }; diff --git a/src/components/PrivateResourceSshFields.tsx b/src/components/PrivateResourceSshFields.tsx index 04ac155de..a727c9649 100644 --- a/src/components/PrivateResourceSshFields.tsx +++ b/src/components/PrivateResourceSshFields.tsx @@ -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; @@ -33,8 +33,8 @@ type PrivateResourceSshFieldsProps = { watch: UseFormWatch; 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 } ); } diff --git a/src/components/PrivateResourcesTable.tsx b/src/components/PrivateResourcesTable.tsx index d15d53205..8c6281dd2 100644 --- a/src/components/PrivateResourcesTable.tsx +++ b/src/components/PrivateResourcesTable.tsx @@ -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 {modeLabels[resourceRow.mode]}; } @@ -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 ( { - const allSites: Array = [...sites]; + const allSites: Array = [...sites]; if ( debouncedQuery.trim().length === 0 && selectedSite && diff --git a/src/components/TrialBillingBanner.tsx b/src/components/TrialBillingBanner.tsx index 52fcb4873..4610f5520 100644 --- a/src/components/TrialBillingBanner.tsx +++ b/src/components/TrialBillingBanner.tsx @@ -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={} - description={t("billingTrialBannerDescription")} + description={t("billingTrialBannerDescription", { + tier: tierName + })} dismissable={false} > + + + + + + {options.map((method) => ( + toggle(method)} + > + + {method} + + ))} + + + + + + ); +} + 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({ - + {t("noRegionFound")} @@ -775,10 +885,19 @@ export function PolicyAccessRulesTable({ )} ))} - + + ) : row.original.match === "METHOD" ? ( + + updateRule(row.original.ruleId, { 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) => { diff --git a/src/components/site-selector.tsx b/src/components/site-selector.tsx index 2a7717572..af918a4fb 100644 --- a/src/components/site-selector.tsx +++ b/src/components/site-selector.tsx @@ -15,7 +15,7 @@ import { CheckIcon } from "lucide-react"; import { useTranslations } from "next-intl"; import { useDebounce } from "use-debounce"; -export type Selectedsite = Pick< +export type SelectedSite = Pick< ListSitesResponse["sites"][number], "name" | "siteId" | "type" > & { @@ -24,8 +24,8 @@ export type Selectedsite = Pick< }; type SiteOnlineStatusProps = { - type: Selectedsite["type"]; - online: Selectedsite["online"]; + type: SelectedSite["type"]; + online: SelectedSite["online"]; }; /** Dot-only indicator matching `SitesTable` colors (newt/wireguard only; nothing for local or missing status). */ @@ -57,8 +57,8 @@ export function SiteOnlineStatus({ type, online }: SiteOnlineStatusProps) { export type SitesSelectorProps = { orgId: string; - selectedSite?: Selectedsite | null; - onSelectSite: (selected: Selectedsite) => void; + selectedSite?: SelectedSite | null; + onSelectSite: (selected: SelectedSite) => void; filterTypes?: string[]; }; @@ -82,7 +82,7 @@ export function SitesSelector({ // always include the selected site in the list of sites shown const sitesShown = useMemo(() => { - const allSites: Array = filterTypes + const allSites: Array = filterTypes ? sites.filter((s) => filterTypes.includes(s.type)) : [...sites]; if ( diff --git a/src/lib/privateResourceForm.ts b/src/lib/privateResourceForm.ts index 612cce4d8..4b8464540 100644 --- a/src/lib/privateResourceForm.ts +++ b/src/lib/privateResourceForm.ts @@ -421,7 +421,14 @@ export function createCreateFormSchema(t: TranslateFn) { .min(1, t("createInternalResourceDialogNameRequired")) .max(255, t("createInternalResourceDialogNameMaxLength")), siteIds: z.array(z.number().int().positive()).optional(), - mode: z.enum(["host", "cidr", "http", "ssh", "inference"]), + mode: z.enum([ + "host", + "cidr", + "http", + "ssh", + "inference", + "gateway" + ]), destination: z.string().nullish(), alias: z.string().nullish(), destinationPort: z @@ -468,6 +475,7 @@ export function createCreateFormSchema(t: TranslateFn) { if ( data.mode !== "ssh" && data.mode !== "inference" && + data.mode !== "gateway" && (!trimmedDestination || trimmedDestination.length < 1) ) { ctx.addIssue({ @@ -652,6 +660,13 @@ export function createCidrFormSchema(t: TranslateFn) { .superRefine((data, ctx) => destinationRefine(data, ctx, t)); } +export function createGatewayFormSchema(t: TranslateFn) { + return z.object({ + siteIds: z.array(z.number().int().positive()).min(1), + mode: z.literal("gateway") + }); +} + export function createHttpFormSchema(t: TranslateFn) { return z .object({ diff --git a/src/lib/privateResourceUtils.ts b/src/lib/privateResourceUtils.ts index 37cc63756..7d53b5d71 100644 --- a/src/lib/privateResourceUtils.ts +++ b/src/lib/privateResourceUtils.ts @@ -1,11 +1,11 @@ "use client"; -import type { Selectedsite } from "@app/components/site-selector"; +import type { SelectedSite } from "@app/components/site-selector"; import type { SiteResourceData } from "@app/lib/privateResourceForm"; export function buildSelectedSitesForResource( resource: Pick -): Selectedsite[] { +): SelectedSite[] { return resource.siteIds.map((siteId, idx) => ({ name: resource.siteNames[idx] ?? "", siteId,