mirror of
https://github.com/fosrl/pangolin.git
synced 2026-08-02 18:50:39 +02:00
Merge branch 'dev' into refactor/standardize-clear-buttons
This commit is contained in:
+2
-2
@@ -200,8 +200,8 @@
|
||||
"shareErrorSelectResource": "Моля, изберете ресурс",
|
||||
"proxyResourceTitle": "Управление на обществени ресурси",
|
||||
"proxyResourceDescription": "Създайте и управлявайте ресурси, които са общодостъпни чрез уеб браузър.",
|
||||
"proxyResourcesBannerTitle": "Публичен достъп чрез уеб.",
|
||||
"proxyResourcesBannerDescription": "Публичните ресурси са HTTPS или TCP/UDP проксита, достъпни за всеки в интернет чрез уеб браузър. За разлика от частните ресурси, те не изискват софтуер от страна на клиента и могат да включват издентити и контексто-осъзнати политики за достъп.",
|
||||
"publicResourcesBannerTitle": "Публичен достъп чрез уеб.",
|
||||
"publicResourcesBannerDescription": "Публичните ресурси са HTTPS или TCP/UDP проксита, достъпни за всеки в интернет чрез уеб браузър. За разлика от частните ресурси, те не изискват софтуер от страна на клиента и могат да включват издентити и контексто-осъзнати политики за достъп.",
|
||||
"clientResourceTitle": "Управление на частни ресурси",
|
||||
"clientResourceDescription": "Създайте и управлявайте ресурси, които са достъпни само чрез свързан клиент.",
|
||||
"privateResourcesBannerTitle": "Достъп до частни ресурси с нулево доверие.",
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@
|
||||
"shareErrorSelectResource": "Zvolte prosím zdroj",
|
||||
"proxyResourceTitle": "Spravovat veřejné zdroje",
|
||||
"proxyResourceDescription": "Vytváření a správa zdrojů, které jsou veřejně přístupné prostřednictvím webového prohlížeče",
|
||||
"proxyResourcesBannerTitle": "Veřejný přístup založený na webu",
|
||||
"proxyResourcesBannerDescription": "Veřejné prostředky jsou HTTPS nebo TCP/UDP proxy, které jsou přístupné každému na internetu prostřednictvím webového prohlížeče. Na rozdíl od soukromých prostředků nevyžadují software na straně klienta a mohou zahrnovat politiky přístupu orientované na identitu a kontext.",
|
||||
"publicResourcesBannerTitle": "Veřejný přístup založený na webu",
|
||||
"publicResourcesBannerDescription": "Veřejné prostředky jsou HTTPS nebo TCP/UDP proxy, které jsou přístupné každému na internetu prostřednictvím webového prohlížeče. Na rozdíl od soukromých prostředků nevyžadují software na straně klienta a mohou zahrnovat politiky přístupu orientované na identitu a kontext.",
|
||||
"clientResourceTitle": "Spravovat soukromé zdroje",
|
||||
"clientResourceDescription": "Vytváření a správa zdrojů, které jsou přístupné pouze prostřednictvím připojeného klienta",
|
||||
"privateResourcesBannerTitle": "Zero-Trust soukromý přístup",
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@
|
||||
"shareErrorSelectResource": "Bitte wählen Sie eine Ressource",
|
||||
"proxyResourceTitle": "Öffentliche Ressourcen verwalten",
|
||||
"proxyResourceDescription": "Erstelle und verwalte Ressourcen, die über einen Webbrowser öffentlich zugänglich sind",
|
||||
"proxyResourcesBannerTitle": "Web-basierter öffentlicher Zugang",
|
||||
"proxyResourcesBannerDescription": "Öffentliche Ressourcen sind HTTPS oder TCP/UDP-Proxys, die über einen Webbrowser für jeden zugänglich sind. Im Gegensatz zu privaten Ressourcen benötigen sie keine Client-seitige Software und können Identitäts- und kontextbezogene Zugriffsrichtlinien beinhalten.",
|
||||
"publicResourcesBannerTitle": "Web-basierter öffentlicher Zugang",
|
||||
"publicResourcesBannerDescription": "Öffentliche Ressourcen sind HTTPS oder TCP/UDP-Proxys, die über einen Webbrowser für jeden zugänglich sind. Im Gegensatz zu privaten Ressourcen benötigen sie keine Client-seitige Software und können Identitäts- und kontextbezogene Zugriffsrichtlinien beinhalten.",
|
||||
"clientResourceTitle": "Private Ressourcen verwalten",
|
||||
"clientResourceDescription": "Erstelle und verwalte Ressourcen, die nur über einen verbundenen Client zugänglich sind",
|
||||
"privateResourcesBannerTitle": "Zero-Trust-Zugriff auf private Ressourcen",
|
||||
|
||||
+97
-32
@@ -150,16 +150,16 @@
|
||||
"siteCredentialsSaveDescription": "You will only be able to see this once. Make sure to copy it to a secure place.",
|
||||
"siteInfo": "Site Information",
|
||||
"status": "Status",
|
||||
"shareTitle": "Manage Share Links",
|
||||
"shareTitle": "Manage Shareable Links",
|
||||
"shareDescription": "Create shareable links to grant temporary or permanent access to proxy resources",
|
||||
"shareSearch": "Search share links...",
|
||||
"shareCreate": "Create Share Link",
|
||||
"shareSearch": "Search shareable links...",
|
||||
"shareCreate": "Create Shareable Link",
|
||||
"shareErrorDelete": "Failed to delete link",
|
||||
"shareErrorDeleteMessage": "An error occurred deleting link",
|
||||
"shareDeleted": "Link deleted",
|
||||
"shareDeletedDescription": "The link has been deleted",
|
||||
"shareDelete": "Delete Share Link",
|
||||
"shareDeleteConfirm": "Confirm Delete Share Link",
|
||||
"shareDelete": "Delete Shareable Link",
|
||||
"shareDeleteConfirm": "Confirm Delete Shareable Link",
|
||||
"shareQuestionRemove": "Are you sure you want to delete this share link?",
|
||||
"shareMessageRemove": "Once deleted, the link will no longer work and anyone using it will lose access to the resource.",
|
||||
"shareTokenDescription": "The access token can be passed in two ways: as a query parameter or in the request headers. These must be passed from the client on every request for authenticated access.",
|
||||
@@ -202,8 +202,8 @@
|
||||
"shareErrorSelectResource": "Please select a resource",
|
||||
"proxyResourceTitle": "Manage Public Resources",
|
||||
"proxyResourceDescription": "Create and manage resources that are publicly accessible through a web browser",
|
||||
"proxyResourcesBannerTitle": "Web-based Public Access",
|
||||
"proxyResourcesBannerDescription": "Public resources are HTTPS proxies accessible to anyone on the internet through a web browser. Unlike private resources, they do not require client-side software and can include identity and context-aware access policies.",
|
||||
"publicResourcesBannerTitle": "Web-based Public Access",
|
||||
"publicResourcesBannerDescription": "Public resources are HTTPS proxies accessible to anyone on the internet through a web browser. Unlike private resources, they do not require client-side software and can include identity and context-aware access policies.",
|
||||
"clientResourceTitle": "Manage Private Resources",
|
||||
"clientResourceDescription": "Create and manage resources that are only accessible through a connected client",
|
||||
"privateResourcesBannerTitle": "Zero-Trust Private Access",
|
||||
@@ -211,15 +211,18 @@
|
||||
"resourcesSearch": "Search resources...",
|
||||
"resourceAdd": "Add Resource",
|
||||
"resourceErrorDelte": "Error deleting resource",
|
||||
"resourcePoliciesTitle": "Manage Resource Policies",
|
||||
"resourcePoliciesAttachedResourcesColumnTitle": "Attached resources",
|
||||
"resourcePoliciesBannerTitle": "Re-use Authentication and Access Rules",
|
||||
"resourcePoliciesBannerDescription": "Shared resource policies let you define authentication methods and access rules once, then attach them to multiple public resources. When you update a policy, every linked resource inherits the change automatically.",
|
||||
"resourcePoliciesTitle": "Manage Public Resource Policies",
|
||||
"resourcePoliciesAttachedResourcesColumnTitle": "Resources",
|
||||
"resourcePoliciesAttachedResources": "{count} resource(s)",
|
||||
"resourcePoliciesAttachedResourcesCount": "{count, plural, one {# resource} other {# resources}}",
|
||||
"resourcePoliciesAttachedResourcesEmpty": "no resources",
|
||||
"resourcePoliciesDescription": "Create and manage authentication policies to control access to your resources",
|
||||
"resourcePoliciesDescription": "Create and manage authentication policies to control access to your public resources",
|
||||
"resourcePoliciesSearch": "Search policies...",
|
||||
"resourcePoliciesAdd": "Add Policy",
|
||||
"resourcePoliciesDefaultBadgeText": "Default policy",
|
||||
"resourcePoliciesCreate": "Create Resource Policy",
|
||||
"resourcePoliciesCreate": "Create Public Resource Policy",
|
||||
"resourcePoliciesCreateDescription": "Follow the steps below to create a new policy",
|
||||
"resourcePolicyName": "Policy Name",
|
||||
"resourcePolicyNameDescription": "Give this policy a name to identify it across your resources",
|
||||
@@ -313,7 +316,7 @@
|
||||
"rules": "Rules",
|
||||
"resourceSettingDescription": "Configure the settings on the resource",
|
||||
"resourceSetting": "{resourceName} Settings",
|
||||
"resourcePolicySettingDescription": "Configure the settings on the resource policy",
|
||||
"resourcePolicySettingDescription": "Configure the settings on this public resource policy",
|
||||
"resourcePolicySetting": "{policyName} Settings",
|
||||
"alwaysAllow": "Bypass Auth",
|
||||
"alwaysDeny": "Block Access",
|
||||
@@ -755,11 +758,11 @@
|
||||
"rulesErrorDuplicate": "Duplicate rule",
|
||||
"rulesErrorDuplicateDescription": "A rule with these settings already exists",
|
||||
"rulesErrorInvalidIpAddressRange": "Invalid CIDR",
|
||||
"rulesErrorInvalidIpAddressRangeDescription": "Please enter a valid CIDR value",
|
||||
"rulesErrorInvalidUrl": "Invalid URL path",
|
||||
"rulesErrorInvalidUrlDescription": "Please enter a valid URL path value",
|
||||
"rulesErrorInvalidIpAddress": "Invalid IP",
|
||||
"rulesErrorInvalidIpAddressDescription": "Please enter a valid IP address",
|
||||
"rulesErrorInvalidIpAddressRangeDescription": "Enter a valid CIDR range (e.g., 10.0.0.0/8).",
|
||||
"rulesErrorInvalidUrl": "Invalid path",
|
||||
"rulesErrorInvalidUrlDescription": "Enter a valid URL path or pattern (e.g., /api/*).",
|
||||
"rulesErrorInvalidIpAddress": "Invalid IP address",
|
||||
"rulesErrorInvalidIpAddressDescription": "Enter a valid IPv4 or IPv6 address.",
|
||||
"rulesErrorUpdate": "Failed to update rules",
|
||||
"rulesErrorUpdateDescription": "An error occurred while updating rules",
|
||||
"rulesUpdated": "Enable Rules",
|
||||
@@ -767,15 +770,24 @@
|
||||
"rulesMatchIpAddressRangeDescription": "Enter an address in CIDR format (e.g., 103.21.244.0/22)",
|
||||
"rulesMatchIpAddress": "Enter an IP address (e.g., 103.21.244.12)",
|
||||
"rulesMatchUrl": "Enter a URL path or pattern (e.g., /api/v1/todos or /api/v1/*)",
|
||||
"rulesErrorInvalidPriority": "Invalid Priority",
|
||||
"rulesErrorInvalidPriorityDescription": "Please enter a valid priority",
|
||||
"rulesErrorDuplicatePriority": "Duplicate Priorities",
|
||||
"rulesErrorDuplicatePriorityDescription": "Please enter unique priorities",
|
||||
"rulesErrorInvalidPriority": "Invalid priority",
|
||||
"rulesErrorInvalidPriorityDescription": "Enter a whole number of 1 or higher.",
|
||||
"rulesErrorDuplicatePriority": "Duplicate priorities",
|
||||
"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).",
|
||||
"rulesErrorValueRequired": "Enter a value for this rule.",
|
||||
"rulesErrorInvalidCountry": "Invalid country",
|
||||
"rulesErrorInvalidCountryDescription": "Select a valid country.",
|
||||
"rulesErrorInvalidAsn": "Invalid ASN",
|
||||
"rulesErrorInvalidAsnDescription": "Enter a valid ASN (e.g., AS15169).",
|
||||
"ruleUpdated": "Rules updated",
|
||||
"ruleUpdatedDescription": "Rules updated successfully",
|
||||
"ruleErrorUpdate": "Operation failed",
|
||||
"ruleErrorUpdateDescription": "An error occurred during the save operation",
|
||||
"rulesPriority": "Priority",
|
||||
"rulesReorderDragHandle": "Drag to reorder rule priority",
|
||||
"rulesAction": "Action",
|
||||
"rulesMatchType": "Match Type",
|
||||
"value": "Value",
|
||||
@@ -794,7 +806,7 @@
|
||||
"rulesResource": "Resource Rules Configuration",
|
||||
"rulesResourceDescription": "Configure rules to control access to the resource",
|
||||
"ruleSubmit": "Add Rule",
|
||||
"rulesNoOne": "No rules. Add a rule using the form.",
|
||||
"rulesNoOne": "No rules yet.",
|
||||
"rulesOrder": "Rules are evaluated by priority in ascending order.",
|
||||
"rulesSubmit": "Save Rules",
|
||||
"policyErrorCreate": "Error creating policy",
|
||||
@@ -805,7 +817,48 @@
|
||||
"policyErrorUpdateMessageDescription": "An unexpected error occurred",
|
||||
"policyCreatedSuccess": "Resource policy succesfully created",
|
||||
"policyUpdatedSuccess": "Resource policy succesfully updated",
|
||||
"authMethodsSave": "Save auth methods",
|
||||
"authMethodsSave": "Save Settings",
|
||||
"policyAuthStackTitle": "Authentication",
|
||||
"policyAuthStackDescription": "Control which authentication methods are required to access this resource",
|
||||
"policyAuthOrLogicTitle": "Multiple authentication methods active",
|
||||
"policyAuthOrLogicBanner": "Visitors may authenticate using any one of the active methods below. They do not need to complete all of them.",
|
||||
"policyAuthMethodActive": "Active",
|
||||
"policyAuthMethodOff": "Off",
|
||||
"policyAuthSsoTitle": "Platform SSO",
|
||||
"policyAuthSsoDescription": "Require sign-in through your organization's identity provider",
|
||||
"policyAuthSsoSummary": "{idp} · {users} users, {roles} roles",
|
||||
"policyAuthSsoDefaultIdp": "Default provider",
|
||||
"policyAuthAddDefaultIdentityProvider": "Add Default Identity Provider",
|
||||
"policyAuthOtherMethodsTitle": "Other Methods",
|
||||
"policyAuthOtherMethodsDescription": "Optional methods visitors can use instead of or alongside platform SSO",
|
||||
"policyAuthPasscodeTitle": "Passcode",
|
||||
"policyAuthPasscodeDescription": "Require a shared alphanumeric passcode to access the resource",
|
||||
"policyAuthPasscodeSummary": "Passcode set",
|
||||
"policyAuthPincodeTitle": "PIN Code",
|
||||
"policyAuthPincodeDescription": "A short numeric code required to access the resource",
|
||||
"policyAuthPincodeSummary": "6-digit PIN set",
|
||||
"policyAuthEmailTitle": "Email Whitelist",
|
||||
"policyAuthEmailDescription": "Allow listed email addresses with one-time passwords",
|
||||
"policyAuthEmailSummary": "{count} addresses allowed",
|
||||
"policyAuthEmailOtpCallout": "Enabling email whitelist sends a one-time password to the visitor's email on login.",
|
||||
"policyAuthHeaderAuthTitle": "Basic Header Auth",
|
||||
"policyAuthHeaderAuthDescription": "Validate a custom HTTP header name and value on each request",
|
||||
"policyAuthHeaderAuthSummary": "Header configured",
|
||||
"policyAuthHeaderName": "Header name",
|
||||
"policyAuthHeaderValue": "Expected value",
|
||||
"policyAuthSetPasscode": "Set Passcode",
|
||||
"policyAuthSetPincode": "Set PIN Code",
|
||||
"policyAuthSetEmailWhitelist": "Set Email Whitelist",
|
||||
"policyAuthSetHeaderAuth": "Set Basic Header Auth",
|
||||
"policyAccessRulesTitle": "Access Rules",
|
||||
"policyAccessRulesEnableDescription": "When enabled, rules are evaluated in descending order until one evaluates as true.",
|
||||
"policyAccessRulesFirstMatch": "Rules are evaluated top to bottom. The first matching rule decides the outcome.",
|
||||
"policyAccessRulesHowItWorks": "Rules match requests by path, IP address, location, or other criteria. Each rule applies an action: bypass authentication, block access, or pass to authentication. If no rule matches, traffic continues to authentication.",
|
||||
"policyAccessRulesFallthroughOff": "When rules are disabled, all traffic passes through to authentication.",
|
||||
"policyAccessRulesFallthroughOn": "When no rule matches, traffic passes through to authentication.",
|
||||
"rulesPlaceholderCidr": "10.0.0.0/8",
|
||||
"rulesPlaceholderPath": "/admin/*",
|
||||
"rulesPlaceholderGeo": "RU, KP",
|
||||
"rulesSave": "Save Rules",
|
||||
"resourceErrorCreate": "Error creating resource",
|
||||
"resourceErrorCreateDescription": "An error occurred when creating the resource",
|
||||
@@ -826,9 +879,9 @@
|
||||
"resourcesErrorUpdateDescription": "An error occurred while updating the resource",
|
||||
"access": "Access",
|
||||
"accessControl": "Access Control",
|
||||
"shareLink": "{resource} Share Link",
|
||||
"shareLink": "{resource} Shareable Link",
|
||||
"resourceSelect": "Select resource",
|
||||
"shareLinks": "Share Links",
|
||||
"shareLinks": "Shareable Links",
|
||||
"share": "Shareable Links",
|
||||
"shareDescription2": "Create shareable links to resources. Links provide temporary or unlimited access to your resource. You can configure the expiration duration of the link when you create one.",
|
||||
"shareEasyCreate": "Easy to create and share",
|
||||
@@ -918,10 +971,16 @@
|
||||
"resourceRoleDescription": "Admins can always access this resource.",
|
||||
"resourcePolicySelectTitle": "Resource Access Policy",
|
||||
"resourcePolicySelectDescription": "Select the resource policy type for authentication",
|
||||
"resourcePolicyTypeLabel": "Policy type",
|
||||
"resourcePolicyLabel": "Resource policy",
|
||||
"resourcePolicyInline": "Inline Resource Policy",
|
||||
"resourcePolicyInlineDescription": "Access Policy scoped to only this resource",
|
||||
"resourcePolicyShared": "Shared Resource Policy",
|
||||
"resourcePolicySharedDescription": "This resource uses a shared policy. Policy-level settings (auth methods, email whitelist) are locked. You can add resource-specific rules, roles, and users below.",
|
||||
"resourcePolicySharedDescription": "This resource uses a shared policy.",
|
||||
"sharedPolicy": "Shared Policy",
|
||||
"sharedPolicyNoneDescription": "This resource has its own policy.",
|
||||
"resourceSharedPolicyAuthenticationNotice": "This resource is using a shared policy. Some authentication settings can be edited on this resource. To change the underlying policy, you must edit to <policyLink>{policyName}</policyLink>.",
|
||||
"resourceSharedPolicyRulesNotice": "This resource is using a shared policy. Some access rules can be edited on this resource. To change the underlying policy, you must edit <policyLink>{policyName}</policyLink>.",
|
||||
"resourceUsersRoles": "Access Controls",
|
||||
"resourceUsersRolesDescription": "Configure which users and roles can visit this resource",
|
||||
"resourceUsersRolesSubmit": "Save Access Controls",
|
||||
@@ -1466,8 +1525,8 @@
|
||||
"sidebarResources": "Resources",
|
||||
"sidebarProxyResources": "Public",
|
||||
"sidebarClientResources": "Private",
|
||||
"sidebarPolicies": "Policies",
|
||||
"sidebarResourcePolicies": "Resources",
|
||||
"sidebarPolicies": "Shared Policies",
|
||||
"sidebarResourcePolicies": "Public Resources",
|
||||
"sidebarAccessControl": "Access Control",
|
||||
"sidebarLogsAndAnalytics": "Logs & Analytics",
|
||||
"sidebarTeam": "Team",
|
||||
@@ -1475,7 +1534,7 @@
|
||||
"sidebarAdmin": "Admin",
|
||||
"sidebarInvitations": "Invitations",
|
||||
"sidebarRoles": "Roles",
|
||||
"sidebarShareableLinks": "Links",
|
||||
"sidebarShareableLinks": "Shareable Links",
|
||||
"sidebarApiKeys": "API Keys",
|
||||
"sidebarProvisioning": "Provisioning",
|
||||
"sidebarSettings": "Settings",
|
||||
@@ -2032,13 +2091,13 @@
|
||||
"healthCheckUnknown": "Unknown",
|
||||
"healthCheck": "Health Check",
|
||||
"configureHealthCheck": "Configure Health Check",
|
||||
"configureHealthCheckDescription": "Set up health monitoring for {target}",
|
||||
"configureHealthCheckDescription": "Set up monitoring for your resource to ensure it is always available",
|
||||
"enableHealthChecks": "Enable Health Checks",
|
||||
"healthCheckDisabledStateDescription": "When disabled, the site will not perform health checks and the state will be considered unknown.",
|
||||
"enableHealthChecksDescription": "Monitor the health of this target. You can monitor a different endpoint than the target if required.",
|
||||
"healthScheme": "Method",
|
||||
"healthSelectScheme": "Select Method",
|
||||
"healthCheckPortInvalid": "Health check port must be between 1 and 65535",
|
||||
"healthCheckPortInvalid": "Port must be between 1 and 65535",
|
||||
"healthCheckPath": "Path",
|
||||
"healthHostname": "IP / Host",
|
||||
"healthPort": "Port",
|
||||
@@ -2080,6 +2139,11 @@
|
||||
"sshServerDestination": "Server Destination",
|
||||
"sshServerDestinationDescription": "Configure the destination of the SSH server",
|
||||
"destination": "Destination",
|
||||
"destinationRequired": "Destination is required.",
|
||||
"domainRequired": "Domain is required.",
|
||||
"proxyPortRequired": "Port is required.",
|
||||
"invalidPathConfiguration": "Invalid path configuration.",
|
||||
"invalidRewritePathConfiguration": "Invalid rewrite path configuration.",
|
||||
"bgTargetMultiSiteDisclaimer": "Selecting multiple sites enables resilient routing and failover for high availability.",
|
||||
"roleAllowSsh": "Allow SSH",
|
||||
"roleAllowSshAllow": "Allow",
|
||||
@@ -3040,7 +3104,7 @@
|
||||
"enterConfirmation": "Enter confirmation",
|
||||
"blueprintViewDetails": "Details",
|
||||
"defaultIdentityProvider": "Default Identity Provider",
|
||||
"defaultIdentityProviderDescription": "When a default identity provider is selected, the user will be automatically redirected to the provider for authentication.",
|
||||
"defaultIdentityProviderDescription": "The user will be automatically redirected to this identity provider for authentication.",
|
||||
"editInternalResourceDialogNetworkSettings": "Network Settings",
|
||||
"editInternalResourceDialogAccessPolicy": "Access Policy",
|
||||
"editInternalResourceDialogAddRoles": "Add Roles",
|
||||
@@ -3081,6 +3145,7 @@
|
||||
"maintenanceModeType": "Maintenance Mode Type",
|
||||
"showMaintenancePage": "Show a maintenance page to visitors",
|
||||
"enableMaintenanceMode": "Enable Maintenance Mode",
|
||||
"enableMaintenanceModeDescription": "When enabled, visitors will see a maintenance page instead of your resource.",
|
||||
"automatic": "Automatic",
|
||||
"automaticModeDescription": " Show maintenance page only when all backend targets are down or unhealthy. Your resource continues working normally as long as at least one target is healthy.",
|
||||
"forced": "Forced",
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@
|
||||
"shareErrorSelectResource": "Por favor, seleccione un recurso",
|
||||
"proxyResourceTitle": "Administrar recursos públicos",
|
||||
"proxyResourceDescription": "Crear y administrar recursos que sean accesibles públicamente a través de un navegador web",
|
||||
"proxyResourcesBannerTitle": "Acceso público basado en web",
|
||||
"proxyResourcesBannerDescription": "Los recursos públicos son proxies HTTPS o TCP/UDP accesibles a cualquiera en Internet a través de un navegador web. A diferencia de los recursos privados, no requieren software del lado del cliente e incluye políticas de acceso basadas en identidad y contexto.",
|
||||
"publicResourcesBannerTitle": "Acceso público basado en web",
|
||||
"publicResourcesBannerDescription": "Los recursos públicos son proxies HTTPS o TCP/UDP accesibles a cualquiera en Internet a través de un navegador web. A diferencia de los recursos privados, no requieren software del lado del cliente e incluye políticas de acceso basadas en identidad y contexto.",
|
||||
"clientResourceTitle": "Administrar recursos privados",
|
||||
"clientResourceDescription": "Crear y administrar recursos que sólo son accesibles a través de un cliente conectado",
|
||||
"privateResourcesBannerTitle": "Acceso privado de confianza cero",
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@
|
||||
"shareErrorSelectResource": "Veuillez sélectionner une ressource",
|
||||
"proxyResourceTitle": "Gérer les ressources publiques",
|
||||
"proxyResourceDescription": "Créer et gérer des ressources accessibles au public via un navigateur web",
|
||||
"proxyResourcesBannerTitle": "Accès public basé sur le Web",
|
||||
"proxyResourcesBannerDescription": "Les ressources publiques sont des proxys HTTPS ou TCP/UDP accessibles par tout le monde sur Internet via un navigateur Web. Contrairement aux ressources privées, elles n'exigent pas de logiciel côté client et peuvent inclure des politiques d'accès basées sur l'identité et le contexte.",
|
||||
"publicResourcesBannerTitle": "Accès public basé sur le Web",
|
||||
"publicResourcesBannerDescription": "Les ressources publiques sont des proxys HTTPS ou TCP/UDP accessibles par tout le monde sur Internet via un navigateur Web. Contrairement aux ressources privées, elles n'exigent pas de logiciel côté client et peuvent inclure des politiques d'accès basées sur l'identité et le contexte.",
|
||||
"clientResourceTitle": "Gérer les ressources privées",
|
||||
"clientResourceDescription": "Créer et gérer des ressources qui ne sont accessibles que via un client connecté",
|
||||
"privateResourcesBannerTitle": "Accès privé sans confiance",
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@
|
||||
"shareErrorSelectResource": "Seleziona una risorsa",
|
||||
"proxyResourceTitle": "Gestisci Risorse Pubbliche",
|
||||
"proxyResourceDescription": "Creare e gestire risorse pubbliche accessibili tramite un browser web",
|
||||
"proxyResourcesBannerTitle": "Accesso Pubblico Basato sul Web",
|
||||
"proxyResourcesBannerDescription": "Le risorse pubbliche sono proxy HTTPS o TCP/UDP accessibili da chiunque tramite Internet da un browser web. A differenza delle risorse private non richiedono software lato client e possono includere politiche di accesso basate su identità e contesto.",
|
||||
"publicResourcesBannerTitle": "Accesso Pubblico Basato sul Web",
|
||||
"publicResourcesBannerDescription": "Le risorse pubbliche sono proxy HTTPS o TCP/UDP accessibili da chiunque tramite Internet da un browser web. A differenza delle risorse private non richiedono software lato client e possono includere politiche di accesso basate su identità e contesto.",
|
||||
"clientResourceTitle": "Gestisci Risorse Private",
|
||||
"clientResourceDescription": "Crea e gestisci risorse accessibili solo tramite un client connesso",
|
||||
"privateResourcesBannerTitle": "Accesso Privato Zero-Trust",
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@
|
||||
"shareErrorSelectResource": "리소스를 선택하세요",
|
||||
"proxyResourceTitle": "공개 리소스 관리",
|
||||
"proxyResourceDescription": "웹 브라우저를 통해 공용으로 접근할 수 있는 리소스를 생성하고 관리하세요.",
|
||||
"proxyResourcesBannerTitle": "웹 기반 공공 접근",
|
||||
"proxyResourcesBannerDescription": "공공 자원은 누구나 웹 브라우저를 통해 접근 가능한 HTTPS 또는 TCP/UDP 프록시입니다. 개인 자원과 달리 클라이언트 측 소프트웨어가 필요하지 않으며, 아이덴티티 및 컨텍스트 인지 접근 정책을 포함할 수 있습니다.",
|
||||
"publicResourcesBannerTitle": "웹 기반 공공 접근",
|
||||
"publicResourcesBannerDescription": "공공 자원은 누구나 웹 브라우저를 통해 접근 가능한 HTTPS 또는 TCP/UDP 프록시입니다. 개인 자원과 달리 클라이언트 측 소프트웨어가 필요하지 않으며, 아이덴티티 및 컨텍스트 인지 접근 정책을 포함할 수 있습니다.",
|
||||
"clientResourceTitle": "개인 리소스 관리",
|
||||
"clientResourceDescription": "연결된 클라이언트를 통해서만 접근할 수 있는 리소스를 생성하고 관리하세요.",
|
||||
"privateResourcesBannerTitle": "제로 트러스트 개인 접근",
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@
|
||||
"shareErrorSelectResource": "Vennligst velg en ressurs",
|
||||
"proxyResourceTitle": "Administrere offentlige ressurser",
|
||||
"proxyResourceDescription": "Opprett og administrer ressurser som er offentlig tilgjengelige via en nettleser",
|
||||
"proxyResourcesBannerTitle": "Nettbasert offentlig tilgang",
|
||||
"proxyResourcesBannerDescription": "Offentlige ressurser er HTTPS- eller TCP/UDP-proxyer tilgjengelige for alle på internett via en nettleser. I motsetning til private ressurser, krever de ikke klient-basert programvare og kan inkludere identitets- og kontekstbevisste tilgangspolicyer.",
|
||||
"publicResourcesBannerTitle": "Nettbasert offentlig tilgang",
|
||||
"publicResourcesBannerDescription": "Offentlige ressurser er HTTPS- eller TCP/UDP-proxyer tilgjengelige for alle på internett via en nettleser. I motsetning til private ressurser, krever de ikke klient-basert programvare og kan inkludere identitets- og kontekstbevisste tilgangspolicyer.",
|
||||
"clientResourceTitle": "Administrer private ressurser",
|
||||
"clientResourceDescription": "Opprette og administrere ressurser som bare er tilgjengelige via en tilkoblet klient",
|
||||
"privateResourcesBannerTitle": "Zero-Trust privat tilgang",
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@
|
||||
"shareErrorSelectResource": "Selecteer een bron",
|
||||
"proxyResourceTitle": "Openbare bronnen beheren",
|
||||
"proxyResourceDescription": "Creëer en beheer bronnen die openbaar toegankelijk zijn via een webbrowser",
|
||||
"proxyResourcesBannerTitle": "Webgebaseerde openbare toegang",
|
||||
"proxyResourcesBannerDescription": "Openbare bronnen zijn HTTPS of TCP/UDP-proxies die toegankelijk zijn voor iedereen op het internet via een webbrowser. In tegenstelling tot priv��bronnen vereisen ze geen client-side software maar kunnen ze identiteits- en context-bewuste toegangsrichtlijnen bevatten.",
|
||||
"publicResourcesBannerTitle": "Webgebaseerde openbare toegang",
|
||||
"publicResourcesBannerDescription": "Openbare bronnen zijn HTTPS of TCP/UDP-proxies die toegankelijk zijn voor iedereen op het internet via een webbrowser. In tegenstelling tot priv��bronnen vereisen ze geen client-side software maar kunnen ze identiteits- en context-bewuste toegangsrichtlijnen bevatten.",
|
||||
"clientResourceTitle": "Privébronnen beheren",
|
||||
"clientResourceDescription": "Creëer en beheer bronnen die alleen toegankelijk zijn via een verbonden client",
|
||||
"privateResourcesBannerTitle": "Zero-Trust Private Access",
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@
|
||||
"shareErrorSelectResource": "Wybierz zasób",
|
||||
"proxyResourceTitle": "Zarządzaj zasobami publicznymi",
|
||||
"proxyResourceDescription": "Twórz i zarządzaj zasobami, które są publicznie dostępne w przeglądarce internetowej",
|
||||
"proxyResourcesBannerTitle": "Publiczny dostęp za pośrednictwem sieci Web",
|
||||
"proxyResourcesBannerDescription": "Zasoby publiczne to proxy HTTPS lub TCP/UDP dostępne dla każdego w internecie za pośrednictwem przeglądarki internetowej. W przeciwieństwie do zasobów prywatnych, nie wymagają oprogramowania po stronie klienta i mogą obejmować polityki dostępu świadome tożsamości i kontekstu.",
|
||||
"publicResourcesBannerTitle": "Publiczny dostęp za pośrednictwem sieci Web",
|
||||
"publicResourcesBannerDescription": "Zasoby publiczne to proxy HTTPS lub TCP/UDP dostępne dla każdego w internecie za pośrednictwem przeglądarki internetowej. W przeciwieństwie do zasobów prywatnych, nie wymagają oprogramowania po stronie klienta i mogą obejmować polityki dostępu świadome tożsamości i kontekstu.",
|
||||
"clientResourceTitle": "Zarządzaj zasobami prywatnymi",
|
||||
"clientResourceDescription": "Twórz i zarządzaj zasobami, które są dostępne tylko za pośrednictwem połączonego klienta",
|
||||
"privateResourcesBannerTitle": "Zero zaufania do prywatnego dostępu",
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@
|
||||
"shareErrorSelectResource": "Por favor, selecione um recurso",
|
||||
"proxyResourceTitle": "Gerenciar Recursos Públicos",
|
||||
"proxyResourceDescription": "Criar e gerenciar recursos que são acessíveis publicamente por meio de um navegador da web",
|
||||
"proxyResourcesBannerTitle": "Acesso Público via Web",
|
||||
"proxyResourcesBannerDescription": "Os recursos públicos são proxies HTTPS ou TCP/UDP acessíveis a qualquer pessoa na internet por meio de um navegador web. Ao contrário dos recursos privados, eles não requerem software do lado do cliente e podem incluir políticas de acesso conscientes de identidade e contexto.",
|
||||
"publicResourcesBannerTitle": "Acesso Público via Web",
|
||||
"publicResourcesBannerDescription": "Os recursos públicos são proxies HTTPS ou TCP/UDP acessíveis a qualquer pessoa na internet por meio de um navegador web. Ao contrário dos recursos privados, eles não requerem software do lado do cliente e podem incluir políticas de acesso conscientes de identidade e contexto.",
|
||||
"clientResourceTitle": "Gerenciar recursos privados",
|
||||
"clientResourceDescription": "Criar e gerenciar recursos que só são acessíveis por meio de um cliente conectado",
|
||||
"privateResourcesBannerTitle": "Acesso Privado com Confiança Zero",
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@
|
||||
"shareErrorSelectResource": "Пожалуйста, выберите ресурс",
|
||||
"proxyResourceTitle": "Управление публичными ресурсами",
|
||||
"proxyResourceDescription": "Создание и управление ресурсами, которые доступны через веб-браузер",
|
||||
"proxyResourcesBannerTitle": "Общедоступный доступ через веб",
|
||||
"proxyResourcesBannerDescription": "Общедоступные ресурсы - это прокси-по HTTPS или TCP/UDP, доступные любому пользователю в Интернете через веб-браузер. В отличие от частных ресурсов, они не требуют программного обеспечения на стороне клиента и могут включать политики доступа на основе идентификации и контекста.",
|
||||
"publicResourcesBannerTitle": "Общедоступный доступ через веб",
|
||||
"publicResourcesBannerDescription": "Общедоступные ресурсы - это прокси-по HTTPS или TCP/UDP, доступные любому пользователю в Интернете через веб-браузер. В отличие от частных ресурсов, они не требуют программного обеспечения на стороне клиента и могут включать политики доступа на основе идентификации и контекста.",
|
||||
"clientResourceTitle": "Управление приватными ресурсами",
|
||||
"clientResourceDescription": "Создание и управление ресурсами, которые доступны только через подключенный клиент",
|
||||
"privateResourcesBannerTitle": "Частный доступ с нулевым доверием",
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@
|
||||
"shareErrorSelectResource": "Lütfen bir kaynak seçin",
|
||||
"proxyResourceTitle": "Herkese Açık Kaynakları Yönet",
|
||||
"proxyResourceDescription": "Bir web tarayıcısı aracılığıyla kamuya açık kaynaklar oluşturun ve yönetin",
|
||||
"proxyResourcesBannerTitle": "Web Tabanlı Genel Erişim",
|
||||
"proxyResourcesBannerDescription": "Genel kaynaklar, web tarayıcısı aracılığıyla herkesin internette erişebileceği HTTPS veya TCP/UDP proxy'leridir. Özel kaynakların aksine, istemci tarafı yazılıma ihtiyaç duymazlar ve kimlik ve bağlam farkındalığı erişim politikalarını içerebilirler.",
|
||||
"publicResourcesBannerTitle": "Web Tabanlı Genel Erişim",
|
||||
"publicResourcesBannerDescription": "Genel kaynaklar, web tarayıcısı aracılığıyla herkesin internette erişebileceği HTTPS veya TCP/UDP proxy'leridir. Özel kaynakların aksine, istemci tarafı yazılıma ihtiyaç duymazlar ve kimlik ve bağlam farkındalığı erişim politikalarını içerebilirler.",
|
||||
"clientResourceTitle": "Özel Kaynakları Yönet",
|
||||
"clientResourceDescription": "Sadece bağlı bir istemci aracılığıyla erişilebilen kaynakları oluşturun ve yönetin",
|
||||
"privateResourcesBannerTitle": "Sıfır Güven Özel Erişim",
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@
|
||||
"shareErrorSelectResource": "请选择一个资源",
|
||||
"proxyResourceTitle": "管理公共资源",
|
||||
"proxyResourceDescription": "创建和管理可通过 Web 浏览器公开访问的资源",
|
||||
"proxyResourcesBannerTitle": "基于Web的公共访问",
|
||||
"proxyResourcesBannerDescription": "公共资源是可以通过网络浏览器在互联网上任何人访问的HTTPS或TCP/UDP代理。与私人资源不同,它们不需要客户端软件,并且可以包含身份和上下文感知访问策略。",
|
||||
"publicResourcesBannerTitle": "基于Web的公共访问",
|
||||
"publicResourcesBannerDescription": "公共资源是可以通过网络浏览器在互联网上任何人访问的HTTPS或TCP/UDP代理。与私人资源不同,它们不需要客户端软件,并且可以包含身份和上下文感知访问策略。",
|
||||
"clientResourceTitle": "管理私有资源",
|
||||
"clientResourceDescription": "创建和管理只能通过连接客户端访问的资源",
|
||||
"privateResourcesBannerTitle": "零信任的私人访问",
|
||||
|
||||
+2
-2
@@ -152,8 +152,8 @@
|
||||
"shareErrorSelectResource": "請選擇一個資源",
|
||||
"proxyResourceTitle": "管理公開資源",
|
||||
"proxyResourceDescription": "建立和管理可透過網頁瀏覽器公開存取的資源",
|
||||
"proxyResourcesBannerTitle": "基於網頁的公開存取",
|
||||
"proxyResourcesBannerDescription": "公開資源是任何人都可以透過網頁瀏覽器存取的 HTTPS 或 TCP/UDP 代理。與私有資源不同,它們不需要客戶端軟體,並且可以包含基於身份和情境感知的存取策略。",
|
||||
"publicResourcesBannerTitle": "基於網頁的公開存取",
|
||||
"publicResourcesBannerDescription": "公開資源是任何人都可以透過網頁瀏覽器存取的 HTTPS 或 TCP/UDP 代理。與私有資源不同,它們不需要客戶端軟體,並且可以包含基於身份和情境感知的存取策略。",
|
||||
"clientResourceTitle": "管理私有資源",
|
||||
"clientResourceDescription": "建立和管理只能透過已連接的客戶端存取的資源",
|
||||
"privateResourcesBannerTitle": "零信任私有存取",
|
||||
|
||||
@@ -580,24 +580,6 @@ export const trialNotifications = pgTable("trialNotifications", {
|
||||
sentAt: bigint("sentAt", { mode: "number" }).notNull()
|
||||
});
|
||||
|
||||
export const browserGatewayTarget = pgTable("browserGatewayTarget", {
|
||||
browserGatewayTargetId: serial("browserGatewayTargetId").primaryKey(),
|
||||
resourceId: integer("resourceId")
|
||||
.references(() => resources.resourceId, {
|
||||
onDelete: "cascade"
|
||||
})
|
||||
.notNull(),
|
||||
siteId: integer("siteId")
|
||||
.references(() => sites.siteId, {
|
||||
onDelete: "cascade"
|
||||
})
|
||||
.notNull(),
|
||||
authToken: varchar("authToken").notNull(),
|
||||
type: varchar("type").notNull(), // "ssh", "rdp", "vnc"
|
||||
destination: varchar("destination").notNull(),
|
||||
destinationPort: integer("destinationPort").notNull()
|
||||
});
|
||||
|
||||
export type Approval = InferSelectModel<typeof approvals>;
|
||||
export type Limit = InferSelectModel<typeof limits>;
|
||||
export type Account = InferSelectModel<typeof account>;
|
||||
@@ -645,6 +627,3 @@ export type AlertEmailRecipients = InferSelectModel<
|
||||
>;
|
||||
export type AlertWebhookActions = InferSelectModel<typeof alertWebhookActions>;
|
||||
export type TrialNotification = InferSelectModel<typeof trialNotifications>;
|
||||
export type BrowserGatewayTarget = InferSelectModel<
|
||||
typeof browserGatewayTarget
|
||||
>;
|
||||
|
||||
@@ -290,7 +290,12 @@ export const targets = pgTable("targets", {
|
||||
pathMatchType: text("pathMatchType"), // exact, prefix, regex
|
||||
rewritePath: text("rewritePath"), // if set, rewrites the path to this value before sending to the target
|
||||
rewritePathType: text("rewritePathType"), // exact, prefix, regex, stripPrefix
|
||||
priority: integer("priority").notNull().default(100)
|
||||
priority: integer("priority").notNull().default(100),
|
||||
mode: varchar("mode")
|
||||
.$type<"http" | "tcp" | "udp" | "ssh" | "rdp" | "vnc">()
|
||||
.notNull()
|
||||
.default("http"),
|
||||
authToken: varchar("authToken")
|
||||
});
|
||||
|
||||
export const targetHealthCheck = pgTable("targetHealthCheck", {
|
||||
|
||||
@@ -588,26 +588,6 @@ export const trialNotifications = sqliteTable("trialNotifications", {
|
||||
sentAt: integer("sentAt").notNull()
|
||||
});
|
||||
|
||||
export const browserGatewayTarget = sqliteTable("browserGatewayTarget", {
|
||||
browserGatewayTargetId: integer("browserGatewayTargetId").primaryKey({
|
||||
autoIncrement: true
|
||||
}),
|
||||
resourceId: integer("resourceId")
|
||||
.references(() => resources.resourceId, {
|
||||
onDelete: "cascade"
|
||||
})
|
||||
.notNull(),
|
||||
siteId: integer("siteId")
|
||||
.references(() => sites.siteId, {
|
||||
onDelete: "cascade"
|
||||
})
|
||||
.notNull(),
|
||||
authToken: text("authToken").notNull(),
|
||||
type: text("type").notNull(), // "ssh", "rdp", "vnc"
|
||||
destination: text("destination").notNull(),
|
||||
destinationPort: integer("destinationPort").notNull()
|
||||
});
|
||||
|
||||
export type Approval = InferSelectModel<typeof approvals>;
|
||||
export type Limit = InferSelectModel<typeof limits>;
|
||||
export type Account = InferSelectModel<typeof account>;
|
||||
@@ -647,6 +627,3 @@ export type AlertEmailAction = InferSelectModel<typeof alertEmailActions>;
|
||||
export type AlertEmailRecipient = InferSelectModel<typeof alertEmailRecipients>;
|
||||
export type AlertWebhookAction = InferSelectModel<typeof alertWebhookActions>;
|
||||
export type TrialNotification = InferSelectModel<typeof trialNotifications>;
|
||||
export type BrowserGatewayTarget = InferSelectModel<
|
||||
typeof browserGatewayTarget
|
||||
>;
|
||||
|
||||
@@ -322,7 +322,12 @@ export const targets = sqliteTable("targets", {
|
||||
pathMatchType: text("pathMatchType"), // exact, prefix, regex
|
||||
rewritePath: text("rewritePath"), // if set, rewrites the path to this value before sending to the target
|
||||
rewritePathType: text("rewritePathType"), // exact, prefix, regex, stripPrefix
|
||||
priority: integer("priority").notNull().default(100)
|
||||
priority: integer("priority").notNull().default(100),
|
||||
mode: text("mode")
|
||||
.$type<"http" | "tcp" | "udp" | "ssh" | "rdp" | "vnc">()
|
||||
.notNull()
|
||||
.default("http"),
|
||||
authToken: text("authToken")
|
||||
});
|
||||
|
||||
export const targetHealthCheck = sqliteTable("targetHealthCheck", {
|
||||
|
||||
@@ -10,16 +10,22 @@ import {
|
||||
clientSiteResources
|
||||
} from "@server/db";
|
||||
import { Config, ConfigSchema } from "./types";
|
||||
import { ProxyResourcesResults, updateProxyResources } from "./proxyResources";
|
||||
import {
|
||||
PublicResourcesResults,
|
||||
updatePublicResources
|
||||
} from "./publicResources";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import logger from "@server/logger";
|
||||
import { sites } from "@server/db";
|
||||
import { eq, and, isNotNull } from "drizzle-orm";
|
||||
import { addTargets as addProxyTargets } from "@server/routers/newt/targets";
|
||||
import {
|
||||
addTargets as addProxyTargets,
|
||||
sendBrowserGatewayTargets
|
||||
} from "@server/routers/newt/targets";
|
||||
import {
|
||||
ClientResourcesResults,
|
||||
updateClientResources
|
||||
} from "./clientResources";
|
||||
updatePrivateResources
|
||||
} from "./privateResources";
|
||||
import { updateResourcePolicies } from "./resourcePolicies";
|
||||
import { BlueprintSource } from "@server/routers/blueprints/types";
|
||||
import { stringify as stringifyYaml } from "yaml";
|
||||
@@ -54,18 +60,18 @@ export async function applyBlueprint({
|
||||
let error: any | null = null;
|
||||
|
||||
try {
|
||||
let proxyResourcesResults: ProxyResourcesResults = [];
|
||||
let proxyResourcesResults: PublicResourcesResults = [];
|
||||
let clientResourcesResults: ClientResourcesResults = [];
|
||||
await db.transaction(async (trx) => {
|
||||
await updateResourcePolicies(orgId, config, trx);
|
||||
|
||||
proxyResourcesResults = await updateProxyResources(
|
||||
proxyResourcesResults = await updatePublicResources(
|
||||
orgId,
|
||||
config,
|
||||
trx,
|
||||
siteId
|
||||
);
|
||||
clientResourcesResults = await updateClientResources(
|
||||
clientResourcesResults = await updatePrivateResources(
|
||||
orgId,
|
||||
config,
|
||||
trx,
|
||||
@@ -104,13 +110,27 @@ export async function applyBlueprint({
|
||||
(hc) => hc.targetId === target.targetId
|
||||
);
|
||||
|
||||
await addProxyTargets(
|
||||
site.newt.newtId,
|
||||
[target],
|
||||
matchingHealthcheck ? [matchingHealthcheck] : [],
|
||||
result.proxyResource.mode === "udp" ? "udp" : "tcp",
|
||||
site.newt.version
|
||||
);
|
||||
if (["http", "tcp", "udp"].includes(target.mode)) {
|
||||
await addProxyTargets(
|
||||
site.newt.newtId,
|
||||
[target],
|
||||
matchingHealthcheck
|
||||
? [matchingHealthcheck]
|
||||
: [],
|
||||
result.proxyResource.mode === "udp"
|
||||
? "udp"
|
||||
: "tcp",
|
||||
site.newt.version
|
||||
);
|
||||
} else if (
|
||||
["ssh", "rdp", "vnc"].includes(target.mode)
|
||||
) {
|
||||
await sendBrowserGatewayTargets(
|
||||
site.newt.newtId,
|
||||
[target],
|
||||
site.newt.version
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -105,7 +105,7 @@ export type ClientResourcesResults = {
|
||||
oldSites: { siteId: number }[];
|
||||
}[];
|
||||
|
||||
export async function updateClientResources(
|
||||
export async function updatePrivateResources(
|
||||
orgId: string,
|
||||
config: Config,
|
||||
trx: Transaction,
|
||||
@@ -48,20 +48,23 @@ import { fireHealthCheckUnknownAlert } from "@server/lib/alerts";
|
||||
import { tierMatrix } from "../billing/tierMatrix";
|
||||
import { defaultRoleAllowedActions } from "@server/routers/role/createRole";
|
||||
import { build } from "@server/build";
|
||||
import { encrypt } from "@server/lib/crypto";
|
||||
import { generateId } from "@server/auth/sessions/app";
|
||||
import serverConfig from "@server/lib/config";
|
||||
|
||||
export type ProxyResourcesResults = {
|
||||
export type PublicResourcesResults = {
|
||||
proxyResource: Resource;
|
||||
targetsToUpdate: Target[];
|
||||
healthchecksToUpdate: TargetHealthCheck[];
|
||||
}[];
|
||||
|
||||
export async function updateProxyResources(
|
||||
export async function updatePublicResources(
|
||||
orgId: string,
|
||||
config: Config,
|
||||
trx: Transaction,
|
||||
siteId?: number
|
||||
): Promise<ProxyResourcesResults> {
|
||||
const results: ProxyResourcesResults = [];
|
||||
): Promise<PublicResourcesResults> {
|
||||
const results: PublicResourcesResults = [];
|
||||
|
||||
for (const [resourceNiceId, resourceData] of Object.entries(
|
||||
config["proxy-resources"]
|
||||
@@ -80,7 +83,7 @@ export async function updateProxyResources(
|
||||
if (targetSiteId) {
|
||||
// Look up site by niceId
|
||||
[site] = await trx
|
||||
.select({ siteId: sites.siteId })
|
||||
.select({ siteId: sites.siteId, type: sites.type })
|
||||
.from(sites)
|
||||
.where(
|
||||
and(
|
||||
@@ -92,7 +95,7 @@ export async function updateProxyResources(
|
||||
} else if (siteId) {
|
||||
// Use the provided siteId directly, but verify it belongs to the org
|
||||
[site] = await trx
|
||||
.select({ siteId: sites.siteId })
|
||||
.select({ siteId: sites.siteId, type: sites.type })
|
||||
.from(sites)
|
||||
.where(
|
||||
and(eq(sites.siteId, siteId), eq(sites.orgId, orgId))
|
||||
@@ -119,6 +122,15 @@ export async function updateProxyResources(
|
||||
internalPortToCreate = targetData["internal-port"];
|
||||
}
|
||||
|
||||
let authToken: string | undefined;
|
||||
if (site.type !== "local") {
|
||||
const plainToken = generateId(48);
|
||||
authToken = encrypt(
|
||||
plainToken,
|
||||
serverConfig.getRawConfig().server.secret!
|
||||
);
|
||||
}
|
||||
|
||||
// Create target
|
||||
const [newTarget] = await trx
|
||||
.insert(targets)
|
||||
@@ -126,10 +138,12 @@ export async function updateProxyResources(
|
||||
resourceId: resourceId,
|
||||
siteId: site.siteId,
|
||||
ip: targetData.hostname,
|
||||
mode: resourceData.mode as Target["mode"],
|
||||
method: targetData.method,
|
||||
port: targetData.port,
|
||||
enabled: targetData.enabled,
|
||||
internalPort: internalPortToCreate,
|
||||
authToken: authToken,
|
||||
path: targetData.path,
|
||||
pathMatchType: targetData["path-match"],
|
||||
rewritePath:
|
||||
@@ -565,6 +579,13 @@ export async function updateProxyResources(
|
||||
? (resourceData["proxy-protocol-version"] ??
|
||||
1)
|
||||
: 1,
|
||||
pamMode:
|
||||
resourceData["auth-daemon"]?.pam ||
|
||||
"passthrough",
|
||||
authDaemonMode:
|
||||
resourceData["auth-daemon"]?.mode || "native",
|
||||
authDaemonPort:
|
||||
resourceData["auth-daemon"]?.port || 22123,
|
||||
resourcePolicyId: null,
|
||||
defaultResourcePolicyId: inlinePolicyId
|
||||
})
|
||||
@@ -707,7 +728,8 @@ export async function updateProxyResources(
|
||||
? "/"
|
||||
: undefined),
|
||||
rewritePathType: targetData["rewrite-match"],
|
||||
priority: targetData.priority
|
||||
priority: targetData.priority,
|
||||
mode: resourceData.mode
|
||||
})
|
||||
.where(eq(targets.targetId, existingTarget.targetId))
|
||||
.returning();
|
||||
@@ -37,7 +37,7 @@ export async function updateResourcePolicies(
|
||||
const results: ResourcePoliciesResults = [];
|
||||
|
||||
for (const [policyNiceId, policyData] of Object.entries(
|
||||
config["resource-policies"]
|
||||
config["public-policies"]
|
||||
)) {
|
||||
const isLicensed = await isLicensedOrSubscribed(
|
||||
orgId,
|
||||
|
||||
@@ -268,8 +268,37 @@ export const PublicResourceSchema = z
|
||||
return true;
|
||||
}
|
||||
|
||||
// If protocol/mode is http, it must have a full-domain
|
||||
if ((resource.mode ?? resource.protocol) === "http") {
|
||||
const effectiveProtocol = resource.mode ?? resource.protocol;
|
||||
if (effectiveProtocol !== "ssh") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const authDaemonMode = resource["auth-daemon"]?.mode;
|
||||
if (authDaemonMode !== "native" && authDaemonMode !== "site") {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
resource.targets.filter((target) => target != null).length <= 1
|
||||
);
|
||||
},
|
||||
{
|
||||
path: ["targets"],
|
||||
error: "When protocol is 'ssh' and auth-daemon mode is 'native' or 'site', only one target/site is allowed"
|
||||
}
|
||||
)
|
||||
.refine(
|
||||
(resource) => {
|
||||
if (isTargetsOnlyResource(resource)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If protocol/mode is http, ssh, rdp, or vnc, it must have a full-domain
|
||||
const effectiveProtocol = resource.mode ?? resource.protocol;
|
||||
if (
|
||||
effectiveProtocol !== undefined &&
|
||||
["http", "ssh", "rdp", "vnc"].includes(effectiveProtocol)
|
||||
) {
|
||||
return (
|
||||
resource["full-domain"] !== undefined &&
|
||||
resource["full-domain"].length > 0
|
||||
@@ -279,7 +308,7 @@ export const PublicResourceSchema = z
|
||||
},
|
||||
{
|
||||
path: ["full-domain"],
|
||||
error: "When protocol is 'http', a 'full-domain' must be provided"
|
||||
error: "When protocol is 'http', 'ssh', 'rdp', or 'vnc', a 'full-domain' must be provided"
|
||||
}
|
||||
)
|
||||
.refine(
|
||||
@@ -506,7 +535,44 @@ export const PrivateResourceSchema = z
|
||||
{
|
||||
message: "Destination must be a valid CIDR notation for cidr mode"
|
||||
}
|
||||
);
|
||||
)
|
||||
.refine(
|
||||
(data) => {
|
||||
if (data.mode !== "ssh") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const authDaemonMode = data["auth-daemon"]?.mode;
|
||||
if (authDaemonMode !== "native" && authDaemonMode !== "site") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const uniqueSites = new Set<string>();
|
||||
if (data.site) {
|
||||
uniqueSites.add(data.site);
|
||||
}
|
||||
for (const site of data.sites) {
|
||||
uniqueSites.add(site);
|
||||
}
|
||||
|
||||
return uniqueSites.size <= 1;
|
||||
},
|
||||
{
|
||||
path: ["sites"],
|
||||
message:
|
||||
"When mode is 'ssh' and auth-daemon mode is 'native' or 'site', only one site/target is allowed"
|
||||
}
|
||||
)
|
||||
.transform((data) => {
|
||||
if (
|
||||
data.mode === "ssh" &&
|
||||
data.destination !== undefined &&
|
||||
data["destination-port"] === undefined
|
||||
) {
|
||||
data["destination-port"] = 22;
|
||||
}
|
||||
return data;
|
||||
});
|
||||
|
||||
export const ResourcePolicyRuleSchema = RuleSchema;
|
||||
|
||||
@@ -573,7 +639,7 @@ export const ConfigSchema = z
|
||||
.record(z.string(), PrivateResourceSchema)
|
||||
.optional()
|
||||
.prefault({}),
|
||||
"resource-policies": z
|
||||
"public-policies": z
|
||||
.record(z.string(), ResourcePolicySchema)
|
||||
.optional()
|
||||
.prefault({}),
|
||||
@@ -607,7 +673,7 @@ export const ConfigSchema = z
|
||||
string,
|
||||
z.infer<typeof PrivateResourceSchema>
|
||||
>;
|
||||
"resource-policies": Record<
|
||||
"public-policies": Record<
|
||||
string,
|
||||
z.infer<typeof ResourcePolicySchema>
|
||||
>;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import z from "zod";
|
||||
import ipaddr from "ipaddr.js";
|
||||
import { COUNTRIES } from "@server/db/countries";
|
||||
import { isValidRegionId } from "@server/db/regions";
|
||||
|
||||
export function isValidCIDR(cidr: string): boolean {
|
||||
return (
|
||||
@@ -67,6 +69,45 @@ export function isValidUrlGlobPattern(pattern: string): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
export const RESOURCE_RULE_MATCH_TYPES = [
|
||||
"CIDR",
|
||||
"IP",
|
||||
"PATH",
|
||||
"COUNTRY",
|
||||
"ASN",
|
||||
"REGION"
|
||||
] as const;
|
||||
|
||||
export type ResourceRuleMatchType = (typeof RESOURCE_RULE_MATCH_TYPES)[number];
|
||||
|
||||
export function getResourceRuleValueValidationError(
|
||||
match: ResourceRuleMatchType,
|
||||
value: string
|
||||
): string | null {
|
||||
switch (match) {
|
||||
case "CIDR":
|
||||
return isValidCIDR(value) ? null : "Invalid CIDR provided";
|
||||
case "IP":
|
||||
return isValidIP(value) ? null : "Invalid IP provided";
|
||||
case "PATH":
|
||||
return isValidUrlGlobPattern(value)
|
||||
? null
|
||||
: "Invalid URL glob pattern provided";
|
||||
case "REGION":
|
||||
return isValidRegionId(value) ? null : "Invalid region ID provided";
|
||||
case "COUNTRY":
|
||||
return COUNTRIES.some((country) => country.code === value)
|
||||
? null
|
||||
: "Invalid country code provided";
|
||||
case "ASN":
|
||||
return /^AS\d+$/i.test(value.trim())
|
||||
? null
|
||||
: "Invalid ASN provided";
|
||||
default:
|
||||
return "Invalid rule match type provided";
|
||||
}
|
||||
}
|
||||
|
||||
export function isUrlValid(url: string | undefined) {
|
||||
if (!url) return true; // the link is optional in the schema so if it's empty it's valid
|
||||
var pattern = new RegExp(
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
*/
|
||||
|
||||
import {
|
||||
browserGatewayTarget,
|
||||
certificates,
|
||||
db,
|
||||
domainNamespaces,
|
||||
@@ -172,8 +171,15 @@ export async function getTraefikConfig(
|
||||
),
|
||||
inArray(sites.type, siteTypes),
|
||||
allowRawResources
|
||||
? inArray(resources.mode, ["http", "udp", "tcp"]) // allow all three
|
||||
: eq(resources.mode, "http")
|
||||
? inArray(resources.mode, [
|
||||
"http",
|
||||
"udp",
|
||||
"tcp",
|
||||
"vnc",
|
||||
"ssh",
|
||||
"rdp"
|
||||
]) // allow all three
|
||||
: inArray(resources.mode, ["http", "vnc", "ssh", "rdp"])
|
||||
)
|
||||
)
|
||||
.orderBy(desc(targets.priority), targets.targetId); // stable ordering
|
||||
@@ -181,7 +187,10 @@ export async function getTraefikConfig(
|
||||
// Group by resource and include targets with their unique site data
|
||||
const resourcesMap = new Map();
|
||||
|
||||
resourcesWithTargetsAndSites.forEach((row) => {
|
||||
for (const row of resourcesWithTargetsAndSites) {
|
||||
if (!["http", "tcp", "udp"].includes(row.mode)) {
|
||||
continue;
|
||||
}
|
||||
const resourceId = row.resourceId;
|
||||
const resourceName = sanitize(row.resourceName) || "";
|
||||
const targetPath = encodePath(row.path); // Use encodePath to avoid collisions (e.g. "/a/b" vs "/a-b")
|
||||
@@ -191,7 +200,7 @@ export async function getTraefikConfig(
|
||||
const priority = row.priority ?? 100;
|
||||
|
||||
if (filterOutNamespaceDomains && row.domainNamespaceId) {
|
||||
return;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Create a unique key combining resourceId, path config, and rewrite config
|
||||
@@ -218,7 +227,7 @@ export async function getTraefikConfig(
|
||||
logger.debug(
|
||||
`Invalid path rewrite configuration for resource ${resourceId}: ${validation.error}`
|
||||
);
|
||||
return;
|
||||
continue;
|
||||
}
|
||||
|
||||
resourcesMap.set(mapKey, {
|
||||
@@ -275,7 +284,7 @@ export async function getTraefikConfig(
|
||||
online: row.siteOnline
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Group browser gateway targets by resource
|
||||
type BrowserGatewayResourceEntry = {
|
||||
@@ -295,13 +304,12 @@ export async function getTraefikConfig(
|
||||
maintenanceMessage: string | null;
|
||||
maintenanceEstimatedTime: string | null;
|
||||
targets: {
|
||||
browserGatewayTargetId: number;
|
||||
targetId: number;
|
||||
bgType: string;
|
||||
siteId: number;
|
||||
siteType: string;
|
||||
siteOnline: boolean | null;
|
||||
subnet: string | null;
|
||||
siteExitNodeId: number | null;
|
||||
}[];
|
||||
};
|
||||
const browserGatewayResourcesMap = new Map<
|
||||
@@ -310,66 +318,10 @@ export async function getTraefikConfig(
|
||||
>();
|
||||
|
||||
if (allowBrowserGatewayResources) {
|
||||
// Query browser gateway targets for this exit node
|
||||
const browserGatewayRows = await db
|
||||
.select({
|
||||
// Resource fields
|
||||
resourceId: resources.resourceId,
|
||||
resourceName: resources.name,
|
||||
fullDomain: resources.fullDomain,
|
||||
ssl: resources.ssl,
|
||||
subdomain: resources.subdomain,
|
||||
domainId: resources.domainId,
|
||||
enabled: resources.enabled,
|
||||
wildcard: resources.wildcard,
|
||||
domainCertResolver: domains.certResolver,
|
||||
preferWildcardCert: domains.preferWildcardCert,
|
||||
domainNamespaceId: domainNamespaces.domainNamespaceId,
|
||||
// Maintenance fields
|
||||
maintenanceModeEnabled: resources.maintenanceModeEnabled,
|
||||
maintenanceModeType: resources.maintenanceModeType,
|
||||
maintenanceTitle: resources.maintenanceTitle,
|
||||
maintenanceMessage: resources.maintenanceMessage,
|
||||
maintenanceEstimatedTime: resources.maintenanceEstimatedTime,
|
||||
// Browser gateway target fields
|
||||
browserGatewayTargetId:
|
||||
browserGatewayTarget.browserGatewayTargetId,
|
||||
bgType: browserGatewayTarget.type,
|
||||
// Site fields
|
||||
siteId: sites.siteId,
|
||||
siteType: sites.type,
|
||||
siteOnline: sites.online,
|
||||
subnet: sites.subnet,
|
||||
siteExitNodeId: sites.exitNodeId
|
||||
})
|
||||
.from(browserGatewayTarget)
|
||||
.innerJoin(sites, eq(sites.siteId, browserGatewayTarget.siteId))
|
||||
.innerJoin(
|
||||
resources,
|
||||
eq(resources.resourceId, browserGatewayTarget.resourceId)
|
||||
)
|
||||
.leftJoin(domains, eq(domains.domainId, resources.domainId))
|
||||
.leftJoin(
|
||||
domainNamespaces,
|
||||
eq(domainNamespaces.domainId, resources.domainId)
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(resources.enabled, true),
|
||||
or(
|
||||
eq(sites.exitNodeId, exitNodeId),
|
||||
and(
|
||||
isNull(sites.exitNodeId),
|
||||
sql`(${siteTypes.includes("local") ? 1 : 0} = 1)`,
|
||||
eq(sites.type, "local"),
|
||||
sql`(${build != "saas" ? 1 : 0} = 1)`
|
||||
)
|
||||
),
|
||||
inArray(sites.type, siteTypes)
|
||||
)
|
||||
);
|
||||
|
||||
for (const row of browserGatewayRows) {
|
||||
for (const row of resourcesWithTargetsAndSites) {
|
||||
if (!["ssh", "vnc", "rdp"].includes(row.mode)) {
|
||||
continue;
|
||||
}
|
||||
if (filterOutNamespaceDomains && row.domainNamespaceId) {
|
||||
continue;
|
||||
}
|
||||
@@ -394,13 +346,12 @@ export async function getTraefikConfig(
|
||||
});
|
||||
}
|
||||
browserGatewayResourcesMap.get(row.resourceId)!.targets.push({
|
||||
browserGatewayTargetId: row.browserGatewayTargetId,
|
||||
bgType: row.bgType,
|
||||
targetId: row.targetId,
|
||||
bgType: row.mode,
|
||||
siteId: row.siteId,
|
||||
siteType: row.siteType,
|
||||
siteOnline: row.siteOnline,
|
||||
subnet: row.subnet,
|
||||
siteExitNodeId: row.siteExitNodeId
|
||||
subnet: row.subnet
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,187 +0,0 @@
|
||||
/*
|
||||
* This file is part of a proprietary work.
|
||||
*
|
||||
* Copyright (c) 2025-2026 Fossorial, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This file is licensed under the Fossorial Commercial License.
|
||||
* You may not use this file except in compliance with the License.
|
||||
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
|
||||
*
|
||||
* This file is not licensed under the AGPLv3.
|
||||
*/
|
||||
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
browserGatewayTarget,
|
||||
BrowserGatewayTarget,
|
||||
db,
|
||||
newts,
|
||||
resources,
|
||||
sites
|
||||
} from "@server/db";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import logger from "@server/logger";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { encrypt } from "@server/lib/crypto";
|
||||
import config from "@server/lib/config";
|
||||
import { sendBrowserGatewayTargets } from "@server/routers/newt/targets";
|
||||
import { generateId } from "@server/auth/sessions/app";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().nonempty(),
|
||||
resourceId: z.string().transform(Number).pipe(z.number().int().positive())
|
||||
});
|
||||
|
||||
const bodySchema = z.strictObject({
|
||||
siteId: z.number().int().positive(),
|
||||
type: z.enum(["ssh", "rdp", "vnc"]),
|
||||
destination: z.string().nonempty(),
|
||||
destinationPort: z.number().int().min(1).max(65535)
|
||||
});
|
||||
|
||||
export type CreateBrowserGatewayTargetResponse = BrowserGatewayTarget;
|
||||
|
||||
registry.registerPath({
|
||||
method: "put",
|
||||
path: "/org/{orgId}/resource/{resourceId}/browser-gateway-target",
|
||||
description: "Create a browser gateway target for a resource.",
|
||||
tags: [OpenAPITags.Org],
|
||||
request: {
|
||||
params: paramsSchema,
|
||||
body: {
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: bodySchema
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
});
|
||||
|
||||
export async function createBrowserGatewayTarget(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId, resourceId } = parsedParams.data;
|
||||
|
||||
const parsedBody = bodySchema.safeParse(req.body);
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedBody.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { siteId, type, destination, destinationPort } = parsedBody.data;
|
||||
|
||||
const [resource] = await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.where(
|
||||
and(
|
||||
eq(resources.resourceId, resourceId),
|
||||
eq(resources.orgId, orgId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!resource) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Resource with ID ${resourceId} not found in organization ${orgId}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const [site] = await db
|
||||
.select()
|
||||
.from(sites)
|
||||
.where(and(eq(sites.siteId, siteId), eq(sites.orgId, orgId)))
|
||||
.limit(1);
|
||||
|
||||
if (!site) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Site with ID ${siteId} not found in organization ${orgId}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const plainToken = generateId(48);
|
||||
const encryptedToken = encrypt(
|
||||
plainToken,
|
||||
config.getRawConfig().server.secret!
|
||||
);
|
||||
|
||||
const [record] = await db
|
||||
.insert(browserGatewayTarget)
|
||||
.values({
|
||||
resourceId,
|
||||
siteId,
|
||||
type,
|
||||
destination,
|
||||
destinationPort,
|
||||
authToken: encryptedToken
|
||||
})
|
||||
.returning();
|
||||
|
||||
if (site.type === "newt") {
|
||||
const [newt] = await db
|
||||
.select()
|
||||
.from(newts)
|
||||
.where(eq(newts.siteId, siteId))
|
||||
.limit(1);
|
||||
|
||||
if (newt) {
|
||||
await sendBrowserGatewayTargets(
|
||||
newt.newtId,
|
||||
[record],
|
||||
newt.version
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`Created browser gateway target ${record.browserGatewayTargetId} for resource ${resourceId}`
|
||||
);
|
||||
|
||||
return response<CreateBrowserGatewayTargetResponse>(res, {
|
||||
data: record,
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Browser gateway target created successfully",
|
||||
status: HttpCode.CREATED
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.INTERNAL_SERVER_ERROR,
|
||||
"Failed to create browser gateway target"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
/*
|
||||
* This file is part of a proprietary work.
|
||||
*
|
||||
* Copyright (c) 2025-2026 Fossorial, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This file is licensed under the Fossorial Commercial License.
|
||||
* You may not use this file except in compliance with the License.
|
||||
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
|
||||
*
|
||||
* This file is not licensed under the AGPLv3.
|
||||
*/
|
||||
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { browserGatewayTarget, db, newts, sites } from "@server/db";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import logger from "@server/logger";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { removeBrowserGatewayTarget } from "@server/routers/newt/targets";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().nonempty(),
|
||||
browserGatewayTargetId: z
|
||||
.string()
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().positive())
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "delete",
|
||||
path: "/org/{orgId}/browser-gateway-target/{browserGatewayTargetId}",
|
||||
description: "Delete a browser gateway target.",
|
||||
tags: [OpenAPITags.Org],
|
||||
request: {
|
||||
params: paramsSchema
|
||||
},
|
||||
responses: {}
|
||||
});
|
||||
|
||||
export async function deleteBrowserGatewayTarget(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId, browserGatewayTargetId } = parsedParams.data;
|
||||
|
||||
const [existing] = await db
|
||||
.select({ bgt: browserGatewayTarget, site: sites })
|
||||
.from(browserGatewayTarget)
|
||||
.innerJoin(sites, eq(sites.siteId, browserGatewayTarget.siteId))
|
||||
.where(
|
||||
and(
|
||||
eq(
|
||||
browserGatewayTarget.browserGatewayTargetId,
|
||||
browserGatewayTargetId
|
||||
),
|
||||
eq(sites.orgId, orgId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!existing) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Browser gateway target with ID ${browserGatewayTargetId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(browserGatewayTarget)
|
||||
.where(
|
||||
eq(
|
||||
browserGatewayTarget.browserGatewayTargetId,
|
||||
browserGatewayTargetId
|
||||
)
|
||||
);
|
||||
|
||||
if (existing.site.type === "newt") {
|
||||
const [newt] = await db
|
||||
.select()
|
||||
.from(newts)
|
||||
.where(eq(newts.siteId, existing.bgt.siteId))
|
||||
.limit(1);
|
||||
|
||||
if (newt) {
|
||||
await removeBrowserGatewayTarget(
|
||||
newt.newtId,
|
||||
browserGatewayTargetId,
|
||||
newt.version
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(`Deleted browser gateway target ${browserGatewayTargetId}`);
|
||||
|
||||
return response(res, {
|
||||
data: null,
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Browser gateway target deleted successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.INTERNAL_SERVER_ERROR,
|
||||
"Failed to delete browser gateway target"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
/*
|
||||
* This file is part of a proprietary work.
|
||||
*
|
||||
* Copyright (c) 2025-2026 Fossorial, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This file is licensed under the Fossorial Commercial License.
|
||||
* You may not use this file except in compliance with the License.
|
||||
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
|
||||
*
|
||||
* This file is not licensed under the AGPLv3.
|
||||
*/
|
||||
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
browserGatewayTarget,
|
||||
BrowserGatewayTarget,
|
||||
db,
|
||||
sites
|
||||
} from "@server/db";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import logger from "@server/logger";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().nonempty(),
|
||||
browserGatewayTargetId: z
|
||||
.string()
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().positive())
|
||||
});
|
||||
|
||||
export type GetBrowserGatewayTargetResponse = BrowserGatewayTarget;
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/org/{orgId}/browser-gateway-target/{browserGatewayTargetId}",
|
||||
description: "Get a browser gateway target.",
|
||||
tags: [OpenAPITags.Org],
|
||||
request: {
|
||||
params: paramsSchema
|
||||
},
|
||||
responses: {}
|
||||
});
|
||||
|
||||
export async function getBrowserGatewayTarget(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId, browserGatewayTargetId } = parsedParams.data;
|
||||
|
||||
const [result] = await db
|
||||
.select({ bgt: browserGatewayTarget })
|
||||
.from(browserGatewayTarget)
|
||||
.innerJoin(sites, eq(sites.siteId, browserGatewayTarget.siteId))
|
||||
.where(
|
||||
and(
|
||||
eq(
|
||||
browserGatewayTarget.browserGatewayTargetId,
|
||||
browserGatewayTargetId
|
||||
),
|
||||
eq(sites.orgId, orgId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!result) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Browser gateway target with ID ${browserGatewayTargetId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return response<GetBrowserGatewayTargetResponse>(res, {
|
||||
data: result.bgt,
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Browser gateway target retrieved successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.INTERNAL_SERVER_ERROR,
|
||||
"Failed to retrieve browser gateway target"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -13,9 +13,8 @@
|
||||
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { browserGatewayTarget, db } from "@server/db";
|
||||
import { resources, targets } from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db, resources, targets } from "@server/db";
|
||||
import { eq, and, inArray } from "drizzle-orm";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -51,11 +50,11 @@ export async function getBrowserTarget(
|
||||
|
||||
logger.info(`Retrieving browser target for domain: ${fullDomain}`);
|
||||
|
||||
const [browserTarget] = await db
|
||||
const [row] = await db
|
||||
.select({
|
||||
destination: browserGatewayTarget.destination,
|
||||
destinationPort: browserGatewayTarget.destinationPort,
|
||||
authToken: browserGatewayTarget.authToken,
|
||||
ip: targets.ip,
|
||||
port: targets.port,
|
||||
authToken: targets.authToken,
|
||||
resourceId: resources.resourceId,
|
||||
niceId: resources.niceId,
|
||||
name: resources.name,
|
||||
@@ -63,20 +62,18 @@ export async function getBrowserTarget(
|
||||
pamMode: resources.pamMode,
|
||||
authDaemonMode: resources.authDaemonMode
|
||||
})
|
||||
.from(browserGatewayTarget)
|
||||
.innerJoin(
|
||||
resources,
|
||||
eq(browserGatewayTarget.resourceId, resources.resourceId)
|
||||
.from(targets)
|
||||
.innerJoin(resources, eq(targets.resourceId, resources.resourceId))
|
||||
.where(
|
||||
and(
|
||||
eq(resources.fullDomain, fullDomain),
|
||||
eq(targets.enabled, true),
|
||||
inArray(targets.mode, ["ssh", "rdp", "vnc"])
|
||||
)
|
||||
)
|
||||
.where(eq(resources.fullDomain, fullDomain))
|
||||
.limit(1);
|
||||
|
||||
const decryptedAuthToken = decrypt(
|
||||
browserTarget.authToken,
|
||||
config.getRawConfig().server.secret!
|
||||
);
|
||||
|
||||
if (!browserTarget) {
|
||||
if (!row) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
@@ -85,17 +82,21 @@ export async function getBrowserTarget(
|
||||
);
|
||||
}
|
||||
|
||||
const decryptedAuthToken = row.authToken
|
||||
? decrypt(row.authToken, config.getRawConfig().server.secret!)
|
||||
: "";
|
||||
|
||||
return response<GetBrowserTargetResponse>(res, {
|
||||
data: {
|
||||
ip: browserTarget.destination,
|
||||
port: browserTarget.destinationPort,
|
||||
ip: row.ip,
|
||||
port: row.port,
|
||||
authToken: decryptedAuthToken,
|
||||
pamMode: browserTarget.pamMode,
|
||||
authDaemonMode: browserTarget.authDaemonMode,
|
||||
orgId: browserTarget.orgId,
|
||||
resourceId: browserTarget.resourceId,
|
||||
niceId: browserTarget.niceId,
|
||||
name: browserTarget.name
|
||||
pamMode: row.pamMode,
|
||||
authDaemonMode: row.authDaemonMode,
|
||||
orgId: row.orgId,
|
||||
resourceId: row.resourceId,
|
||||
niceId: row.niceId,
|
||||
name: row.name ?? ""
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
|
||||
@@ -11,9 +11,4 @@
|
||||
* This file is not licensed under the AGPLv3.
|
||||
*/
|
||||
|
||||
export * from "./createBrowserGatewayTarget";
|
||||
export * from "./updateBrowserGatewayTarget";
|
||||
export * from "./deleteBrowserGatewayTarget";
|
||||
export * from "./getBrowserGatewayTarget";
|
||||
export * from "./listBrowserGatewayTargets";
|
||||
export * from "./getBrowserTarget";
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
/*
|
||||
* This file is part of a proprietary work.
|
||||
*
|
||||
* Copyright (c) 2025-2026 Fossorial, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This file is licensed under the Fossorial Commercial License.
|
||||
* You may not use this file except in compliance with the License.
|
||||
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
|
||||
*
|
||||
* This file is not licensed under the AGPLv3.
|
||||
*/
|
||||
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
browserGatewayTarget,
|
||||
BrowserGatewayTarget,
|
||||
db,
|
||||
resources,
|
||||
sites
|
||||
} from "@server/db";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import logger from "@server/logger";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().nonempty(),
|
||||
resourceId: z.string().transform(Number).pipe(z.number().int().positive())
|
||||
});
|
||||
|
||||
const querySchema = z.object({
|
||||
limit: z
|
||||
.string()
|
||||
.optional()
|
||||
.default("1000")
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().positive()),
|
||||
offset: z
|
||||
.string()
|
||||
.optional()
|
||||
.default("0")
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().nonnegative())
|
||||
});
|
||||
|
||||
export type ListBrowserGatewayTargetsResponse = {
|
||||
targets: BrowserGatewayTarget[];
|
||||
total: number;
|
||||
limit: number;
|
||||
offset: number;
|
||||
};
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/org/{orgId}/resource/{resourceId}/browser-gateway-targets",
|
||||
description: "List browser gateway targets for a resource.",
|
||||
tags: [OpenAPITags.Org],
|
||||
request: {
|
||||
params: paramsSchema,
|
||||
query: querySchema
|
||||
},
|
||||
responses: {}
|
||||
});
|
||||
|
||||
export async function listBrowserGatewayTargets(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId, resourceId } = parsedParams.data;
|
||||
|
||||
const parsedQuery = querySchema.safeParse(req.query);
|
||||
if (!parsedQuery.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedQuery.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { limit, offset } = parsedQuery.data;
|
||||
|
||||
const [resource] = await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.where(
|
||||
and(
|
||||
eq(resources.resourceId, resourceId),
|
||||
eq(resources.orgId, orgId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!resource) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Resource with ID ${resourceId} not found in organization ${orgId}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
browserGatewayTargetId:
|
||||
browserGatewayTarget.browserGatewayTargetId,
|
||||
resourceId: browserGatewayTarget.resourceId,
|
||||
siteId: browserGatewayTarget.siteId,
|
||||
authToken: browserGatewayTarget.authToken,
|
||||
type: browserGatewayTarget.type,
|
||||
destination: browserGatewayTarget.destination,
|
||||
destinationPort: browserGatewayTarget.destinationPort,
|
||||
siteName: sites.name
|
||||
})
|
||||
.from(browserGatewayTarget)
|
||||
.leftJoin(sites, eq(sites.siteId, browserGatewayTarget.siteId))
|
||||
.where(eq(browserGatewayTarget.resourceId, resourceId))
|
||||
.limit(limit)
|
||||
.offset(offset);
|
||||
|
||||
return response<ListBrowserGatewayTargetsResponse>(res, {
|
||||
data: {
|
||||
targets: rows as any,
|
||||
total: rows.length,
|
||||
limit,
|
||||
offset
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Browser gateway targets retrieved successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.INTERNAL_SERVER_ERROR,
|
||||
"Failed to list browser gateway targets"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
/*
|
||||
* This file is part of a proprietary work.
|
||||
*
|
||||
* Copyright (c) 2025-2026 Fossorial, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This file is licensed under the Fossorial Commercial License.
|
||||
* You may not use this file except in compliance with the License.
|
||||
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
|
||||
*
|
||||
* This file is not licensed under the AGPLv3.
|
||||
*/
|
||||
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
browserGatewayTarget,
|
||||
BrowserGatewayTarget,
|
||||
db,
|
||||
newts,
|
||||
sites
|
||||
} from "@server/db";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import logger from "@server/logger";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { sendBrowserGatewayTargets } from "@server/routers/newt/targets";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().nonempty(),
|
||||
browserGatewayTargetId: z
|
||||
.string()
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().positive())
|
||||
});
|
||||
|
||||
const bodySchema = z.strictObject({
|
||||
siteId: z.number().int().positive().optional(),
|
||||
type: z.enum(["ssh", "rdp", "vnc"]).optional(),
|
||||
destination: z.string().nonempty().optional(),
|
||||
destinationPort: z.number().int().min(1).max(65535).optional()
|
||||
});
|
||||
|
||||
export type UpdateBrowserGatewayTargetResponse = BrowserGatewayTarget;
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/org/{orgId}/browser-gateway-target/{browserGatewayTargetId}",
|
||||
description: "Update a browser gateway target.",
|
||||
tags: [OpenAPITags.Org],
|
||||
request: {
|
||||
params: paramsSchema,
|
||||
body: {
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: bodySchema
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
});
|
||||
|
||||
export async function updateBrowserGatewayTarget(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId, browserGatewayTargetId } = parsedParams.data;
|
||||
|
||||
const parsedBody = bodySchema.safeParse(req.body);
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedBody.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { siteId, type, destination, destinationPort } = parsedBody.data;
|
||||
|
||||
const [existing] = await db
|
||||
.select({ bgt: browserGatewayTarget, site: sites })
|
||||
.from(browserGatewayTarget)
|
||||
.innerJoin(sites, eq(sites.siteId, browserGatewayTarget.siteId))
|
||||
.where(
|
||||
and(
|
||||
eq(
|
||||
browserGatewayTarget.browserGatewayTargetId,
|
||||
browserGatewayTargetId
|
||||
),
|
||||
eq(sites.orgId, orgId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!existing) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Browser gateway target with ID ${browserGatewayTargetId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const updateValues: Partial<BrowserGatewayTarget> = {};
|
||||
if (siteId !== undefined) updateValues.siteId = siteId;
|
||||
if (type !== undefined) updateValues.type = type;
|
||||
if (destination !== undefined) updateValues.destination = destination;
|
||||
if (destinationPort !== undefined)
|
||||
updateValues.destinationPort = destinationPort;
|
||||
|
||||
const [updated] = await db
|
||||
.update(browserGatewayTarget)
|
||||
.set(updateValues)
|
||||
.where(
|
||||
eq(
|
||||
browserGatewayTarget.browserGatewayTargetId,
|
||||
browserGatewayTargetId
|
||||
)
|
||||
)
|
||||
.returning();
|
||||
|
||||
const targetSiteId = siteId ?? existing.bgt.siteId;
|
||||
const [site] = await db
|
||||
.select()
|
||||
.from(sites)
|
||||
.where(eq(sites.siteId, targetSiteId))
|
||||
.limit(1);
|
||||
|
||||
if (site && site.type === "newt") {
|
||||
const [newt] = await db
|
||||
.select()
|
||||
.from(newts)
|
||||
.where(eq(newts.siteId, targetSiteId))
|
||||
.limit(1);
|
||||
|
||||
if (newt) {
|
||||
await sendBrowserGatewayTargets(
|
||||
newt.newtId,
|
||||
[updated],
|
||||
newt.version
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(`Updated browser gateway target ${browserGatewayTargetId}`);
|
||||
|
||||
return response<UpdateBrowserGatewayTargetResponse>(res, {
|
||||
data: updated,
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Browser gateway target updated successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.INTERNAL_SERVER_ERROR,
|
||||
"Failed to update browser gateway target"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,6 @@ import * as siteProvisioning from "#private/routers/siteProvisioning";
|
||||
import * as eventStreamingDestination from "#private/routers/eventStreamingDestination";
|
||||
import * as alertRule from "#private/routers/alertRule";
|
||||
import * as healthChecks from "#private/routers/healthChecks";
|
||||
import * as browserGatewayTarget from "#private/routers/browserGatewayTarget";
|
||||
import * as labels from "#private/routers/labels";
|
||||
import * as client from "@server/routers/client";
|
||||
import * as resource from "#private/routers/resource";
|
||||
@@ -879,48 +878,3 @@ authenticated.post(
|
||||
verifyClientAccess,
|
||||
client.rebuildClientAssociationsCacheRoute
|
||||
);
|
||||
|
||||
authenticated.put(
|
||||
"/org/:orgId/resource/:resourceId/browser-gateway-target",
|
||||
verifyValidLicense,
|
||||
verifyOrgAccess,
|
||||
verifyLimits,
|
||||
verifyUserHasAction(ActionsEnum.createBrowserGatewayTarget),
|
||||
logActionAudit(ActionsEnum.createBrowserGatewayTarget),
|
||||
browserGatewayTarget.createBrowserGatewayTarget
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/resource/:resourceId/browser-gateway-targets",
|
||||
verifyValidLicense,
|
||||
verifyOrgAccess,
|
||||
verifyUserHasAction(ActionsEnum.listBrowserGatewayTargets),
|
||||
browserGatewayTarget.listBrowserGatewayTargets
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/browser-gateway-target/:browserGatewayTargetId",
|
||||
verifyValidLicense,
|
||||
verifyOrgAccess,
|
||||
verifyUserHasAction(ActionsEnum.getBrowserGatewayTarget),
|
||||
browserGatewayTarget.getBrowserGatewayTarget
|
||||
);
|
||||
|
||||
authenticated.post(
|
||||
"/org/:orgId/browser-gateway-target/:browserGatewayTargetId",
|
||||
verifyValidLicense,
|
||||
verifyOrgAccess,
|
||||
verifyLimits,
|
||||
verifyUserHasAction(ActionsEnum.updateBrowserGatewayTarget),
|
||||
logActionAudit(ActionsEnum.updateBrowserGatewayTarget),
|
||||
browserGatewayTarget.updateBrowserGatewayTarget
|
||||
);
|
||||
|
||||
authenticated.delete(
|
||||
"/org/:orgId/browser-gateway-target/:browserGatewayTargetId",
|
||||
verifyValidLicense,
|
||||
verifyOrgAccess,
|
||||
verifyUserHasAction(ActionsEnum.deleteBrowserGatewayTarget),
|
||||
logActionAudit(ActionsEnum.deleteBrowserGatewayTarget),
|
||||
browserGatewayTarget.deleteBrowserGatewayTarget
|
||||
);
|
||||
|
||||
@@ -16,7 +16,6 @@ import * as org from "#private/routers/org";
|
||||
import * as logs from "#private/routers/auditLogs";
|
||||
import * as alertEvents from "#private/routers/alertEvents";
|
||||
import * as certificates from "#private/routers/certificates";
|
||||
import * as browserGatewayTarget from "#private/routers/browserGatewayTarget";
|
||||
|
||||
import {
|
||||
verifyApiKeyHasAction,
|
||||
@@ -216,43 +215,3 @@ authenticated.delete(
|
||||
logActionAudit(ActionsEnum.removeUserRole),
|
||||
user.removeUserRole
|
||||
);
|
||||
|
||||
authenticated.put(
|
||||
"/org/:orgId/resource/:resourceId/browser-gateway-target",
|
||||
verifyApiKeyOrgAccess,
|
||||
verifyLimits,
|
||||
verifyApiKeyHasAction(ActionsEnum.createBrowserGatewayTarget),
|
||||
logActionAudit(ActionsEnum.createBrowserGatewayTarget),
|
||||
browserGatewayTarget.createBrowserGatewayTarget
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/resource/:resourceId/browser-gateway-targets",
|
||||
verifyApiKeyOrgAccess,
|
||||
verifyApiKeyHasAction(ActionsEnum.listBrowserGatewayTargets),
|
||||
browserGatewayTarget.listBrowserGatewayTargets
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/browser-gateway-target/:browserGatewayTargetId",
|
||||
verifyApiKeyOrgAccess,
|
||||
verifyApiKeyHasAction(ActionsEnum.getBrowserGatewayTarget),
|
||||
browserGatewayTarget.getBrowserGatewayTarget
|
||||
);
|
||||
|
||||
authenticated.post(
|
||||
"/org/:orgId/browser-gateway-target/:browserGatewayTargetId",
|
||||
verifyApiKeyOrgAccess,
|
||||
verifyLimits,
|
||||
verifyApiKeyHasAction(ActionsEnum.updateBrowserGatewayTarget),
|
||||
logActionAudit(ActionsEnum.updateBrowserGatewayTarget),
|
||||
browserGatewayTarget.updateBrowserGatewayTarget
|
||||
);
|
||||
|
||||
authenticated.delete(
|
||||
"/org/:orgId/browser-gateway-target/:browserGatewayTargetId",
|
||||
verifyApiKeyOrgAccess,
|
||||
verifyApiKeyHasAction(ActionsEnum.deleteBrowserGatewayTarget),
|
||||
logActionAudit(ActionsEnum.deleteBrowserGatewayTarget),
|
||||
browserGatewayTarget.deleteBrowserGatewayTarget
|
||||
);
|
||||
|
||||
@@ -17,9 +17,9 @@ import * as orgIdp from "#private/routers/orgIdp";
|
||||
import * as billing from "#private/routers/billing";
|
||||
import * as license from "#private/routers/license";
|
||||
import * as resource from "#private/routers/resource";
|
||||
import * as browserTarget from "#private/routers/browserGatewayTarget";
|
||||
import * as ssh from "#private/routers/ssh";
|
||||
import * as ws from "@server/routers/ws";
|
||||
import * as browserTarget from "#private/routers/browserGatewayTarget";
|
||||
|
||||
import {
|
||||
verifySessionUserMiddleware,
|
||||
|
||||
@@ -33,9 +33,8 @@ import {
|
||||
import { getUniqueResourcePolicyName } from "@server/db/names";
|
||||
import response from "@server/lib/response";
|
||||
import {
|
||||
isValidCIDR,
|
||||
isValidIP,
|
||||
isValidUrlGlobPattern
|
||||
getResourceRuleValueValidationError,
|
||||
RESOURCE_RULE_MATCH_TYPES
|
||||
} from "@server/lib/validators";
|
||||
import logger from "@server/logger";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
@@ -56,9 +55,9 @@ const ruleSchema = z.strictObject({
|
||||
enum: ["ACCEPT", "DROP", "PASS"],
|
||||
description: "rule action"
|
||||
}),
|
||||
match: z.enum(["CIDR", "IP", "PATH"]).openapi({
|
||||
match: z.enum(RESOURCE_RULE_MATCH_TYPES).openapi({
|
||||
type: "string",
|
||||
enum: ["CIDR", "IP", "PATH"],
|
||||
enum: [...RESOURCE_RULE_MATCH_TYPES],
|
||||
description: "rule match"
|
||||
}),
|
||||
value: z.string().min(1),
|
||||
@@ -261,26 +260,13 @@ export async function createResourcePolicy(
|
||||
const niceId = await getUniqueResourcePolicyName(orgId);
|
||||
|
||||
for (const rule of rules) {
|
||||
if (rule.match === "CIDR" && !isValidCIDR(rule.value)) {
|
||||
const validationError = getResourceRuleValueValidationError(
|
||||
rule.match,
|
||||
rule.value
|
||||
);
|
||||
if (validationError) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Invalid CIDR provided"
|
||||
)
|
||||
);
|
||||
} else if (rule.match === "IP" && !isValidIP(rule.value)) {
|
||||
return next(
|
||||
createHttpError(HttpCode.BAD_REQUEST, "Invalid IP provided")
|
||||
);
|
||||
} else if (
|
||||
rule.match === "PATH" &&
|
||||
!isValidUrlGlobPattern(rule.value)
|
||||
) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Invalid URL glob pattern provided"
|
||||
)
|
||||
createHttpError(HttpCode.BAD_REQUEST, validationError)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,6 +216,7 @@ export async function listResourcePolicies(
|
||||
: await db
|
||||
.select({
|
||||
resourceId: resources.resourceId,
|
||||
niceId: resources.niceId,
|
||||
name: resources.name,
|
||||
fullDomain: resources.fullDomain,
|
||||
resourcePolicyId: resources.resourcePolicyId
|
||||
|
||||
@@ -30,8 +30,7 @@ import {
|
||||
userOrgs,
|
||||
sites,
|
||||
Resource,
|
||||
SiteResource,
|
||||
browserGatewayTarget
|
||||
SiteResource
|
||||
} from "@server/db";
|
||||
import { logAccessAudit } from "#private/lib/logAccessAudit";
|
||||
import { isLicensedOrSubscribed } from "#private/lib/isLicencedOrSubscribed";
|
||||
@@ -291,16 +290,15 @@ export async function signSshKey(
|
||||
const publicResource = resource as Resource;
|
||||
const targetRows = await db
|
||||
.select({
|
||||
siteId: browserGatewayTarget.siteId,
|
||||
ip: browserGatewayTarget.destination
|
||||
siteId: targets.siteId,
|
||||
ip: targets.ip
|
||||
})
|
||||
.from(browserGatewayTarget)
|
||||
.from(targets)
|
||||
.where(
|
||||
and(
|
||||
eq(
|
||||
browserGatewayTarget.resourceId,
|
||||
publicResource.resourceId
|
||||
)
|
||||
eq(targets.resourceId, publicResource.resourceId),
|
||||
eq(targets.enabled, true),
|
||||
eq(targets.mode, "ssh")
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
@@ -666,6 +666,13 @@ authenticated.get(
|
||||
resource.getResourcePolicies
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/resource-policy/:resourcePolicyId",
|
||||
verifyResourcePolicyAccess,
|
||||
verifyUserHasAction(ActionsEnum.getResourcePolicy),
|
||||
policy.getResourcePolicy
|
||||
);
|
||||
|
||||
authenticated.put(
|
||||
"/resource-policy/:resourcePolicyId",
|
||||
verifyResourcePolicyAccess,
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import {
|
||||
browserGatewayTarget,
|
||||
BrowserGatewayTarget,
|
||||
clients,
|
||||
clientSiteResourcesAssociationsCache,
|
||||
clientSitesAssociationsCache,
|
||||
@@ -16,7 +14,7 @@ import {
|
||||
} from "@server/db";
|
||||
import logger from "@server/logger";
|
||||
import { initPeerAddHandshake, updatePeer } from "../olm/peers";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { eq, and, inArray } from "drizzle-orm";
|
||||
import config from "@server/lib/config";
|
||||
import { decrypt } from "@server/lib/crypto";
|
||||
import {
|
||||
@@ -211,7 +209,13 @@ export async function buildTargetConfigurationForNewtClient(
|
||||
})
|
||||
.from(targets)
|
||||
.innerJoin(resources, eq(targets.resourceId, resources.resourceId))
|
||||
.where(and(eq(targets.siteId, siteId), eq(targets.enabled, true)));
|
||||
.where(
|
||||
and(
|
||||
eq(targets.siteId, siteId),
|
||||
eq(targets.enabled, true),
|
||||
inArray(targets.mode, ["http", "udp", "tcp"])
|
||||
)
|
||||
);
|
||||
|
||||
const allHealthChecks = await db
|
||||
.select({
|
||||
@@ -236,10 +240,27 @@ export async function buildTargetConfigurationForNewtClient(
|
||||
.from(targetHealthCheck)
|
||||
.where(eq(targetHealthCheck.siteId, siteId));
|
||||
|
||||
// Get all enabled targets with their resource mode information
|
||||
const allBrowserGatewayTargets = await db
|
||||
.select()
|
||||
.from(browserGatewayTarget)
|
||||
.where(eq(browserGatewayTarget.siteId, siteId));
|
||||
.select({
|
||||
resourceId: targets.resourceId,
|
||||
targetId: targets.targetId,
|
||||
ip: targets.ip,
|
||||
method: targets.method,
|
||||
port: targets.port,
|
||||
enabled: targets.enabled,
|
||||
mode: resources.mode,
|
||||
authToken: targets.authToken
|
||||
})
|
||||
.from(targets)
|
||||
.innerJoin(resources, eq(targets.resourceId, resources.resourceId))
|
||||
.where(
|
||||
and(
|
||||
eq(targets.siteId, siteId),
|
||||
eq(targets.enabled, true),
|
||||
inArray(targets.mode, ["ssh", "rdp", "vnc"])
|
||||
)
|
||||
);
|
||||
|
||||
const { tcpTargets, udpTargets } = allTargets.reduce(
|
||||
(acc, target) => {
|
||||
@@ -315,12 +336,15 @@ export async function buildTargetConfigurationForNewtClient(
|
||||
|
||||
const serverSecret = config.getRawConfig().server.secret!;
|
||||
const browserGatewayTargets = allBrowserGatewayTargets.map((t) => {
|
||||
if (!t.ip || !t.port || !t.authToken) {
|
||||
return null;
|
||||
}
|
||||
const decryptAuthToken = decrypt(t.authToken, serverSecret);
|
||||
return {
|
||||
id: t.browserGatewayTargetId,
|
||||
type: t.type,
|
||||
destination: t.destination,
|
||||
destinationPort: t.destinationPort,
|
||||
id: t.targetId,
|
||||
type: t.mode,
|
||||
destination: t.ip,
|
||||
destinationPort: t.port,
|
||||
authToken: decryptAuthToken
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { BrowserGatewayTarget, Target, TargetHealthCheck } from "@server/db";
|
||||
import { Target, TargetHealthCheck } from "@server/db";
|
||||
import { sendToClient } from "#dynamic/routers/ws";
|
||||
import logger from "@server/logger";
|
||||
import { canCompress } from "@server/lib/clientVersionChecks";
|
||||
@@ -244,23 +244,27 @@ export async function removeTargets(
|
||||
|
||||
export async function sendBrowserGatewayTargets(
|
||||
newtId: string,
|
||||
targets: BrowserGatewayTarget[],
|
||||
targets: Target[],
|
||||
version?: string | null
|
||||
) {
|
||||
if (targets.length === 0) return;
|
||||
|
||||
const payload = targets.map((t) => {
|
||||
// filter out the ones without auth tokens
|
||||
const filteredTargets = targets.filter((t) => t.authToken);
|
||||
if (filteredTargets.length === 0) return;
|
||||
|
||||
const payload = filteredTargets.map((t) => {
|
||||
const decryptAuthToken = decrypt(
|
||||
t.authToken,
|
||||
t.authToken!,
|
||||
config.getRawConfig().server.secret!
|
||||
);
|
||||
return {
|
||||
id: t.browserGatewayTargetId,
|
||||
id: t.targetId,
|
||||
resourceId: t.resourceId,
|
||||
siteId: t.siteId,
|
||||
type: t.type,
|
||||
destination: t.destination,
|
||||
destinationPort: t.destinationPort,
|
||||
type: t.mode,
|
||||
destination: t.ip,
|
||||
destinationPort: t.port,
|
||||
authToken: decryptAuthToken
|
||||
};
|
||||
});
|
||||
|
||||
@@ -8,9 +8,8 @@ import createHttpError from "http-errors";
|
||||
import logger from "@server/logger";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import {
|
||||
isValidCIDR,
|
||||
isValidIP,
|
||||
isValidUrlGlobPattern
|
||||
getResourceRuleValueValidationError,
|
||||
RESOURCE_RULE_MATCH_TYPES
|
||||
} from "@server/lib/validators";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
|
||||
@@ -20,9 +19,9 @@ const ruleSchema = z.strictObject({
|
||||
enum: ["ACCEPT", "DROP", "PASS"],
|
||||
description: "rule action"
|
||||
}),
|
||||
match: z.enum(["CIDR", "IP", "PATH"]).openapi({
|
||||
match: z.enum(RESOURCE_RULE_MATCH_TYPES).openapi({
|
||||
type: "string",
|
||||
enum: ["CIDR", "IP", "PATH"],
|
||||
enum: [...RESOURCE_RULE_MATCH_TYPES],
|
||||
description: "rule match"
|
||||
}),
|
||||
value: z.string().min(1),
|
||||
@@ -105,26 +104,13 @@ export async function setResourcePolicyRules(
|
||||
}
|
||||
|
||||
for (const rule of rules) {
|
||||
if (rule.match === "CIDR" && !isValidCIDR(rule.value)) {
|
||||
const validationError = getResourceRuleValueValidationError(
|
||||
rule.match,
|
||||
rule.value
|
||||
);
|
||||
if (validationError) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Invalid CIDR provided"
|
||||
)
|
||||
);
|
||||
} else if (rule.match === "IP" && !isValidIP(rule.value)) {
|
||||
return next(
|
||||
createHttpError(HttpCode.BAD_REQUEST, "Invalid IP provided")
|
||||
);
|
||||
} else if (
|
||||
rule.match === "PATH" &&
|
||||
!isValidUrlGlobPattern(rule.value)
|
||||
) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Invalid URL glob pattern provided"
|
||||
)
|
||||
createHttpError(HttpCode.BAD_REQUEST, validationError)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import {
|
||||
browserGatewayTarget,
|
||||
alias,
|
||||
db,
|
||||
labels,
|
||||
resourceHeaderAuth,
|
||||
resourceHeaderAuthExtendedCompatibility,
|
||||
resourceLabels,
|
||||
resourcePassword,
|
||||
resourcePincode,
|
||||
@@ -187,16 +186,98 @@ export type ResourceWithTargets = {
|
||||
};
|
||||
|
||||
function queryResourcesBase() {
|
||||
const sharedPolicy = alias(resourcePolicies, "sharedPolicy");
|
||||
const defaultPolicy = alias(resourcePolicies, "defaultPolicy");
|
||||
const sharedPolicyPincode = alias(
|
||||
resourcePolicyPincode,
|
||||
"sharedPolicyPincode"
|
||||
);
|
||||
const defaultPolicyPincode = alias(
|
||||
resourcePolicyPincode,
|
||||
"defaultPolicyPincode"
|
||||
);
|
||||
const sharedPolicyPassword = alias(
|
||||
resourcePolicyPassword,
|
||||
"sharedPolicyPassword"
|
||||
);
|
||||
const defaultPolicyPassword = alias(
|
||||
resourcePolicyPassword,
|
||||
"defaultPolicyPassword"
|
||||
);
|
||||
const sharedPolicyHeaderAuth = alias(
|
||||
resourcePolicyHeaderAuth,
|
||||
"sharedPolicyHeaderAuth"
|
||||
);
|
||||
const defaultPolicyHeaderAuth = alias(
|
||||
resourcePolicyHeaderAuth,
|
||||
"defaultPolicyHeaderAuth"
|
||||
);
|
||||
|
||||
const effectivePasswordId = sql<number | null>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicyPassword.passwordId}
|
||||
ELSE ${defaultPolicyPassword.passwordId}
|
||||
END,
|
||||
${resourcePassword.passwordId}
|
||||
)
|
||||
`;
|
||||
const effectivePincodeId = sql<number | null>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicyPincode.pincodeId}
|
||||
ELSE ${defaultPolicyPincode.pincodeId}
|
||||
END,
|
||||
${resourcePincode.pincodeId}
|
||||
)
|
||||
`;
|
||||
const effectiveHeaderAuthId = sql<number | null>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicyHeaderAuth.headerAuthId}
|
||||
ELSE ${defaultPolicyHeaderAuth.headerAuthId}
|
||||
END,
|
||||
${resourceHeaderAuth.headerAuthId}
|
||||
)
|
||||
`;
|
||||
const effectiveSso = sql<boolean>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicy.sso}
|
||||
ELSE ${defaultPolicy.sso}
|
||||
END,
|
||||
false
|
||||
)
|
||||
`;
|
||||
const effectiveWhitelist = sql<boolean>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicy.emailWhitelistEnabled}
|
||||
ELSE ${defaultPolicy.emailWhitelistEnabled}
|
||||
END,
|
||||
false
|
||||
)
|
||||
`;
|
||||
const effectiveHeaderAuthExtendedCompatibility = sql<boolean>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicyHeaderAuth.extendedCompatibility}
|
||||
ELSE ${defaultPolicyHeaderAuth.extendedCompatibility}
|
||||
END,
|
||||
false
|
||||
)
|
||||
`;
|
||||
|
||||
return db
|
||||
.select({
|
||||
resourceId: resources.resourceId,
|
||||
name: resources.name,
|
||||
ssl: resources.ssl,
|
||||
fullDomain: resources.fullDomain,
|
||||
passwordId: resourcePolicyPassword.passwordId,
|
||||
sso: resourcePolicies.sso,
|
||||
pincodeId: resourcePolicyPincode.pincodeId,
|
||||
whitelist: resourcePolicies.emailWhitelistEnabled,
|
||||
passwordId: effectivePasswordId,
|
||||
sso: effectiveSso,
|
||||
pincodeId: effectivePincodeId,
|
||||
whitelist: effectiveWhitelist,
|
||||
proxyPort: resources.proxyPort,
|
||||
enabled: resources.enabled,
|
||||
domainId: resources.domainId,
|
||||
@@ -204,44 +285,74 @@ function queryResourcesBase() {
|
||||
wildcard: resources.wildcard,
|
||||
mode: resources.mode,
|
||||
health: resources.health,
|
||||
headerAuthId: resourcePolicyHeaderAuth.headerAuthId,
|
||||
headerAuthId: effectiveHeaderAuthId,
|
||||
headerAuthExtendedCompatibility:
|
||||
resourcePolicyHeaderAuth.extendedCompatibility
|
||||
effectiveHeaderAuthExtendedCompatibility
|
||||
})
|
||||
.from(resources)
|
||||
.leftJoin(
|
||||
resourcePolicies,
|
||||
or(
|
||||
eq(
|
||||
resourcePolicies.resourcePolicyId,
|
||||
resources.resourcePolicyId
|
||||
),
|
||||
eq(
|
||||
resourcePolicies.resourcePolicyId,
|
||||
resources.defaultResourcePolicyId
|
||||
)
|
||||
)
|
||||
resourcePincode,
|
||||
eq(resourcePincode.resourceId, resources.resourceId)
|
||||
)
|
||||
|
||||
.leftJoin(
|
||||
resourcePolicyPassword,
|
||||
resourcePassword,
|
||||
eq(resourcePassword.resourceId, resources.resourceId)
|
||||
)
|
||||
.leftJoin(
|
||||
resourceHeaderAuth,
|
||||
eq(resourceHeaderAuth.resourceId, resources.resourceId)
|
||||
)
|
||||
.leftJoin(
|
||||
sharedPolicy,
|
||||
eq(sharedPolicy.resourcePolicyId, resources.resourcePolicyId)
|
||||
)
|
||||
.leftJoin(
|
||||
sharedPolicyPincode,
|
||||
eq(
|
||||
resourcePolicyPassword.resourcePolicyId,
|
||||
resourcePolicies.resourcePolicyId
|
||||
sharedPolicyPincode.resourcePolicyId,
|
||||
sharedPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
resourcePolicyPincode,
|
||||
sharedPolicyPassword,
|
||||
eq(
|
||||
resourcePolicyPincode.resourcePolicyId,
|
||||
resourcePolicies.resourcePolicyId
|
||||
sharedPolicyPassword.resourcePolicyId,
|
||||
sharedPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
resourcePolicyHeaderAuth,
|
||||
sharedPolicyHeaderAuth,
|
||||
eq(
|
||||
resourcePolicyHeaderAuth.resourcePolicyId,
|
||||
resourcePolicies.resourcePolicyId
|
||||
sharedPolicyHeaderAuth.resourcePolicyId,
|
||||
sharedPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicy,
|
||||
eq(
|
||||
defaultPolicy.resourcePolicyId,
|
||||
resources.defaultResourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicyPincode,
|
||||
eq(
|
||||
defaultPolicyPincode.resourcePolicyId,
|
||||
defaultPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicyPassword,
|
||||
eq(
|
||||
defaultPolicyPassword.resourcePolicyId,
|
||||
defaultPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicyHeaderAuth,
|
||||
eq(
|
||||
defaultPolicyHeaderAuth.resourcePolicyId,
|
||||
defaultPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(targets, eq(targets.resourceId, resources.resourceId))
|
||||
@@ -251,10 +362,23 @@ function queryResourcesBase() {
|
||||
)
|
||||
.groupBy(
|
||||
resources.resourceId,
|
||||
resourcePolicies.resourcePolicyId,
|
||||
resourcePolicyPassword.passwordId,
|
||||
resourcePolicyPincode.pincodeId,
|
||||
resourcePolicyHeaderAuth.headerAuthId
|
||||
resourcePincode.pincodeId,
|
||||
resourcePassword.passwordId,
|
||||
resourceHeaderAuth.headerAuthId,
|
||||
sharedPolicy.resourcePolicyId,
|
||||
sharedPolicy.sso,
|
||||
sharedPolicy.emailWhitelistEnabled,
|
||||
sharedPolicyPincode.pincodeId,
|
||||
sharedPolicyPassword.passwordId,
|
||||
sharedPolicyHeaderAuth.headerAuthId,
|
||||
sharedPolicyHeaderAuth.extendedCompatibility,
|
||||
defaultPolicy.resourcePolicyId,
|
||||
defaultPolicy.sso,
|
||||
defaultPolicy.emailWhitelistEnabled,
|
||||
defaultPolicyPincode.pincodeId,
|
||||
defaultPolicyPassword.passwordId,
|
||||
defaultPolicyHeaderAuth.headerAuthId,
|
||||
defaultPolicyHeaderAuth.extendedCompatibility
|
||||
);
|
||||
}
|
||||
|
||||
@@ -396,6 +520,80 @@ export async function listResources(
|
||||
}
|
||||
|
||||
if (typeof authState !== "undefined") {
|
||||
const sharedPolicy = alias(resourcePolicies, "sharedPolicy");
|
||||
const defaultPolicy = alias(resourcePolicies, "defaultPolicy");
|
||||
const sharedPolicyPincode = alias(
|
||||
resourcePolicyPincode,
|
||||
"sharedPolicyPincode"
|
||||
);
|
||||
const defaultPolicyPincode = alias(
|
||||
resourcePolicyPincode,
|
||||
"defaultPolicyPincode"
|
||||
);
|
||||
const sharedPolicyPassword = alias(
|
||||
resourcePolicyPassword,
|
||||
"sharedPolicyPassword"
|
||||
);
|
||||
const defaultPolicyPassword = alias(
|
||||
resourcePolicyPassword,
|
||||
"defaultPolicyPassword"
|
||||
);
|
||||
const sharedPolicyHeaderAuth = alias(
|
||||
resourcePolicyHeaderAuth,
|
||||
"sharedPolicyHeaderAuth"
|
||||
);
|
||||
const defaultPolicyHeaderAuth = alias(
|
||||
resourcePolicyHeaderAuth,
|
||||
"defaultPolicyHeaderAuth"
|
||||
);
|
||||
|
||||
const effectiveSso = sql<boolean>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicy.sso}
|
||||
ELSE ${defaultPolicy.sso}
|
||||
END,
|
||||
false
|
||||
)
|
||||
`;
|
||||
const effectiveWhitelist = sql<boolean>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicy.emailWhitelistEnabled}
|
||||
ELSE ${defaultPolicy.emailWhitelistEnabled}
|
||||
END,
|
||||
false
|
||||
)
|
||||
`;
|
||||
const effectiveHeaderAuthId = sql<number | null>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicyHeaderAuth.headerAuthId}
|
||||
ELSE ${defaultPolicyHeaderAuth.headerAuthId}
|
||||
END,
|
||||
${resourceHeaderAuth.headerAuthId}
|
||||
)
|
||||
`;
|
||||
const effectivePincodeId = sql<number | null>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicyPincode.pincodeId}
|
||||
ELSE ${defaultPolicyPincode.pincodeId}
|
||||
END,
|
||||
${resourcePincode.pincodeId}
|
||||
)
|
||||
`;
|
||||
const effectivePasswordId = sql<number | null>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicyPassword.passwordId}
|
||||
ELSE ${defaultPolicyPassword.passwordId}
|
||||
END,
|
||||
${resourcePassword.passwordId}
|
||||
)
|
||||
`;
|
||||
const browserGatewayModes = ["http", "ssh", "rdp", "vnc"];
|
||||
|
||||
switch (authState) {
|
||||
case "none":
|
||||
conditions.push(
|
||||
@@ -404,22 +602,28 @@ export async function listResources(
|
||||
break;
|
||||
case "protected":
|
||||
conditions.push(
|
||||
or(
|
||||
eq(resourcePolicies.sso, true),
|
||||
eq(resourcePolicies.emailWhitelistEnabled, true),
|
||||
not(isNull(resourcePolicyHeaderAuth.headerAuthId)),
|
||||
not(isNull(resourcePolicyPincode.pincodeId)),
|
||||
not(isNull(resourcePolicyPassword.passwordId))
|
||||
and(
|
||||
inArray(resources.mode, browserGatewayModes),
|
||||
or(
|
||||
eq(effectiveSso, true),
|
||||
eq(effectiveWhitelist, true),
|
||||
not(isNull(effectiveHeaderAuthId)),
|
||||
not(isNull(effectivePincodeId)),
|
||||
not(isNull(effectivePasswordId))
|
||||
)
|
||||
)
|
||||
);
|
||||
break;
|
||||
case "not_protected":
|
||||
conditions.push(
|
||||
not(eq(resourcePolicies.sso, true)),
|
||||
not(eq(resourcePolicies.emailWhitelistEnabled, true)),
|
||||
isNull(resourcePolicyHeaderAuth.headerAuthId),
|
||||
isNull(resourcePolicyPincode.pincodeId),
|
||||
isNull(resourcePolicyPassword.passwordId)
|
||||
and(
|
||||
inArray(resources.mode, browserGatewayModes),
|
||||
not(eq(effectiveSso, true)),
|
||||
not(eq(effectiveWhitelist, true)),
|
||||
isNull(effectiveHeaderAuthId),
|
||||
isNull(effectivePincodeId),
|
||||
isNull(effectivePasswordId)
|
||||
)
|
||||
);
|
||||
break;
|
||||
}
|
||||
@@ -434,15 +638,8 @@ export async function listResources(
|
||||
.from(targets)
|
||||
.innerJoin(sites, eq(targets.siteId, sites.siteId))
|
||||
.where(and(eq(sites.orgId, orgId), eq(sites.siteId, siteId)));
|
||||
const resourcesWithBrowserGateway = db
|
||||
.select({ resourceId: browserGatewayTarget.resourceId })
|
||||
.from(browserGatewayTarget)
|
||||
.where(eq(browserGatewayTarget.siteId, siteId));
|
||||
conditions.push(
|
||||
or(
|
||||
inArray(resources.resourceId, resourcesWithSite),
|
||||
inArray(resources.resourceId, resourcesWithBrowserGateway)
|
||||
)
|
||||
or(inArray(resources.resourceId, resourcesWithSite))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -565,30 +762,6 @@ export async function listResources(
|
||||
)
|
||||
.leftJoin(sites, eq(targets.siteId, sites.siteId));
|
||||
|
||||
const allBgTargetSites =
|
||||
resourceIdList.length === 0
|
||||
? []
|
||||
: await db
|
||||
.select({
|
||||
resourceId: browserGatewayTarget.resourceId,
|
||||
siteId: browserGatewayTarget.siteId,
|
||||
siteName: sites.name,
|
||||
siteNiceId: sites.niceId,
|
||||
siteOnline: sites.online,
|
||||
siteType: sites.type
|
||||
})
|
||||
.from(browserGatewayTarget)
|
||||
.where(
|
||||
inArray(
|
||||
browserGatewayTarget.resourceId,
|
||||
resourceIdList
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
sites,
|
||||
eq(sites.siteId, browserGatewayTarget.siteId)
|
||||
);
|
||||
|
||||
// avoids TS issues with reduce/never[]
|
||||
const map = new Map<number, ResourceWithTargets>();
|
||||
|
||||
@@ -651,21 +824,6 @@ export async function listResources(
|
||||
online: isLocal ? undefined : Boolean(t.siteOnline)
|
||||
});
|
||||
}
|
||||
const bgRaw = allBgTargetSites.filter(
|
||||
(t) => t.resourceId === entry.resourceId
|
||||
);
|
||||
for (const t of bgRaw) {
|
||||
if (typeof t.siteId !== "number" || siteById.has(t.siteId)) {
|
||||
continue;
|
||||
}
|
||||
const isLocal = t.siteType === "local";
|
||||
siteById.set(t.siteId, {
|
||||
siteId: t.siteId,
|
||||
siteName: t.siteName ?? "",
|
||||
siteNiceId: t.siteNiceId ?? "",
|
||||
online: isLocal ? undefined : Boolean(t.siteOnline)
|
||||
});
|
||||
}
|
||||
entry.sites = Array.from(siteById.values());
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ export type GetMaintenanceInfoResponse = {
|
||||
|
||||
export type AttachedResource = Pick<
|
||||
Resource,
|
||||
"resourceId" | "name" | "fullDomain"
|
||||
"resourceId" | "niceId" | "name" | "fullDomain"
|
||||
>;
|
||||
|
||||
export type ResourcePolicyWithResources = Pick<
|
||||
|
||||
@@ -93,10 +93,9 @@ export async function deleteSite(
|
||||
// Clean up all client associations and send peer/proxy removal
|
||||
// messages in a single efficient pass before deleting the row.
|
||||
await cleanupSiteAssociations(site, trx);
|
||||
|
||||
await trx.delete(sites).where(eq(sites.siteId, siteId));
|
||||
}
|
||||
|
||||
await trx.delete(sites).where(eq(sites.siteId, siteId));
|
||||
await usageService.add(site.orgId, FeatureId.SITES, -1, trx);
|
||||
});
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
userSites,
|
||||
labels,
|
||||
siteLabels,
|
||||
browserGatewayTarget,
|
||||
type Label
|
||||
} from "@server/db";
|
||||
import cache from "#dynamic/lib/cache";
|
||||
@@ -241,10 +240,6 @@ function querySitesBase() {
|
||||
ON ${siteResources.networkId} = ${siteNetworks.networkId}
|
||||
WHERE ${siteNetworks.siteId} = ${sites.siteId}
|
||||
AND ${siteResources.orgId} = ${sites.orgId}
|
||||
) + (
|
||||
SELECT COUNT(DISTINCT ${browserGatewayTarget.resourceId})
|
||||
FROM ${browserGatewayTarget}
|
||||
WHERE ${browserGatewayTarget.siteId} = ${sites.siteId}
|
||||
)`,
|
||||
status: sites.status
|
||||
})
|
||||
|
||||
@@ -142,6 +142,7 @@ const createSiteResourceSchema = z
|
||||
data.destinationPort <= 65535)
|
||||
);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
message:
|
||||
|
||||
@@ -24,6 +24,10 @@ import {
|
||||
fireHealthCheckUnhealthyAlert,
|
||||
fireHealthCheckUnknownAlert
|
||||
} from "@server/lib/alerts";
|
||||
import { encrypt } from "@server/lib/crypto";
|
||||
import { generateId } from "@server/auth/sessions/app";
|
||||
import config from "@server/lib/config";
|
||||
import { sendBrowserGatewayTargets } from "@server/routers/newt/targets";
|
||||
|
||||
const createTargetParamsSchema = z.strictObject({
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
@@ -32,6 +36,7 @@ const createTargetParamsSchema = z.strictObject({
|
||||
const createTargetSchema = z.strictObject({
|
||||
siteId: z.int().positive(),
|
||||
ip: z.string().refine(isTargetValid),
|
||||
mode: z.enum(["http", "tcp", "udp", "ssh", "rdp", "vnc"]).optional(),
|
||||
method: z.string().optional().nullable(),
|
||||
port: z.int().min(1).max(65535),
|
||||
enabled: z.boolean().default(true),
|
||||
@@ -161,6 +166,12 @@ export async function createTarget(
|
||||
);
|
||||
}
|
||||
|
||||
const plainToken = generateId(48);
|
||||
const encryptedToken = encrypt(
|
||||
plainToken,
|
||||
config.getRawConfig().server.secret!
|
||||
);
|
||||
|
||||
let newTarget: Target[] = [];
|
||||
let targetIps: string[] = [];
|
||||
let healthCheck: TargetHealthCheck[] = [];
|
||||
@@ -191,6 +202,9 @@ export async function createTarget(
|
||||
.values({
|
||||
resourceId,
|
||||
...targetData,
|
||||
mode: (targetData.mode ??
|
||||
resource.mode ??
|
||||
"http") as Target["mode"],
|
||||
priority: targetData.priority || 100
|
||||
})
|
||||
.returning();
|
||||
@@ -226,6 +240,10 @@ export async function createTarget(
|
||||
resourceId,
|
||||
siteId: site.siteId,
|
||||
ip: targetData.ip,
|
||||
mode: (targetData.mode ??
|
||||
resource.mode ??
|
||||
"http") as Target["mode"],
|
||||
authToken: encryptedToken,
|
||||
method: targetData.method,
|
||||
port: targetData.port,
|
||||
internalPort,
|
||||
@@ -325,13 +343,21 @@ export async function createTarget(
|
||||
.where(eq(newts.siteId, site.siteId))
|
||||
.limit(1);
|
||||
|
||||
await addTargets(
|
||||
newt.newtId,
|
||||
newTarget,
|
||||
healthCheck,
|
||||
resource.mode === "udp" ? "udp" : "tcp",
|
||||
newt.version
|
||||
);
|
||||
if (["http", "tcp", "udp"].includes(newTarget[0].mode)) {
|
||||
await addTargets(
|
||||
newt.newtId,
|
||||
newTarget,
|
||||
healthCheck,
|
||||
resource.mode === "udp" ? "udp" : "tcp",
|
||||
newt.version
|
||||
);
|
||||
} else if (["ssh", "rdp", "vnc"].includes(newTarget[0].mode)) {
|
||||
await sendBrowserGatewayTargets(
|
||||
newt.newtId,
|
||||
newTarget,
|
||||
newt.version
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import { fromError } from "zod-validation-error";
|
||||
import { removeTargets } from "../newt/targets";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { targetHealthCheck } from "@server/db";
|
||||
import { removeBrowserGatewayTarget } from "@server/routers/newt/targets";
|
||||
|
||||
const deleteTargetSchema = z.strictObject({
|
||||
targetId: z.coerce.number().int().positive()
|
||||
@@ -136,14 +137,22 @@ export async function deleteTarget(
|
||||
.where(eq(newts.siteId, site.siteId))
|
||||
.limit(1);
|
||||
|
||||
await removeTargets(
|
||||
newt.newtId,
|
||||
// [deletedTarget],
|
||||
[], // deleting the target from newt causes issues because we cant unbind the port. this needs to be fixed in newt before we can do this
|
||||
[deletedHealthCheck],
|
||||
resource.mode === "udp" ? "udp" : "tcp",
|
||||
newt.version
|
||||
);
|
||||
if (["http", "tcp", "udp"].includes(deletedTarget.mode)) {
|
||||
await removeTargets(
|
||||
newt.newtId,
|
||||
// [deletedTarget],
|
||||
[], // deleting the target from newt causes issues because we cant unbind the port. this needs to be fixed in newt before we can do this
|
||||
[deletedHealthCheck],
|
||||
resource.mode === "udp" ? "udp" : "tcp",
|
||||
newt.version
|
||||
);
|
||||
} else if (["ssh", "rdp", "vnc"].includes(deletedTarget.mode)) {
|
||||
await removeBrowserGatewayTarget(
|
||||
newt.newtId,
|
||||
deletedTarget.targetId,
|
||||
newt.version
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,6 +34,7 @@ function queryTargets(resourceId: number) {
|
||||
.select({
|
||||
targetId: targets.targetId,
|
||||
ip: targets.ip,
|
||||
mode: targets.mode,
|
||||
method: targets.method,
|
||||
port: targets.port,
|
||||
enabled: targets.enabled,
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import { pickPort } from "./helpers";
|
||||
import { isTargetValid } from "@server/lib/validators";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { sendBrowserGatewayTargets } from "@server/routers/newt/targets";
|
||||
|
||||
const updateTargetParamsSchema = z.strictObject({
|
||||
targetId: z.coerce.number().int().positive()
|
||||
@@ -27,6 +28,10 @@ const updateTargetBodySchema = z
|
||||
.strictObject({
|
||||
siteId: z.int().positive(),
|
||||
ip: z.string().refine(isTargetValid),
|
||||
mode: z
|
||||
.enum(["http", "tcp", "udp", "ssh", "rdp", "vnc"])
|
||||
.optional()
|
||||
.nullable(),
|
||||
method: z.string().min(1).max(10).optional().nullable(),
|
||||
port: z.int().min(1).max(65535).optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
@@ -184,6 +189,8 @@ export async function updateTarget(
|
||||
}
|
||||
|
||||
const pathMatchTypeRemoved = parsedBody.data.pathMatchType === null;
|
||||
const nextMode =
|
||||
parsedBody.data.mode === null ? undefined : parsedBody.data.mode;
|
||||
|
||||
let updatedTarget: any;
|
||||
let updatedHc: any;
|
||||
@@ -193,6 +200,7 @@ export async function updateTarget(
|
||||
.set({
|
||||
siteId: parsedBody.data.siteId,
|
||||
ip: parsedBody.data.ip,
|
||||
mode: nextMode,
|
||||
method: parsedBody.data.method,
|
||||
port: parsedBody.data.port,
|
||||
internalPort,
|
||||
@@ -343,13 +351,21 @@ export async function updateTarget(
|
||||
.where(eq(newts.siteId, site.siteId))
|
||||
.limit(1);
|
||||
|
||||
await addTargets(
|
||||
newt.newtId,
|
||||
[updatedTarget],
|
||||
[updatedHc],
|
||||
resource.mode === "udp" ? "udp" : "tcp",
|
||||
newt.version
|
||||
);
|
||||
if (["http", "tcp", "udp"].includes(updatedTarget.mode)) {
|
||||
await addTargets(
|
||||
newt.newtId,
|
||||
[updatedTarget],
|
||||
[updatedHc],
|
||||
resource.mode === "udp" ? "udp" : "tcp",
|
||||
newt.version
|
||||
);
|
||||
} else if (["ssh", "rdp", "vnc"].includes(updatedTarget.mode)) {
|
||||
await sendBrowserGatewayTargets(
|
||||
newt.newtId,
|
||||
[updatedTarget],
|
||||
newt.version
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -39,18 +39,6 @@ export default async function migration() {
|
||||
try {
|
||||
await db.execute(sql`BEGIN`);
|
||||
|
||||
await db.execute(sql`
|
||||
CREATE TABLE "browserGatewayTarget" (
|
||||
"browserGatewayTargetId" serial PRIMARY KEY NOT NULL,
|
||||
"resourceId" integer NOT NULL,
|
||||
"siteId" integer NOT NULL,
|
||||
"authToken" varchar NOT NULL,
|
||||
"type" varchar NOT NULL,
|
||||
"destination" varchar NOT NULL,
|
||||
"destinationPort" integer NOT NULL
|
||||
);
|
||||
`);
|
||||
|
||||
await db.execute(sql`
|
||||
CREATE TABLE "clientLabels" (
|
||||
"clientLabelId" serial PRIMARY KEY NOT NULL,
|
||||
@@ -215,12 +203,6 @@ export default async function migration() {
|
||||
await db.execute(
|
||||
sql`ALTER TABLE "sites" ADD COLUMN "autoUpdateOverrideOrg" boolean DEFAULT false NOT NULL;`
|
||||
);
|
||||
await db.execute(
|
||||
sql`ALTER TABLE "browserGatewayTarget" ADD CONSTRAINT "browserGatewayTarget_resourceId_resources_resourceId_fk" FOREIGN KEY ("resourceId") REFERENCES "public"."resources"("resourceId") ON DELETE cascade ON UPDATE no action;`
|
||||
);
|
||||
await db.execute(
|
||||
sql`ALTER TABLE "browserGatewayTarget" ADD CONSTRAINT "browserGatewayTarget_siteId_sites_siteId_fk" FOREIGN KEY ("siteId") REFERENCES "public"."sites"("siteId") ON DELETE cascade ON UPDATE no action;`
|
||||
);
|
||||
await db.execute(
|
||||
sql`ALTER TABLE "clientLabels" ADD CONSTRAINT "clientLabels_clientId_clients_clientId_fk" FOREIGN KEY ("clientId") REFERENCES "public"."clients"("clientId") ON DELETE cascade ON UPDATE no action;`
|
||||
);
|
||||
@@ -289,6 +271,10 @@ export default async function migration() {
|
||||
);
|
||||
await db.execute(sql`ALTER TABLE "resources" DROP COLUMN "http";`);
|
||||
await db.execute(sql`ALTER TABLE "resources" DROP COLUMN "protocol";`);
|
||||
await db.execute(
|
||||
sql`ALTER TABLE "targets" ADD "mode" text DEFAULT 'http' NOT NULL;`
|
||||
);
|
||||
await db.execute(sql`ALTER TABLE "targets" ADD "authToken" text;`);
|
||||
|
||||
await db.execute(sql`COMMIT`);
|
||||
console.log("Migrated database");
|
||||
|
||||
@@ -40,22 +40,6 @@ export default async function migration() {
|
||||
|
||||
try {
|
||||
db.transaction(() => {
|
||||
db.prepare(
|
||||
`
|
||||
CREATE TABLE 'browserGatewayTarget' (
|
||||
'browserGatewayTargetId' integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
'resourceId' integer NOT NULL,
|
||||
'siteId' integer NOT NULL,
|
||||
'authToken' text NOT NULL,
|
||||
'type' text NOT NULL,
|
||||
'destination' text NOT NULL,
|
||||
'destinationPort' integer NOT NULL,
|
||||
FOREIGN KEY ('resourceId') REFERENCES 'resources'('resourceId') ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY ('siteId') REFERENCES 'sites'('siteId') ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
`
|
||||
).run();
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
CREATE TABLE 'clientLabels' (
|
||||
@@ -350,6 +334,16 @@ export default async function migration() {
|
||||
ALTER TABLE 'resourceSessions' ADD 'policyWhitelistId' integer REFERENCES resourcePolicyWhitelist(id);
|
||||
`
|
||||
).run();
|
||||
db.prepare(
|
||||
`
|
||||
ALTER TABLE 'targets' ADD 'mode' text DEFAULT 'http' NOT NULL;
|
||||
`
|
||||
).run();
|
||||
db.prepare(
|
||||
`
|
||||
ALTER TABLE 'targets' ADD 'authToken' text;
|
||||
`
|
||||
).run();
|
||||
})();
|
||||
|
||||
const existingResources = db
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { EditPolicyForm } from "@app/components/resource-policy/EditPolicyForm";
|
||||
|
||||
export default function EditPolicyAuthenticationPage() {
|
||||
return <EditPolicyForm section="authentication" />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { EditPolicyForm } from "@app/components/resource-policy/EditPolicyForm";
|
||||
|
||||
export default function EditPolicyGeneralPage() {
|
||||
return <EditPolicyForm section="general" />;
|
||||
}
|
||||
+33
-8
@@ -1,5 +1,5 @@
|
||||
import { EditPolicyForm } from "@app/components/resource-policy/EditPolicyForm";
|
||||
import SettingsSectionTitle from "@app/components/SettingsSectionTitle";
|
||||
import { HorizontalTabs } from "@app/components/HorizontalTabs";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { internal } from "@app/lib/api";
|
||||
import { authCookieHeader } from "@app/lib/api/cookies";
|
||||
@@ -9,12 +9,20 @@ import type { AxiosResponse } from "axios";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import type { Metadata } from "next";
|
||||
|
||||
export interface EditPolicyPageProps {
|
||||
export const metadata: Metadata = {
|
||||
title: "Resource Policy"
|
||||
};
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type EditPolicyLayoutProps = {
|
||||
children: React.ReactNode;
|
||||
params: Promise<{ niceId: string; orgId: string }>;
|
||||
}
|
||||
};
|
||||
|
||||
export default async function EditPolicyPage(props: EditPolicyPageProps) {
|
||||
export default async function EditPolicyLayout(props: EditPolicyLayoutProps) {
|
||||
const params = await props.params;
|
||||
const t = await getTranslations();
|
||||
|
||||
@@ -28,13 +36,28 @@ export default async function EditPolicyPage(props: EditPolicyPageProps) {
|
||||
);
|
||||
policyResponse = res.data.data;
|
||||
} catch {
|
||||
redirect(`/${params.orgId}/settings/policies/resource`);
|
||||
redirect(`/${params.orgId}/settings/policies/resources/public`);
|
||||
}
|
||||
|
||||
if (!policyResponse) {
|
||||
redirect(`/${params.orgId}/settings/policies/resource`);
|
||||
redirect(`/${params.orgId}/settings/policies/resources/public`);
|
||||
}
|
||||
|
||||
const navItems = [
|
||||
{
|
||||
title: t("general"),
|
||||
href: "/{orgId}/settings/policies/resources/public/{niceId}/general"
|
||||
},
|
||||
{
|
||||
title: t("authentication"),
|
||||
href: "/{orgId}/settings/policies/resources/public/{niceId}/authentication"
|
||||
},
|
||||
{
|
||||
title: t("policyAccessRulesTitle"),
|
||||
href: "/{orgId}/settings/policies/resources/public/{niceId}/rules"
|
||||
}
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex justify-between">
|
||||
@@ -46,14 +69,16 @@ export default async function EditPolicyPage(props: EditPolicyPageProps) {
|
||||
/>
|
||||
|
||||
<Button asChild variant="outline">
|
||||
<Link href={`/${params.orgId}/settings/policies/resource`}>
|
||||
<Link
|
||||
href={`/${params.orgId}/settings/policies/resources/public`}
|
||||
>
|
||||
{t("resourcePoliciesSeeAll")}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<ResourcePolicyProvider policy={policyResponse}>
|
||||
<EditPolicyForm />
|
||||
<HorizontalTabs items={navItems}>{props.children}</HorizontalTabs>
|
||||
</ResourcePolicyProvider>
|
||||
</>
|
||||
);
|
||||
@@ -0,0 +1,12 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
type EditPolicyPageProps = {
|
||||
params: Promise<{ niceId: string; orgId: string }>;
|
||||
};
|
||||
|
||||
export default async function EditPolicyPage(props: EditPolicyPageProps) {
|
||||
const params = await props.params;
|
||||
redirect(
|
||||
`/${params.orgId}/settings/policies/resources/public/${params.niceId}/general`
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { EditPolicyForm } from "@app/components/resource-policy/EditPolicyForm";
|
||||
|
||||
export default function EditPolicyRulesPage() {
|
||||
return <EditPolicyForm section="rules" />;
|
||||
}
|
||||
+3
-1
@@ -23,7 +23,9 @@ export default async function CreateResourcePolicyPage(
|
||||
/>
|
||||
|
||||
<Button asChild variant="outline">
|
||||
<Link href={`/${params.orgId}/settings/policies/resource`}>
|
||||
<Link
|
||||
href={`/${params.orgId}/settings/policies/resources/public`}
|
||||
>
|
||||
{t("resourcePoliciesSeeAll")}
|
||||
</Link>
|
||||
</Button>
|
||||
+3
@@ -1,3 +1,4 @@
|
||||
import ResourcePoliciesBanner from "@app/components/ResourcePoliciesBanner";
|
||||
import { ResourcePoliciesTable } from "@app/components/ResourcePoliciesTable";
|
||||
import SettingsSectionTitle from "@app/components/SettingsSectionTitle";
|
||||
import { internal } from "@app/lib/api";
|
||||
@@ -54,6 +55,8 @@ export default async function ResourcePoliciesPage(
|
||||
description={t("resourcePoliciesDescription")}
|
||||
/>
|
||||
|
||||
<ResourcePoliciesBanner />
|
||||
|
||||
<ResourcePoliciesTable
|
||||
policies={policies}
|
||||
orgId={params.orgId}
|
||||
@@ -10,7 +10,10 @@ import {
|
||||
PathRewriteDisplay,
|
||||
PathRewriteModal
|
||||
} from "@app/components/PathMatchRenameModal";
|
||||
import { ResourceTargetAddressItem } from "@app/components/resource-target-address-item";
|
||||
import {
|
||||
ResourceTargetAddressItem,
|
||||
ResourceTargetSiteItem
|
||||
} from "@app/components/resource-target-address-item";
|
||||
import {
|
||||
SettingsSection,
|
||||
SettingsSectionBody,
|
||||
@@ -18,6 +21,7 @@ import {
|
||||
SettingsSectionHeader,
|
||||
SettingsSectionTitle
|
||||
} from "@app/components/Settings";
|
||||
import { DataTableEmptyState } from "@app/components/ui/data-table-empty-state";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -65,6 +69,7 @@ import {
|
||||
useMemo,
|
||||
useState
|
||||
} from "react";
|
||||
import { maxSize } from "zod";
|
||||
|
||||
export type LocalTarget = Omit<
|
||||
ArrayElement<ListTargetsResponse["targets"]> & {
|
||||
@@ -138,11 +143,6 @@ export function ProxyResourceTargetsForm({
|
||||
const [selectedTargetForHealthCheck, setSelectedTargetForHealthCheck] =
|
||||
useState<LocalTarget | null>(null);
|
||||
|
||||
const [bgDestination, setBgDestination] = useState("");
|
||||
const [bgDestinationPort, setBgDestinationPort] = useState("");
|
||||
const [bgSiteId, setBgSiteId] = useState<number | null>(null);
|
||||
const [bgTargetId, setBgTargetId] = useState<number | null>(null);
|
||||
|
||||
const initializeDockerForSite = async (siteId: number) => {
|
||||
if (dockerStates.has(siteId)) {
|
||||
return;
|
||||
@@ -207,42 +207,6 @@ export function ProxyResourceTargetsForm({
|
||||
})
|
||||
);
|
||||
|
||||
// Browser-gateway targets (edit mode only)
|
||||
const { data: bgTargetsResponse } = useQuery({
|
||||
queryKey: ["browserGatewayTargets", resource?.resourceId, orgId],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(
|
||||
`/org/${orgId}/resource/${resource!.resourceId}/browser-gateway-targets`
|
||||
);
|
||||
return res.data.data as {
|
||||
targets: Array<{
|
||||
browserGatewayTargetId: number;
|
||||
resourceId: number;
|
||||
siteId: number;
|
||||
type: string;
|
||||
destination: string;
|
||||
destinationPort: number;
|
||||
}>;
|
||||
};
|
||||
},
|
||||
enabled: !!resource
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!bgTargetsResponse?.targets?.length) return;
|
||||
const bgt = bgTargetsResponse.targets[0];
|
||||
setBgDestination(bgt.destination);
|
||||
setBgDestinationPort(String(bgt.destinationPort));
|
||||
setBgSiteId(bgt.siteId);
|
||||
setBgTargetId(bgt.browserGatewayTargetId);
|
||||
}, [bgTargetsResponse]);
|
||||
|
||||
useEffect(() => {
|
||||
if (sites.length > 0 && bgSiteId === null) {
|
||||
setBgSiteId(sites[0].siteId);
|
||||
}
|
||||
}, [sites, bgSiteId]);
|
||||
|
||||
const updateTarget = useCallback(
|
||||
(targetId: number, data: Partial<LocalTarget>) => {
|
||||
setTargets((prevTargets) => {
|
||||
@@ -269,7 +233,7 @@ export function ProxyResourceTargetsForm({
|
||||
const priorityColumn: ColumnDef<LocalTarget> = {
|
||||
id: "priority",
|
||||
header: () => (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-2 p-3">
|
||||
{t("priority")}
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
@@ -285,7 +249,6 @@ export function ProxyResourceTargetsForm({
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full">
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
@@ -303,7 +266,6 @@ export function ProxyResourceTargetsForm({
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
size: 120,
|
||||
@@ -437,13 +399,12 @@ export function ProxyResourceTargetsForm({
|
||||
maxSize: 200
|
||||
};
|
||||
|
||||
const addressColumn: ColumnDef<LocalTarget> = {
|
||||
accessorKey: "address",
|
||||
header: () => <span className="p-3">{t("address")}</span>,
|
||||
const siteColumn: ColumnDef<LocalTarget> = {
|
||||
accessorKey: "site",
|
||||
header: () => <span className="p-3">{t("site")}</span>,
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<ResourceTargetAddressItem
|
||||
isHttp={isHttp}
|
||||
<ResourceTargetSiteItem
|
||||
orgId={orgId}
|
||||
getDockerStateForSite={getDockerStateForSite}
|
||||
proxyTarget={row.original}
|
||||
@@ -452,9 +413,26 @@ export function ProxyResourceTargetsForm({
|
||||
/>
|
||||
);
|
||||
},
|
||||
size: 400,
|
||||
minSize: 350,
|
||||
maxSize: 500
|
||||
size: 220,
|
||||
minSize: 180,
|
||||
maxSize: 280
|
||||
};
|
||||
|
||||
const addressColumn: ColumnDef<LocalTarget> = {
|
||||
accessorKey: "address",
|
||||
header: () => <span className="p-3">{t("address")}</span>,
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<ResourceTargetAddressItem
|
||||
isHttp={isHttp}
|
||||
proxyTarget={row.original}
|
||||
updateTarget={updateTarget}
|
||||
/>
|
||||
);
|
||||
},
|
||||
size: 350,
|
||||
minSize: 300,
|
||||
maxSize: 450
|
||||
};
|
||||
|
||||
const rewritePathColumn: ColumnDef<LocalTarget> = {
|
||||
@@ -567,6 +545,7 @@ export function ProxyResourceTargetsForm({
|
||||
|
||||
if (isAdvancedMode) {
|
||||
const cols = [
|
||||
siteColumn,
|
||||
addressColumn,
|
||||
healthCheckColumn,
|
||||
enabledColumn,
|
||||
@@ -575,12 +554,13 @@ export function ProxyResourceTargetsForm({
|
||||
|
||||
if (isHttp) {
|
||||
cols.unshift(matchPathColumn);
|
||||
cols.splice(3, 0, rewritePathColumn, priorityColumn);
|
||||
cols.splice(4, 0, rewritePathColumn, priorityColumn);
|
||||
}
|
||||
|
||||
return cols;
|
||||
} else {
|
||||
return [
|
||||
siteColumn,
|
||||
addressColumn,
|
||||
healthCheckColumn,
|
||||
enabledColumn,
|
||||
@@ -603,6 +583,8 @@ export function ProxyResourceTargetsForm({
|
||||
const newTarget: LocalTarget = {
|
||||
targetId: -Date.now(),
|
||||
ip: "",
|
||||
mode: ((resource?.mode as LocalTarget["mode"]) ??
|
||||
(isHttp ? "http" : "tcp")) as LocalTarget["mode"],
|
||||
method: isHttp ? "http" : null,
|
||||
port: 0,
|
||||
siteId: sites.length > 0 ? sites[0].siteId : 0,
|
||||
@@ -690,6 +672,15 @@ export function ProxyResourceTargetsForm({
|
||||
|
||||
const [, formAction, isSubmitting] = useActionState(saveTargets, null);
|
||||
|
||||
const addTargetButton = (
|
||||
<Button onClick={addNewTarget} variant="outline">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
{t("addTarget")}
|
||||
</Button>
|
||||
);
|
||||
|
||||
const hasTargets = targets.length > 0;
|
||||
|
||||
async function saveTargets() {
|
||||
if (!resource) return;
|
||||
|
||||
@@ -803,131 +794,104 @@ export function ProxyResourceTargetsForm({
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
{targets.length > 0 ? (
|
||||
<>
|
||||
<div className="overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table
|
||||
.getHeaderGroups()
|
||||
.map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map(
|
||||
(header) => {
|
||||
const isActionsColumn =
|
||||
header.column
|
||||
.id ===
|
||||
"actions";
|
||||
return (
|
||||
<TableHead
|
||||
key={
|
||||
header.id
|
||||
}
|
||||
className={
|
||||
isActionsColumn
|
||||
? "sticky right-0 z-10 w-auto min-w-fit bg-card"
|
||||
: ""
|
||||
}
|
||||
>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header
|
||||
.column
|
||||
.columnDef
|
||||
.header,
|
||||
header.getContext()
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
}
|
||||
)}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table
|
||||
.getRowModel()
|
||||
.rows.map((row) => (
|
||||
<TableRow key={row.id}>
|
||||
{row
|
||||
.getVisibleCells()
|
||||
.map((cell) => {
|
||||
const isActionsColumn =
|
||||
cell.column
|
||||
.id ===
|
||||
"actions";
|
||||
return (
|
||||
<TableCell
|
||||
key={
|
||||
cell.id
|
||||
}
|
||||
className={
|
||||
isActionsColumn
|
||||
? "sticky right-0 z-10 w-auto min-w-fit bg-card"
|
||||
: ""
|
||||
}
|
||||
>
|
||||
{flexRender(
|
||||
cell
|
||||
.column
|
||||
.columnDef
|
||||
.cell,
|
||||
cell.getContext()
|
||||
)}
|
||||
</TableCell>
|
||||
);
|
||||
})}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell
|
||||
colSpan={columns.length}
|
||||
className="h-24 text-center"
|
||||
<div className="overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
const isActionsColumn =
|
||||
header.column.id === "actions";
|
||||
const isSiteColumn =
|
||||
header.column.id === "site";
|
||||
return (
|
||||
<TableHead
|
||||
key={header.id}
|
||||
className={
|
||||
isActionsColumn
|
||||
? "sticky right-0 z-10 w-auto min-w-fit bg-card"
|
||||
: isSiteColumn
|
||||
? "w-45"
|
||||
: ""
|
||||
}
|
||||
>
|
||||
{t("targetNoOne")}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="flex items-center justify-between w-full gap-2">
|
||||
<Button
|
||||
onClick={addNewTarget}
|
||||
variant="outline"
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column
|
||||
.columnDef
|
||||
.header,
|
||||
header.getContext()
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map((row) => (
|
||||
<TableRow key={row.id}>
|
||||
{row
|
||||
.getVisibleCells()
|
||||
.map((cell) => {
|
||||
const isActionsColumn =
|
||||
cell.column.id ===
|
||||
"actions";
|
||||
const isSiteColumn =
|
||||
cell.column.id ===
|
||||
"site";
|
||||
return (
|
||||
<TableCell
|
||||
key={cell.id}
|
||||
className={
|
||||
isActionsColumn
|
||||
? "sticky right-0 z-10 w-auto min-w-fit bg-card"
|
||||
: isSiteColumn
|
||||
? "w-45"
|
||||
: ""
|
||||
}
|
||||
>
|
||||
{flexRender(
|
||||
cell.column
|
||||
.columnDef
|
||||
.cell,
|
||||
cell.getContext()
|
||||
)}
|
||||
</TableCell>
|
||||
);
|
||||
})}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<DataTableEmptyState
|
||||
colSpan={columns.length}
|
||||
message={t("targetNoOne")}
|
||||
action={addTargetButton}
|
||||
/>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
{hasTargets && (
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="flex items-center justify-between w-full gap-2">
|
||||
{addTargetButton}
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id="advanced-mode-toggle"
|
||||
checked={isAdvancedMode}
|
||||
onCheckedChange={setIsAdvancedMode}
|
||||
/>
|
||||
<label
|
||||
htmlFor="advanced-mode-toggle"
|
||||
className="text-sm"
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
{t("addTarget")}
|
||||
</Button>
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id="advanced-mode-toggle"
|
||||
checked={isAdvancedMode}
|
||||
onCheckedChange={setIsAdvancedMode}
|
||||
/>
|
||||
<label
|
||||
htmlFor="advanced-mode-toggle"
|
||||
className="text-sm"
|
||||
>
|
||||
{t("advancedMode")}
|
||||
</label>
|
||||
</div>
|
||||
{t("advancedMode")}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-center py-8 border-2 border-dashed border-muted rounded-lg p-4">
|
||||
<p className="text-muted-foreground mb-4">
|
||||
{t("targetNoOne")}
|
||||
</p>
|
||||
<Button onClick={addNewTarget} variant="outline">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
{t("addTarget")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{build === "saas" &&
|
||||
|
||||
@@ -1,350 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import ActionBanner from "@app/components/ActionBanner";
|
||||
import { EditPolicyForm } from "@app/components/resource-policy/EditPolicyForm";
|
||||
import {
|
||||
SettingsContainer,
|
||||
SettingsSection,
|
||||
SettingsSectionBody,
|
||||
SettingsSectionDescription,
|
||||
SettingsSectionFooter,
|
||||
SettingsSectionHeader,
|
||||
SettingsSectionTitle
|
||||
} from "@app/components/Settings";
|
||||
import {
|
||||
StrategySelect,
|
||||
type StrategyOption
|
||||
} from "@app/components/StrategySelect";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList
|
||||
} from "@app/components/ui/command";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger
|
||||
} from "@app/components/ui/popover";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { useOrgContext } from "@app/hooks/useOrgContext";
|
||||
import { usePaidStatus } from "@app/hooks/usePaidStatus";
|
||||
import { useResourceContext } from "@app/hooks/useResourceContext";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { createApiClient, formatAxiosError } from "@app/lib/api";
|
||||
import { cn } from "@app/lib/cn";
|
||||
import { orgQueries, resourceQueries } from "@app/lib/queries";
|
||||
import { ResourcePolicyProvider } from "@app/providers/ResourcePolicyProvider";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { CaretSortIcon } from "@radix-ui/react-icons";
|
||||
import { build } from "@server/build";
|
||||
import { tierMatrix, TierFeature } from "@server/lib/billing/tierMatrix";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import SetResourcePasswordForm from "@app/components/SetResourcePasswordForm";
|
||||
import { Binary, Bot, InfoIcon, Key } from "lucide-react";
|
||||
import { ArrowRightIcon, CheckIcon, ShieldAlertIcon } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState, useTransition } from "react";
|
||||
import { useForm, useWatch } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
const resourceTypeSchema = z
|
||||
.object({
|
||||
type: z.literal("inline")
|
||||
})
|
||||
.or(
|
||||
z.object({
|
||||
type: z.literal("shared"),
|
||||
resourcePolicyId: z.number()
|
||||
})
|
||||
);
|
||||
|
||||
type ResourcePolicyType = StrategyOption<"inline" | "shared">;
|
||||
import { ResourcePolicyEditForm } from "@app/components/resource-policy/ResourcePolicyEditForm";
|
||||
|
||||
export default function ResourceAuthenticationPage() {
|
||||
const { org } = useOrgContext();
|
||||
const { resource, updateResource } = useResourceContext();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { env } = useEnvContext();
|
||||
const { isPaidUser } = usePaidStatus();
|
||||
|
||||
const api = createApiClient({ env });
|
||||
const router = useRouter();
|
||||
const t = useTranslations();
|
||||
|
||||
const { data: policies, isLoading: isLoadingPolicies } = useQuery(
|
||||
resourceQueries.policies({
|
||||
resourceId: resource.resourceId
|
||||
})
|
||||
);
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(resourceTypeSchema),
|
||||
defaultValues: {
|
||||
type:
|
||||
build !== "oss" && resource.resourcePolicyId
|
||||
? "shared"
|
||||
: "inline"
|
||||
}
|
||||
});
|
||||
|
||||
const selectedResourceType = useWatch({
|
||||
control: form.control,
|
||||
name: "type"
|
||||
});
|
||||
|
||||
const [resourcePolicysearchQuery, setResourcePolicySearchQuery] =
|
||||
useState("");
|
||||
|
||||
const { data: policiesList = [] } = useQuery({
|
||||
...orgQueries.policies({
|
||||
orgId: org.org.orgId,
|
||||
name: resourcePolicysearchQuery
|
||||
}),
|
||||
enabled: selectedResourceType === "shared"
|
||||
});
|
||||
|
||||
const [selectedPolicy, setSelectedPolicy] = useState<{
|
||||
name: string;
|
||||
id: number;
|
||||
} | null>(null);
|
||||
|
||||
const resourcePolicyTypes: Array<ResourcePolicyType> = [
|
||||
{
|
||||
id: "inline",
|
||||
title: t("resourcePolicyInline"),
|
||||
description: t("resourcePolicyInlineDescription")
|
||||
},
|
||||
{
|
||||
id: "shared",
|
||||
title: t("resourcePolicyShared"),
|
||||
description: t("resourcePolicySharedDescription")
|
||||
}
|
||||
];
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoadingPolicies && policies?.sharedPolicy) {
|
||||
setSelectedPolicy({
|
||||
id: policies?.sharedPolicy.resourcePolicyId,
|
||||
name: policies?.sharedPolicy.name
|
||||
});
|
||||
}
|
||||
}, [isLoadingPolicies, policies?.sharedPolicy]);
|
||||
|
||||
const [isUpdatingResource, startTransition] = useTransition();
|
||||
|
||||
async function handleSaveResourcePolicyType() {
|
||||
try {
|
||||
if (selectedResourceType === "inline") {
|
||||
await api.post(`/resource/${resource.resourceId}`, {
|
||||
resourcePolicyId: null
|
||||
});
|
||||
} else {
|
||||
if (!selectedPolicy) {
|
||||
toast({
|
||||
title: t("error"),
|
||||
description: t("resourcePolicySelectError"),
|
||||
variant: "destructive"
|
||||
});
|
||||
return;
|
||||
}
|
||||
await api.post(`/resource/${resource.resourceId}`, {
|
||||
resourcePolicyId: selectedPolicy.id
|
||||
});
|
||||
}
|
||||
router.refresh();
|
||||
toast({
|
||||
title: t("resourceUpdated"),
|
||||
description: t("resourceUpdatedDescription")
|
||||
});
|
||||
} catch (e) {
|
||||
toast({
|
||||
title: t("error"),
|
||||
description: formatAxiosError(e),
|
||||
variant: "destructive"
|
||||
});
|
||||
} finally {
|
||||
await queryClient.invalidateQueries(
|
||||
resourceQueries.policies({
|
||||
resourceId: resource.resourceId
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const pageLoading = isLoadingPolicies || !policies;
|
||||
|
||||
if (pageLoading) {
|
||||
return <></>;
|
||||
}
|
||||
|
||||
console.log({
|
||||
shared: policies.sharedPolicy
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsContainer>
|
||||
{build !== "oss" &&
|
||||
isPaidUser(tierMatrix[TierFeature.ResourcePolicies]) && (
|
||||
<SettingsSection>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>
|
||||
{t("resourcePolicySelectTitle")}
|
||||
</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
{t("resourcePolicySelectDescription")}
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
<StrategySelect
|
||||
options={resourcePolicyTypes}
|
||||
value={selectedResourceType}
|
||||
onChange={(value) => {
|
||||
form.setValue("type", value);
|
||||
}}
|
||||
cols={2}
|
||||
/>
|
||||
{selectedResourceType === "shared" && (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
className={
|
||||
"w-full md:w-1/2 justify-between"
|
||||
}
|
||||
>
|
||||
<span className="truncate max-w-37.5">
|
||||
{selectedPolicy
|
||||
? selectedPolicy.name
|
||||
: t(
|
||||
"resourcePolicySelect"
|
||||
)}
|
||||
</span>
|
||||
<CaretSortIcon className="ml-2h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="p-0 w-45">
|
||||
<Command shouldFilter={false}>
|
||||
<CommandInput
|
||||
placeholder={t(
|
||||
"resourcePolicySearch"
|
||||
)}
|
||||
value={
|
||||
resourcePolicysearchQuery
|
||||
}
|
||||
onValueChange={
|
||||
setResourcePolicySearchQuery
|
||||
}
|
||||
/>
|
||||
<CommandList>
|
||||
<CommandEmpty>
|
||||
{t(
|
||||
"resourcePolicyNotFound"
|
||||
)}
|
||||
</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{policiesList.map(
|
||||
(policy) => (
|
||||
<CommandItem
|
||||
key={
|
||||
policy.resourcePolicyId
|
||||
}
|
||||
value={policy.resourcePolicyId.toString()}
|
||||
onSelect={() =>
|
||||
setSelectedPolicy(
|
||||
{
|
||||
id: policy.resourcePolicyId,
|
||||
name: policy.name
|
||||
}
|
||||
)
|
||||
}
|
||||
>
|
||||
<CheckIcon
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
policy.resourcePolicyId ===
|
||||
selectedPolicy?.id
|
||||
? "opacity-100"
|
||||
: "opacity-0"
|
||||
)}
|
||||
/>
|
||||
{
|
||||
policy.name
|
||||
}
|
||||
</CommandItem>
|
||||
)
|
||||
)}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)}
|
||||
</SettingsSectionBody>
|
||||
<SettingsSectionFooter className="justify-start">
|
||||
<Button
|
||||
onClick={() =>
|
||||
startTransition(
|
||||
handleSaveResourcePolicyType
|
||||
)
|
||||
}
|
||||
loading={isUpdatingResource}
|
||||
>
|
||||
{t("resourcePolicyTypeSave")}
|
||||
</Button>
|
||||
</SettingsSectionFooter>
|
||||
</SettingsSection>
|
||||
)}
|
||||
|
||||
{selectedResourceType === "inline" ? (
|
||||
<ResourcePolicyProvider policy={policies.defaultPolicy}>
|
||||
<EditPolicyForm hidePolicyNameForm />
|
||||
</ResourcePolicyProvider>
|
||||
) : (
|
||||
policies.sharedPolicy && (
|
||||
<ResourcePolicyProvider
|
||||
policy={policies.sharedPolicy}
|
||||
key={policies.sharedPolicy.resourcePolicyId}
|
||||
>
|
||||
<ActionBanner
|
||||
variant="info"
|
||||
title={t("resourcePolicyShared")}
|
||||
titleIcon={
|
||||
<ShieldAlertIcon className="w-5 h-5" />
|
||||
}
|
||||
description={t(
|
||||
"resourcePolicySharedDescription"
|
||||
)}
|
||||
actions={
|
||||
<Button
|
||||
variant="outline"
|
||||
className="gap-2"
|
||||
asChild
|
||||
>
|
||||
<Link
|
||||
href={`/${org.org.orgId}/settings/policies/resource/${policies.sharedPolicy.niceId}`}
|
||||
>
|
||||
{t("editSharedPolicy")}
|
||||
<ArrowRightIcon className="size-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<EditPolicyForm
|
||||
resourceId={resource.resourceId}
|
||||
/>
|
||||
</ResourcePolicyProvider>
|
||||
)
|
||||
)}
|
||||
</SettingsContainer>
|
||||
</>
|
||||
);
|
||||
return <ResourcePolicyEditForm section="authentication" />;
|
||||
}
|
||||
|
||||
@@ -36,10 +36,14 @@ import { AlertCircle } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { toASCII, toUnicode } from "punycode";
|
||||
import { useActionState, useMemo, useState } from "react";
|
||||
import { useActionState, useEffect, useMemo, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import z from "zod";
|
||||
import { SharedPolicySelect } from "@app/components/shared-policy-selector";
|
||||
import { useOrgContext } from "@app/hooks/useOrgContext";
|
||||
import { build } from "@server/build";
|
||||
import { TierFeature } from "@server/lib/billing/tierMatrix";
|
||||
import { Alert, AlertDescription } from "@app/components/ui/alert";
|
||||
import { RadioGroup, RadioGroupItem } from "@app/components/ui/radio-group";
|
||||
import {
|
||||
@@ -220,6 +224,11 @@ function MaintenanceSectionForm({
|
||||
</TooltipProvider>
|
||||
</FormControl>
|
||||
</div>
|
||||
<FormDescription>
|
||||
{t(
|
||||
"enableMaintenanceModeDescription"
|
||||
)}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
);
|
||||
@@ -429,16 +438,30 @@ function MaintenanceSectionForm({
|
||||
|
||||
export default function GeneralForm() {
|
||||
const params = useParams();
|
||||
const { org } = useOrgContext();
|
||||
const { resource, updateResource } = useResourceContext();
|
||||
const router = useRouter();
|
||||
const t = useTranslations();
|
||||
|
||||
const { env } = useEnvContext();
|
||||
const { isPaidUser } = usePaidStatus();
|
||||
|
||||
const orgId = params.orgId;
|
||||
|
||||
const api = createApiClient({ env });
|
||||
|
||||
const showResourcePolicy =
|
||||
build !== "oss" &&
|
||||
isPaidUser(tierMatrix[TierFeature.ResourcePolicies]);
|
||||
|
||||
const [selectedSharedPolicyId, setSelectedSharedPolicyId] = useState<
|
||||
number | null
|
||||
>(resource.resourcePolicyId ?? null);
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedSharedPolicyId(resource.resourcePolicyId ?? null);
|
||||
}, [resource.resourcePolicyId]);
|
||||
|
||||
const [resourceFullDomain, setResourceFullDomain] = useState(
|
||||
`${resource.ssl ? "https" : "http"}://${toUnicode(resource.fullDomain || "")}`
|
||||
);
|
||||
@@ -501,6 +524,12 @@ export default function GeneralForm() {
|
||||
|
||||
const data = form.getValues();
|
||||
|
||||
let resourcePolicyId: number | null | undefined;
|
||||
|
||||
if (showResourcePolicy) {
|
||||
resourcePolicyId = selectedSharedPolicyId;
|
||||
}
|
||||
|
||||
const res = await api
|
||||
.post<AxiosResponse<UpdateResourceResponse>>(
|
||||
`resource/${resource?.resourceId}`,
|
||||
@@ -514,7 +543,8 @@ export default function GeneralForm() {
|
||||
)
|
||||
: undefined,
|
||||
domainId: data.domainId,
|
||||
proxyPort: data.proxyPort
|
||||
proxyPort: data.proxyPort,
|
||||
...(resourcePolicyId !== undefined && { resourcePolicyId })
|
||||
}
|
||||
)
|
||||
.catch((e) => {
|
||||
@@ -538,7 +568,10 @@ export default function GeneralForm() {
|
||||
subdomain: data.subdomain,
|
||||
fullDomain: updated.fullDomain,
|
||||
proxyPort: data.proxyPort,
|
||||
domainId: data.domainId
|
||||
domainId: data.domainId,
|
||||
...(resourcePolicyId !== undefined && {
|
||||
resourcePolicyId
|
||||
})
|
||||
});
|
||||
|
||||
toast({
|
||||
@@ -579,13 +612,47 @@ export default function GeneralForm() {
|
||||
</SettingsSectionHeader>
|
||||
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm>
|
||||
<SettingsSectionForm variant="half">
|
||||
<Form {...form}>
|
||||
<form
|
||||
action={formAction}
|
||||
className="space-y-4"
|
||||
id="general-settings-form"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="enabled"
|
||||
render={() => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<SwitchInput
|
||||
id="enable-resource"
|
||||
defaultChecked={
|
||||
resource.enabled
|
||||
}
|
||||
label={t(
|
||||
"resourceEnable"
|
||||
)}
|
||||
onCheckedChange={(
|
||||
val
|
||||
) =>
|
||||
form.setValue(
|
||||
"enabled",
|
||||
val
|
||||
)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t(
|
||||
"disabledResourceDescription"
|
||||
)}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
@@ -732,40 +799,24 @@ export default function GeneralForm() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="enabled"
|
||||
render={() => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<SwitchInput
|
||||
id="enable-resource"
|
||||
defaultChecked={
|
||||
resource.enabled
|
||||
}
|
||||
label={t(
|
||||
"resourceEnable"
|
||||
)}
|
||||
onCheckedChange={(
|
||||
val
|
||||
) =>
|
||||
form.setValue(
|
||||
"enabled",
|
||||
val
|
||||
)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t(
|
||||
"disabledResourceDescription"
|
||||
)}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{showResourcePolicy && (
|
||||
<div className="space-y-2">
|
||||
<FormLabel>
|
||||
{t("sharedPolicy")}
|
||||
</FormLabel>
|
||||
<SharedPolicySelect
|
||||
key={
|
||||
resource.resourcePolicyId ??
|
||||
"none"
|
||||
}
|
||||
orgId={org.org.orgId}
|
||||
value={selectedSharedPolicyId}
|
||||
onChange={
|
||||
setSelectedSharedPolicyId
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
</Form>
|
||||
</SettingsSectionForm>
|
||||
|
||||
@@ -92,10 +92,16 @@ export default async function ResourceLayout(props: ResourceLayoutProps) {
|
||||
];
|
||||
|
||||
if (["http", "ssh", "rdp", "vnc"].includes(resource.mode)) {
|
||||
navItems.push({
|
||||
title: t("authentication"),
|
||||
href: `/{orgId}/settings/resources/public/{niceId}/authentication`
|
||||
});
|
||||
navItems.push(
|
||||
{
|
||||
title: t("authentication"),
|
||||
href: `/{orgId}/settings/resources/public/{niceId}/authentication`
|
||||
},
|
||||
{
|
||||
title: t("policyAccessRulesTitle"),
|
||||
href: `/{orgId}/settings/resources/public/{niceId}/rules`
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -11,201 +11,183 @@ import {
|
||||
} from "@app/components/Settings";
|
||||
import { BrowserGatewayTargetForm } from "@app/components/BrowserGatewayTargetForm";
|
||||
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
|
||||
import { type Selectedsite } from "@app/components/site-selector";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { Form } from "@app/components/ui/form";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { useResourceContext } from "@app/hooks/useResourceContext";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { usePaidStatus } from "@app/hooks/usePaidStatus";
|
||||
import { createBrowserGatewayTargetFormSchema } from "@app/lib/browserGatewayTargetFormSchema";
|
||||
import type { BrowserGatewayTargetFormValues } from "@app/lib/browserGatewayTargetFormSchema";
|
||||
import { tierMatrix, TierFeature } from "@server/lib/billing/tierMatrix";
|
||||
import { createApiClient } from "@app/lib/api";
|
||||
import { formatAxiosError } from "@app/lib/api/formatAxiosError";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { use, useActionState, useEffect, useState } from "react";
|
||||
import { use, useActionState, useMemo, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { GetResourceResponse } from "@server/routers/resource";
|
||||
import type { ResourceContextType } from "@app/contexts/resourceContext";
|
||||
|
||||
type ExistingTarget = {
|
||||
browserGatewayTargetId: number;
|
||||
targetId: number;
|
||||
siteId: number;
|
||||
};
|
||||
|
||||
const sshFormSchema = z.object({
|
||||
authDaemonPort: z.string().refine(
|
||||
(val) => {
|
||||
if (!val) return true;
|
||||
const n = Number(val);
|
||||
return Number.isInteger(n) && n >= 1 && n <= 65535;
|
||||
},
|
||||
{ message: "Port must be between 1 and 65535" }
|
||||
)
|
||||
});
|
||||
type TargetRow = {
|
||||
targetId: number;
|
||||
resourceId: number;
|
||||
siteId: number;
|
||||
siteName?: string;
|
||||
mode: string | null;
|
||||
ip: string;
|
||||
port: number;
|
||||
};
|
||||
|
||||
export default function SshSettingsPage(props: {
|
||||
type ResourceTargetsResponse = {
|
||||
targets: TargetRow[];
|
||||
};
|
||||
|
||||
export default function RdpSettingsPage(props: {
|
||||
params: Promise<{ orgId: string }>;
|
||||
}) {
|
||||
const params = use(props.params);
|
||||
const { resource, updateResource } = useResourceContext();
|
||||
const { isPaidUser } = usePaidStatus();
|
||||
const api = createApiClient(useEnvContext());
|
||||
const disabled = !isPaidUser(
|
||||
tierMatrix[TierFeature.AdvancedPublicResources]
|
||||
);
|
||||
|
||||
const { data: targetsResponse, isLoading: isLoadingTargets } = useQuery({
|
||||
queryKey: ["resourceTargets", resource.resourceId, params.orgId, "rdp"],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/resource/${resource.resourceId}/targets`);
|
||||
return res.data.data as ResourceTargetsResponse;
|
||||
}
|
||||
});
|
||||
|
||||
if (isLoadingTargets) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsContainer>
|
||||
<PaidFeaturesAlert
|
||||
tiers={tierMatrix[TierFeature.AdvancedPublicResources]}
|
||||
/>
|
||||
<SshServerForm
|
||||
<RdpServerForm
|
||||
orgId={params.orgId}
|
||||
resource={resource}
|
||||
updateResource={updateResource}
|
||||
disabled={disabled}
|
||||
targetsResponse={targetsResponse ?? { targets: [] }}
|
||||
/>
|
||||
</SettingsContainer>
|
||||
);
|
||||
}
|
||||
|
||||
function SshServerForm({
|
||||
function RdpServerForm({
|
||||
orgId,
|
||||
resource,
|
||||
updateResource,
|
||||
disabled
|
||||
disabled,
|
||||
targetsResponse
|
||||
}: {
|
||||
orgId: string;
|
||||
resource: GetResourceResponse;
|
||||
updateResource: ResourceContextType["updateResource"];
|
||||
disabled: boolean;
|
||||
targetsResponse: ResourceTargetsResponse;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const api = createApiClient(useEnvContext());
|
||||
const router = useRouter();
|
||||
const targets = targetsResponse.targets.filter((t) => t.mode === "rdp");
|
||||
const firstTarget = targets[0];
|
||||
|
||||
// Standard mode: multi-site
|
||||
const [selectedSites, setSelectedSites] = useState<Selectedsite[]>([]);
|
||||
const [bgDestination, setBgDestination] = useState("");
|
||||
const [bgDestinationPort, setBgDestinationPort] = useState("22");
|
||||
const [existingTargets, setExistingTargets] = useState<ExistingTarget[]>(
|
||||
[]
|
||||
const formSchema = useMemo(
|
||||
() => createBrowserGatewayTargetFormSchema(t),
|
||||
[t]
|
||||
);
|
||||
|
||||
// Native mode: single site
|
||||
const [selectedNativeSite, setSelectedNativeSite] =
|
||||
useState<Selectedsite | null>(null);
|
||||
const [nativeExistingTarget, setNativeExistingTarget] =
|
||||
useState<ExistingTarget | null>(null);
|
||||
|
||||
const { data: bgTargetsResponse } = useQuery({
|
||||
queryKey: ["browserGatewayTargets", resource.resourceId, orgId],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(
|
||||
`/org/${orgId}/resource/${resource.resourceId}/browser-gateway-targets`
|
||||
);
|
||||
return res.data.data as {
|
||||
targets: Array<{
|
||||
browserGatewayTargetId: number;
|
||||
resourceId: number;
|
||||
siteId: number;
|
||||
siteName?: string;
|
||||
type: string;
|
||||
destination: string;
|
||||
destinationPort: number;
|
||||
}>;
|
||||
};
|
||||
const form = useForm<BrowserGatewayTargetFormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
selectedSites: targets.map((target) => ({
|
||||
siteId: target.siteId,
|
||||
name: target.siteName ?? String(target.siteId),
|
||||
type: "newt" as const
|
||||
})),
|
||||
destination: firstTarget?.ip ?? "",
|
||||
destinationPort: firstTarget ? String(firstTarget.port) : "3389"
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!bgTargetsResponse?.targets?.length) return;
|
||||
const targets = bgTargetsResponse.targets;
|
||||
const first = targets[0];
|
||||
|
||||
setBgDestination(first.destination);
|
||||
setBgDestinationPort(String(first.destinationPort));
|
||||
setExistingTargets(
|
||||
targets.map((t) => ({
|
||||
browserGatewayTargetId: t.browserGatewayTargetId,
|
||||
siteId: t.siteId
|
||||
const [existingTargets, setExistingTargets] = useState<ExistingTarget[]>(
|
||||
() =>
|
||||
targets.map((target) => ({
|
||||
targetId: target.targetId,
|
||||
siteId: target.siteId
|
||||
}))
|
||||
);
|
||||
setSelectedSites(
|
||||
targets.map((t) => ({
|
||||
siteId: t.siteId,
|
||||
name: t.siteName ?? String(t.siteId),
|
||||
type: "newt" as const
|
||||
}))
|
||||
);
|
||||
}, [bgTargetsResponse]);
|
||||
);
|
||||
|
||||
const [, formAction, isSubmitting] = useActionState(save, null);
|
||||
|
||||
async function save() {
|
||||
const isValid = await form.trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const { selectedSites, destination, destinationPort } =
|
||||
form.getValues();
|
||||
|
||||
try {
|
||||
if (bgDestination && bgDestinationPort) {
|
||||
const selectedSiteIds = new Set(
|
||||
selectedSites.map((s) => s.siteId)
|
||||
);
|
||||
const existingSiteIds = new Set(
|
||||
existingTargets.map((t) => t.siteId)
|
||||
);
|
||||
const selectedSiteIds = new Set(selectedSites.map((s) => s.siteId));
|
||||
const existingSiteIds = new Set(
|
||||
existingTargets.map((t) => t.siteId)
|
||||
);
|
||||
|
||||
const toDelete = existingTargets.filter(
|
||||
(t) => !selectedSiteIds.has(t.siteId)
|
||||
);
|
||||
await Promise.all(
|
||||
toDelete.map((t) =>
|
||||
api.delete(
|
||||
`/org/${orgId}/browser-gateway-target/${t.browserGatewayTargetId}`
|
||||
)
|
||||
)
|
||||
);
|
||||
const toDelete = existingTargets.filter(
|
||||
(t) => !selectedSiteIds.has(t.siteId)
|
||||
);
|
||||
await Promise.all(toDelete.map((t) => api.delete(`/target/${t.targetId}`)));
|
||||
|
||||
const toUpdate = existingTargets.filter((t) =>
|
||||
selectedSiteIds.has(t.siteId)
|
||||
);
|
||||
await Promise.all(
|
||||
toUpdate.map((t) =>
|
||||
api.post(
|
||||
`/org/${orgId}/browser-gateway-target/${t.browserGatewayTargetId}`,
|
||||
{
|
||||
type: "rdp",
|
||||
destination: bgDestination,
|
||||
destinationPort: Number(bgDestinationPort),
|
||||
siteId: t.siteId
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
const toUpdate = existingTargets.filter((t) =>
|
||||
selectedSiteIds.has(t.siteId)
|
||||
);
|
||||
await Promise.all(
|
||||
toUpdate.map((t) =>
|
||||
api.post(`/target/${t.targetId}`, {
|
||||
mode: "rdp",
|
||||
ip: destination,
|
||||
port: Number(destinationPort),
|
||||
siteId: t.siteId,
|
||||
hcEnabled: false
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const toCreate = selectedSites.filter(
|
||||
(s) => !existingSiteIds.has(s.siteId)
|
||||
);
|
||||
const created = await Promise.all(
|
||||
toCreate.map((s) =>
|
||||
api.put(
|
||||
`/org/${orgId}/resource/${resource.resourceId}/browser-gateway-target`,
|
||||
{
|
||||
siteId: s.siteId,
|
||||
type: "rdp",
|
||||
destination: bgDestination,
|
||||
destinationPort: Number(bgDestinationPort)
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
const toCreate = selectedSites.filter(
|
||||
(s) => !existingSiteIds.has(s.siteId)
|
||||
);
|
||||
const created = await Promise.all(
|
||||
toCreate.map((s) =>
|
||||
api.put(`/resource/${resource.resourceId}/target`, {
|
||||
siteId: s.siteId,
|
||||
mode: "rdp",
|
||||
ip: destination,
|
||||
port: Number(destinationPort),
|
||||
hcEnabled: false
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const newTargets: ExistingTarget[] = created.map((res, i) => ({
|
||||
browserGatewayTargetId:
|
||||
res.data.data.browserGatewayTargetId,
|
||||
siteId: toCreate[i].siteId
|
||||
}));
|
||||
setExistingTargets([...toUpdate, ...newTargets]);
|
||||
}
|
||||
const newTargets: ExistingTarget[] = created.map((res, i) => ({
|
||||
targetId: res.data.data.targetId,
|
||||
siteId: toCreate[i].siteId
|
||||
}));
|
||||
setExistingTargets([...toUpdate, ...newTargets]);
|
||||
|
||||
toast({
|
||||
title: t("settingsUpdated"),
|
||||
@@ -237,31 +219,31 @@ function SshServerForm({
|
||||
disabled={disabled}
|
||||
className={disabled ? "opacity-50 pointer-events-none" : ""}
|
||||
>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm variant="half">
|
||||
<BrowserGatewayTargetForm
|
||||
orgId={orgId}
|
||||
multiSite={true}
|
||||
selectedSites={selectedSites}
|
||||
onSitesChange={setSelectedSites}
|
||||
destination={bgDestination}
|
||||
destinationPort={bgDestinationPort}
|
||||
onDestinationChange={setBgDestination}
|
||||
onDestinationPortChange={setBgDestinationPort}
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/rdp"
|
||||
defaultPort={3389}
|
||||
/>
|
||||
</SettingsSectionForm>
|
||||
</SettingsSectionBody>
|
||||
<form action={formAction} className="flex justify-end mt-4">
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
type="submit"
|
||||
>
|
||||
{t("saveSettings")}
|
||||
</Button>
|
||||
</form>
|
||||
<Form {...form}>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm variant="half">
|
||||
<BrowserGatewayTargetForm
|
||||
control={form.control}
|
||||
orgId={orgId}
|
||||
multiSite={true}
|
||||
sitesField="selectedSites"
|
||||
destinationField="destination"
|
||||
destinationPortField="destinationPort"
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/rdp"
|
||||
defaultPort={3389}
|
||||
/>
|
||||
</SettingsSectionForm>
|
||||
</SettingsSectionBody>
|
||||
<form action={formAction} className="flex justify-end mt-4">
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
type="submit"
|
||||
>
|
||||
{t("saveSettings")}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</fieldset>
|
||||
</SettingsSection>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { ResourcePolicyEditForm } from "@app/components/resource-policy/ResourcePolicyEditForm";
|
||||
|
||||
export default function ResourcePolicyRulesPage() {
|
||||
return <ResourcePolicyEditForm section="rules" />;
|
||||
}
|
||||
@@ -15,10 +15,7 @@ import {
|
||||
import { StrategySelect, StrategyOption } from "@app/components/StrategySelect";
|
||||
import { BrowserGatewayTargetForm } from "@app/components/BrowserGatewayTargetForm";
|
||||
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
|
||||
import {
|
||||
SitesSelector,
|
||||
type Selectedsite
|
||||
} from "@app/components/site-selector";
|
||||
import { SitesSelector } from "@app/components/site-selector";
|
||||
import { usePaidStatus } from "@app/hooks/usePaidStatus";
|
||||
import { tierMatrix, TierFeature } from "@server/lib/billing/tierMatrix";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
@@ -41,33 +38,37 @@ import { Badge } from "@app/components/ui/badge";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { useResourceContext } from "@app/hooks/useResourceContext";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { createSshSettingsFormSchema } from "@app/lib/browserGatewayTargetFormSchema";
|
||||
import type { SshSettingsFormValues } from "@app/lib/browserGatewayTargetFormSchema";
|
||||
import { createApiClient } from "@app/lib/api";
|
||||
import { formatAxiosError } from "@app/lib/api/formatAxiosError";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { use, useActionState, useEffect, useState } from "react";
|
||||
import { use, useActionState, useMemo, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { GetResourceResponse } from "@server/routers/resource";
|
||||
import type { ResourceContextType } from "@app/contexts/resourceContext";
|
||||
|
||||
type ExistingTarget = {
|
||||
browserGatewayTargetId: number;
|
||||
targetId: number;
|
||||
siteId: number;
|
||||
};
|
||||
|
||||
const sshFormSchema = z.object({
|
||||
authDaemonPort: z.string().refine(
|
||||
(val) => {
|
||||
if (!val) return true;
|
||||
const n = Number(val);
|
||||
return Number.isInteger(n) && n >= 1 && n <= 65535;
|
||||
},
|
||||
{ message: "Port must be between 1 and 65535" }
|
||||
)
|
||||
});
|
||||
type TargetRow = {
|
||||
targetId: number;
|
||||
resourceId: number;
|
||||
siteId: number;
|
||||
siteName?: string;
|
||||
mode: string | null;
|
||||
ip: string;
|
||||
port: number;
|
||||
};
|
||||
|
||||
type ResourceTargetsResponse = {
|
||||
targets: TargetRow[];
|
||||
};
|
||||
|
||||
export default function SshSettingsPage(props: {
|
||||
params: Promise<{ orgId: string }>;
|
||||
@@ -75,10 +76,23 @@ export default function SshSettingsPage(props: {
|
||||
const params = use(props.params);
|
||||
const { resource, updateResource } = useResourceContext();
|
||||
const { isPaidUser } = usePaidStatus();
|
||||
const api = createApiClient(useEnvContext());
|
||||
const disabled = !isPaidUser(
|
||||
tierMatrix[TierFeature.AdvancedPublicResources]
|
||||
);
|
||||
|
||||
const { data: targetsResponse, isLoading: isLoadingTargets } = useQuery({
|
||||
queryKey: ["resourceTargets", resource.resourceId, params.orgId, "ssh"],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/resource/${resource.resourceId}/targets`);
|
||||
return res.data.data as ResourceTargetsResponse;
|
||||
}
|
||||
});
|
||||
|
||||
if (isLoadingTargets) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsContainer>
|
||||
<PaidFeaturesAlert
|
||||
@@ -89,6 +103,7 @@ export default function SshSettingsPage(props: {
|
||||
resource={resource}
|
||||
updateResource={updateResource}
|
||||
disabled={disabled}
|
||||
targetsResponse={targetsResponse ?? { targets: [] }}
|
||||
/>
|
||||
</SettingsContainer>
|
||||
);
|
||||
@@ -98,232 +113,235 @@ function SshServerForm({
|
||||
orgId,
|
||||
resource,
|
||||
updateResource,
|
||||
disabled
|
||||
disabled,
|
||||
targetsResponse
|
||||
}: {
|
||||
orgId: string;
|
||||
resource: GetResourceResponse;
|
||||
updateResource: ResourceContextType["updateResource"];
|
||||
disabled: boolean;
|
||||
targetsResponse: ResourceTargetsResponse;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const api = createApiClient(useEnvContext());
|
||||
const router = useRouter();
|
||||
|
||||
const isNativeInitially = resource.authDaemonMode === "native";
|
||||
const targets = targetsResponse.targets.filter((t) => t.mode === "ssh");
|
||||
const firstTarget = targets[0];
|
||||
const initialPamMode =
|
||||
(resource.pamMode as "passthrough" | "push") || "passthrough";
|
||||
const initialStandardDaemonLocation = isNativeInitially
|
||||
? "site"
|
||||
: ((resource.authDaemonMode as "site" | "remote") || "site");
|
||||
const useSingleSiteOnLoad =
|
||||
!isNativeInitially &&
|
||||
initialPamMode === "push" &&
|
||||
initialStandardDaemonLocation === "site";
|
||||
|
||||
const [sshServerMode, setSshServerMode] = useState<"standard" | "native">(
|
||||
const [sshServerMode] = useState<"standard" | "native">(
|
||||
isNativeInitially ? "native" : "standard"
|
||||
);
|
||||
const isNative = sshServerMode === "native";
|
||||
|
||||
const [pamMode, setPamMode] = useState<"passthrough" | "push">(
|
||||
(resource.pamMode as "passthrough" | "push") || "passthrough"
|
||||
const formSchema = useMemo(
|
||||
() => createSshSettingsFormSchema(t, { isNative }),
|
||||
[t, isNative]
|
||||
);
|
||||
|
||||
const [standardDaemonLocation, setStandardDaemonLocation] = useState<
|
||||
"site" | "remote"
|
||||
>(
|
||||
isNativeInitially
|
||||
? "site"
|
||||
: (resource.authDaemonMode as "site" | "remote") || "site"
|
||||
);
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(sshFormSchema),
|
||||
const form = useForm<SshSettingsFormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
authDaemonPort: (resource as any).authDaemonPort
|
||||
? String((resource as any).authDaemonPort)
|
||||
: "22123"
|
||||
pamMode: initialPamMode,
|
||||
standardDaemonLocation: initialStandardDaemonLocation,
|
||||
authDaemonPort: (resource as { authDaemonPort?: number })
|
||||
.authDaemonPort
|
||||
? String((resource as { authDaemonPort?: number }).authDaemonPort)
|
||||
: "22123",
|
||||
selectedSites:
|
||||
isNativeInitially || useSingleSiteOnLoad
|
||||
? []
|
||||
: targets.map((target) => ({
|
||||
siteId: target.siteId,
|
||||
name: target.siteName ?? String(target.siteId),
|
||||
type: "newt" as const
|
||||
})),
|
||||
selectedSite:
|
||||
useSingleSiteOnLoad && firstTarget
|
||||
? {
|
||||
siteId: firstTarget.siteId,
|
||||
name:
|
||||
firstTarget.siteName ??
|
||||
String(firstTarget.siteId),
|
||||
type: "newt" as const
|
||||
}
|
||||
: null,
|
||||
selectedNativeSite:
|
||||
isNativeInitially && firstTarget
|
||||
? {
|
||||
siteId: firstTarget.siteId,
|
||||
name:
|
||||
firstTarget.siteName ??
|
||||
String(firstTarget.siteId),
|
||||
type: "newt" as const
|
||||
}
|
||||
: null,
|
||||
destination: isNativeInitially
|
||||
? ""
|
||||
: (firstTarget?.ip ?? ""),
|
||||
destinationPort: isNativeInitially
|
||||
? "22"
|
||||
: firstTarget
|
||||
? String(firstTarget.port)
|
||||
: "22"
|
||||
}
|
||||
});
|
||||
|
||||
// Standard mode: multi-site
|
||||
const [selectedSites, setSelectedSites] = useState<Selectedsite[]>([]);
|
||||
const [selectedSite, setSelectedSite] = useState<Selectedsite | null>(null);
|
||||
const [bgDestination, setBgDestination] = useState("");
|
||||
const [bgDestinationPort, setBgDestinationPort] = useState("22");
|
||||
const [existingTargets, setExistingTargets] = useState<ExistingTarget[]>(
|
||||
[]
|
||||
() =>
|
||||
isNativeInitially
|
||||
? []
|
||||
: targets.map((target) => ({
|
||||
targetId: target.targetId,
|
||||
siteId: target.siteId,
|
||||
}))
|
||||
);
|
||||
|
||||
// Native mode: single site
|
||||
const [selectedNativeSite, setSelectedNativeSite] =
|
||||
useState<Selectedsite | null>(null);
|
||||
const [nativeExistingTarget, setNativeExistingTarget] =
|
||||
useState<ExistingTarget | null>(null);
|
||||
useState<ExistingTarget | null>(() =>
|
||||
isNativeInitially && firstTarget
|
||||
? {
|
||||
targetId: firstTarget.targetId,
|
||||
siteId: firstTarget.siteId,
|
||||
}
|
||||
: null
|
||||
);
|
||||
const [nativeSiteOpen, setNativeSiteOpen] = useState(false);
|
||||
|
||||
const { data: bgTargetsResponse } = useQuery({
|
||||
queryKey: ["browserGatewayTargets", resource.resourceId, orgId],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(
|
||||
`/org/${orgId}/resource/${resource.resourceId}/browser-gateway-targets`
|
||||
);
|
||||
return res.data.data as {
|
||||
targets: Array<{
|
||||
browserGatewayTargetId: number;
|
||||
resourceId: number;
|
||||
siteId: number;
|
||||
siteName?: string;
|
||||
type: string;
|
||||
destination: string;
|
||||
destinationPort: number;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!bgTargetsResponse?.targets?.length) return;
|
||||
const targets = bgTargetsResponse.targets;
|
||||
const first = targets[0];
|
||||
if (isNativeInitially) {
|
||||
setSelectedNativeSite({
|
||||
siteId: first.siteId,
|
||||
name: first.siteName ?? String(first.siteId),
|
||||
type: "newt" as const
|
||||
});
|
||||
setNativeExistingTarget({
|
||||
browserGatewayTargetId: first.browserGatewayTargetId,
|
||||
siteId: first.siteId
|
||||
});
|
||||
} else {
|
||||
setBgDestination(first.destination);
|
||||
setBgDestinationPort(String(first.destinationPort));
|
||||
setExistingTargets(
|
||||
targets.map((t) => ({
|
||||
browserGatewayTargetId: t.browserGatewayTargetId,
|
||||
siteId: t.siteId
|
||||
}))
|
||||
);
|
||||
setSelectedSites(
|
||||
targets.map((t) => ({
|
||||
siteId: t.siteId,
|
||||
name: t.siteName ?? String(t.siteId),
|
||||
type: "newt" as const
|
||||
}))
|
||||
);
|
||||
}
|
||||
}, [bgTargetsResponse]);
|
||||
|
||||
const [, formAction, isSubmitting] = useActionState(save, null);
|
||||
|
||||
const pamMode = form.watch("pamMode");
|
||||
const standardDaemonLocation = form.watch("standardDaemonLocation");
|
||||
const selectedNativeSite = form.watch("selectedNativeSite");
|
||||
|
||||
async function save() {
|
||||
const isValid = await form.trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const effectiveMode = isNative ? "native" : standardDaemonLocation;
|
||||
const portVal = form.getValues().authDaemonPort;
|
||||
const values = form.getValues();
|
||||
const effectiveMode = isNative ? "native" : values.standardDaemonLocation;
|
||||
const effectivePort =
|
||||
!isNative && standardDaemonLocation === "remote" && portVal
|
||||
? Number(portVal)
|
||||
!isNative &&
|
||||
values.standardDaemonLocation === "remote" &&
|
||||
values.authDaemonPort
|
||||
? Number(values.authDaemonPort)
|
||||
: null;
|
||||
|
||||
try {
|
||||
await api.post(`/resource/${resource.resourceId}`, {
|
||||
pamMode,
|
||||
pamMode: values.pamMode,
|
||||
authDaemonMode: effectiveMode,
|
||||
authDaemonPort: effectivePort
|
||||
});
|
||||
|
||||
updateResource({
|
||||
...resource,
|
||||
pamMode,
|
||||
pamMode: values.pamMode,
|
||||
authDaemonMode: effectiveMode
|
||||
});
|
||||
|
||||
if (isNative) {
|
||||
if (selectedNativeSite) {
|
||||
const nativeSite = values.selectedNativeSite;
|
||||
if (nativeSite) {
|
||||
if (nativeExistingTarget) {
|
||||
await api.post(
|
||||
`/org/${orgId}/browser-gateway-target/${nativeExistingTarget.browserGatewayTargetId}`,
|
||||
`/target/${nativeExistingTarget.targetId}`,
|
||||
{
|
||||
type: "ssh",
|
||||
destination: "localhost",
|
||||
destinationPort: 22,
|
||||
siteId: selectedNativeSite.siteId
|
||||
}
|
||||
);
|
||||
} else {
|
||||
const res = await api.put(
|
||||
`/org/${orgId}/resource/${resource.resourceId}/browser-gateway-target`,
|
||||
{
|
||||
siteId: selectedNativeSite.siteId,
|
||||
type: "ssh",
|
||||
destination: "localhost",
|
||||
destinationPort: 22
|
||||
mode: "ssh",
|
||||
ip: "localhost",
|
||||
port: 22,
|
||||
siteId: nativeSite.siteId,
|
||||
hcEnabled: false
|
||||
}
|
||||
);
|
||||
setNativeExistingTarget({
|
||||
browserGatewayTargetId:
|
||||
res.data.data.browserGatewayTargetId,
|
||||
siteId: selectedNativeSite.siteId
|
||||
...nativeExistingTarget,
|
||||
siteId: nativeSite.siteId
|
||||
});
|
||||
} else {
|
||||
const res = await api.put(
|
||||
`/resource/${resource.resourceId}/target`,
|
||||
{
|
||||
siteId: nativeSite.siteId,
|
||||
mode: "ssh",
|
||||
ip: "localhost",
|
||||
port: 22,
|
||||
hcEnabled: false
|
||||
}
|
||||
);
|
||||
setNativeExistingTarget({
|
||||
targetId: res.data.data.targetId,
|
||||
siteId: nativeSite.siteId,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (bgDestination && bgDestinationPort) {
|
||||
const selectedSiteIds = new Set(
|
||||
selectedSites.map((s) => s.siteId)
|
||||
);
|
||||
const existingSiteIds = new Set(
|
||||
existingTargets.map((t) => t.siteId)
|
||||
);
|
||||
const useMultiSite =
|
||||
values.standardDaemonLocation !== "site" ||
|
||||
values.pamMode === "passthrough";
|
||||
const activeSites = useMultiSite
|
||||
? values.selectedSites
|
||||
: values.selectedSite
|
||||
? [values.selectedSite]
|
||||
: [];
|
||||
const selectedSiteIds = new Set(
|
||||
activeSites.map((s) => s.siteId)
|
||||
);
|
||||
const existingSiteIds = new Set(
|
||||
existingTargets.map((t) => t.siteId)
|
||||
);
|
||||
|
||||
const toDelete = existingTargets.filter(
|
||||
(t) => !selectedSiteIds.has(t.siteId)
|
||||
);
|
||||
await Promise.all(
|
||||
toDelete.map((t) =>
|
||||
api.delete(
|
||||
`/org/${orgId}/browser-gateway-target/${t.browserGatewayTargetId}`
|
||||
)
|
||||
)
|
||||
);
|
||||
const toDelete = existingTargets.filter(
|
||||
(t) => !selectedSiteIds.has(t.siteId)
|
||||
);
|
||||
await Promise.all(
|
||||
toDelete.map((t) => api.delete(`/target/${t.targetId}`))
|
||||
);
|
||||
|
||||
const toUpdate = existingTargets.filter((t) =>
|
||||
selectedSiteIds.has(t.siteId)
|
||||
);
|
||||
await Promise.all(
|
||||
toUpdate.map((t) =>
|
||||
api.post(
|
||||
`/org/${orgId}/browser-gateway-target/${t.browserGatewayTargetId}`,
|
||||
{
|
||||
type: "ssh",
|
||||
destination: bgDestination,
|
||||
destinationPort: Number(bgDestinationPort),
|
||||
siteId: t.siteId
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
const toCreate = selectedSites.filter(
|
||||
(s) => !existingSiteIds.has(s.siteId)
|
||||
);
|
||||
const created = await Promise.all(
|
||||
toCreate.map((s) =>
|
||||
api.put(
|
||||
`/org/${orgId}/resource/${resource.resourceId}/browser-gateway-target`,
|
||||
{
|
||||
siteId: s.siteId,
|
||||
type: "ssh",
|
||||
destination: bgDestination,
|
||||
destinationPort: Number(bgDestinationPort)
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
const newTargets: ExistingTarget[] = created.map(
|
||||
(res, i) => ({
|
||||
browserGatewayTargetId:
|
||||
res.data.data.browserGatewayTargetId,
|
||||
siteId: toCreate[i].siteId
|
||||
const toUpdate = existingTargets.filter((t) =>
|
||||
selectedSiteIds.has(t.siteId)
|
||||
);
|
||||
await Promise.all(
|
||||
toUpdate.map((t) =>
|
||||
api.post(`/target/${t.targetId}`, {
|
||||
mode: "ssh",
|
||||
ip: values.destination,
|
||||
port: Number(values.destinationPort),
|
||||
siteId: t.siteId,
|
||||
hcEnabled: false
|
||||
})
|
||||
);
|
||||
setExistingTargets([...toUpdate, ...newTargets]);
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
const toCreate = activeSites.filter(
|
||||
(s) => !existingSiteIds.has(s.siteId)
|
||||
);
|
||||
const created = await Promise.all(
|
||||
toCreate.map((s) =>
|
||||
api.put(`/resource/${resource.resourceId}/target`, {
|
||||
siteId: s.siteId,
|
||||
mode: "ssh",
|
||||
ip: values.destination,
|
||||
port: Number(values.destinationPort),
|
||||
hcEnabled: false
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const newTargets: ExistingTarget[] = created.map((res, i) => ({
|
||||
targetId: res.data.data.targetId,
|
||||
siteId: toCreate[i].siteId,
|
||||
}));
|
||||
setExistingTargets([...toUpdate, ...newTargets]);
|
||||
}
|
||||
|
||||
toast({
|
||||
@@ -373,6 +391,9 @@ function SshServerForm({
|
||||
const showDaemonLocation = !isNative && pamMode === "push";
|
||||
const showDaemonPort =
|
||||
!isNative && pamMode === "push" && standardDaemonLocation === "remote";
|
||||
const useMultiSiteTargetForm =
|
||||
!isNative &&
|
||||
(standardDaemonLocation !== "site" || pamMode === "passthrough");
|
||||
|
||||
return (
|
||||
<SettingsSection>
|
||||
@@ -386,160 +407,189 @@ function SshServerForm({
|
||||
disabled={disabled}
|
||||
className={disabled ? "opacity-50 pointer-events-none" : ""}
|
||||
>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm variant="half">
|
||||
<div className="space-y-3">
|
||||
<SettingsSubsectionTitle>
|
||||
{t("sshServerMode")}
|
||||
</SettingsSubsectionTitle>
|
||||
<Badge variant="secondary">
|
||||
{sshServerMode == "standard"
|
||||
? t("sshServerModeStandard")
|
||||
: t("sshServerModePangolin")}
|
||||
</Badge>
|
||||
</div>
|
||||
<Form {...form}>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm variant="half">
|
||||
<div className="space-y-2">
|
||||
<p className="font-semibold text-sm">{t("sshServerMode")}</p>
|
||||
<Badge variant="secondary">
|
||||
{sshServerMode == "standard"
|
||||
? t("sshServerModeStandard")
|
||||
: t("sshServerModePangolin")}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<SettingsSubsectionTitle>
|
||||
{t("sshAuthenticationMethod")}
|
||||
</SettingsSubsectionTitle>
|
||||
<StrategySelect<"passthrough" | "push">
|
||||
value={pamMode}
|
||||
options={authMethodOptions}
|
||||
onChange={setPamMode}
|
||||
cols={2}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<p className="font-semibold text-sm">{t("sshAuthenticationMethod")}</p>
|
||||
<StrategySelect<"passthrough" | "push">
|
||||
value={pamMode}
|
||||
options={authMethodOptions}
|
||||
onChange={(value) =>
|
||||
form.setValue("pamMode", value, {
|
||||
shouldValidate: true
|
||||
})
|
||||
}
|
||||
cols={2}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{showDaemonLocation && (
|
||||
<div className="space-y-3">
|
||||
<SettingsSubsectionTitle>
|
||||
{t("sshAuthDaemonLocation")}
|
||||
</SettingsSubsectionTitle>
|
||||
<StrategySelect<"site" | "remote">
|
||||
value={standardDaemonLocation}
|
||||
options={daemonLocationOptions}
|
||||
onChange={setStandardDaemonLocation}
|
||||
cols={2}
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("sshDaemonDisclaimer")}{" "}
|
||||
<a
|
||||
href="https://docs.pangolin.net/manage/resources/public/ssh"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
{t("learnMore")}
|
||||
<ExternalLink className="size-3.5 shrink-0" />
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showDaemonPort && (
|
||||
<Form {...form}>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="authDaemonPort"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("sshDaemonPort")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</Form>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<SettingsSubsectionHeader>
|
||||
<SettingsSubsectionTitle>
|
||||
{t("sshServerDestination")}
|
||||
</SettingsSubsectionTitle>
|
||||
<SettingsSubsectionDescription>
|
||||
{t("sshServerDestinationDescription")}
|
||||
</SettingsSubsectionDescription>
|
||||
</SettingsSubsectionHeader>
|
||||
{isNative ? (
|
||||
<Popover
|
||||
open={nativeSiteOpen}
|
||||
onOpenChange={setNativeSiteOpen}
|
||||
>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
className="w-full max-w-xs justify-between font-normal"
|
||||
>
|
||||
<span className="truncate">
|
||||
{selectedNativeSite?.name ??
|
||||
t("siteSelect")}
|
||||
</span>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
|
||||
<SitesSelector
|
||||
orgId={orgId}
|
||||
selectedSite={selectedNativeSite}
|
||||
onSelectSite={(site) => {
|
||||
setSelectedNativeSite(site);
|
||||
setNativeSiteOpen(false);
|
||||
}}
|
||||
{showDaemonLocation && (
|
||||
<div className="space-y-2">
|
||||
<p className="font-semibold text-sm">{t("sshAuthDaemonLocation")}</p>
|
||||
<StrategySelect<"site" | "remote">
|
||||
value={standardDaemonLocation}
|
||||
options={daemonLocationOptions}
|
||||
onChange={(value) =>
|
||||
form.setValue(
|
||||
"standardDaemonLocation",
|
||||
value,
|
||||
{ shouldValidate: true }
|
||||
)
|
||||
}
|
||||
cols={2}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
) : standardDaemonLocation !== "site" ||
|
||||
pamMode === "passthrough" ? (
|
||||
<BrowserGatewayTargetForm
|
||||
orgId={orgId}
|
||||
multiSite={true}
|
||||
selectedSites={selectedSites}
|
||||
onSitesChange={setSelectedSites}
|
||||
destination={bgDestination}
|
||||
destinationPort={bgDestinationPort}
|
||||
onDestinationChange={setBgDestination}
|
||||
onDestinationPortChange={setBgDestinationPort}
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh"
|
||||
defaultPort={22}
|
||||
/>
|
||||
) : (
|
||||
<BrowserGatewayTargetForm
|
||||
orgId={orgId}
|
||||
multiSite={false}
|
||||
selectedSite={selectedSite}
|
||||
onSiteChange={setSelectedSite}
|
||||
destination={bgDestination}
|
||||
destinationPort={bgDestinationPort}
|
||||
onDestinationChange={setBgDestination}
|
||||
onDestinationPortChange={setBgDestinationPort}
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh"
|
||||
defaultPort={22}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</SettingsSectionForm>
|
||||
</SettingsSectionBody>
|
||||
<form action={formAction} className="flex justify-end mt-4">
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
type="submit"
|
||||
>
|
||||
{t("saveSettings")}
|
||||
</Button>
|
||||
</form>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("sshDaemonDisclaimer")}{" "}
|
||||
<a
|
||||
href="https://docs.pangolin.net/manage/resources/public/ssh"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
{t("learnMore")}
|
||||
<ExternalLink className="size-3.5 shrink-0" />
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showDaemonPort && (
|
||||
<div className="w-full md:w-1/2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="authDaemonPort"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("sshDaemonPort")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<SettingsSubsectionHeader>
|
||||
<SettingsSubsectionTitle>
|
||||
{t("sshServerDestination")}
|
||||
</SettingsSubsectionTitle>
|
||||
<SettingsSubsectionDescription>
|
||||
{t("sshServerDestinationDescription")}
|
||||
</SettingsSubsectionDescription>
|
||||
</SettingsSubsectionHeader>
|
||||
{isNative ? (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="selectedNativeSite"
|
||||
render={() => (
|
||||
<FormItem>
|
||||
<Popover
|
||||
open={nativeSiteOpen}
|
||||
onOpenChange={
|
||||
setNativeSiteOpen
|
||||
}
|
||||
>
|
||||
<PopoverTrigger asChild>
|
||||
<FormControl>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
className="w-full max-w-xs justify-between font-normal"
|
||||
>
|
||||
<span className="truncate">
|
||||
{selectedNativeSite?.name ??
|
||||
t(
|
||||
"siteSelect"
|
||||
)}
|
||||
</span>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</FormControl>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
|
||||
<SitesSelector
|
||||
orgId={orgId}
|
||||
selectedSite={
|
||||
selectedNativeSite
|
||||
}
|
||||
onSelectSite={(
|
||||
site
|
||||
) => {
|
||||
form.setValue(
|
||||
"selectedNativeSite",
|
||||
site,
|
||||
{
|
||||
shouldValidate:
|
||||
true
|
||||
}
|
||||
);
|
||||
setNativeSiteOpen(
|
||||
false
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
) : useMultiSiteTargetForm ? (
|
||||
<BrowserGatewayTargetForm
|
||||
control={form.control}
|
||||
orgId={orgId}
|
||||
multiSite={true}
|
||||
sitesField="selectedSites"
|
||||
destinationField="destination"
|
||||
destinationPortField="destinationPort"
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh"
|
||||
defaultPort={22}
|
||||
/>
|
||||
) : (
|
||||
<BrowserGatewayTargetForm
|
||||
control={form.control}
|
||||
orgId={orgId}
|
||||
multiSite={false}
|
||||
siteField="selectedSite"
|
||||
destinationField="destination"
|
||||
destinationPortField="destinationPort"
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh"
|
||||
defaultPort={22}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</SettingsSectionForm>
|
||||
</SettingsSectionBody>
|
||||
<form action={formAction} className="flex justify-end mt-4">
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
type="submit"
|
||||
>
|
||||
{t("saveSettings")}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</fieldset>
|
||||
</SettingsSection>
|
||||
);
|
||||
|
||||
@@ -11,199 +11,183 @@ import {
|
||||
} from "@app/components/Settings";
|
||||
import { BrowserGatewayTargetForm } from "@app/components/BrowserGatewayTargetForm";
|
||||
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
|
||||
import { type Selectedsite } from "@app/components/site-selector";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { Form } from "@app/components/ui/form";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { useResourceContext } from "@app/hooks/useResourceContext";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { usePaidStatus } from "@app/hooks/usePaidStatus";
|
||||
import { createBrowserGatewayTargetFormSchema } from "@app/lib/browserGatewayTargetFormSchema";
|
||||
import type { BrowserGatewayTargetFormValues } from "@app/lib/browserGatewayTargetFormSchema";
|
||||
import { tierMatrix, TierFeature } from "@server/lib/billing/tierMatrix";
|
||||
import { createApiClient } from "@app/lib/api";
|
||||
import { formatAxiosError } from "@app/lib/api/formatAxiosError";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { use, useActionState, useEffect, useState } from "react";
|
||||
import { z } from "zod";
|
||||
import { use, useActionState, useMemo, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { GetResourceResponse } from "@server/routers/resource";
|
||||
import type { ResourceContextType } from "@app/contexts/resourceContext";
|
||||
|
||||
type ExistingTarget = {
|
||||
browserGatewayTargetId: number;
|
||||
targetId: number;
|
||||
siteId: number;
|
||||
};
|
||||
|
||||
const sshFormSchema = z.object({
|
||||
authDaemonPort: z.string().refine(
|
||||
(val) => {
|
||||
if (!val) return true;
|
||||
const n = Number(val);
|
||||
return Number.isInteger(n) && n >= 1 && n <= 65535;
|
||||
},
|
||||
{ message: "Port must be between 1 and 65535" }
|
||||
)
|
||||
});
|
||||
type TargetRow = {
|
||||
targetId: number;
|
||||
resourceId: number;
|
||||
siteId: number;
|
||||
siteName?: string;
|
||||
mode: string | null;
|
||||
ip: string;
|
||||
port: number;
|
||||
};
|
||||
|
||||
export default function SshSettingsPage(props: {
|
||||
type ResourceTargetsResponse = {
|
||||
targets: TargetRow[];
|
||||
};
|
||||
|
||||
export default function VncSettingsPage(props: {
|
||||
params: Promise<{ orgId: string }>;
|
||||
}) {
|
||||
const params = use(props.params);
|
||||
const { resource, updateResource } = useResourceContext();
|
||||
const { isPaidUser } = usePaidStatus();
|
||||
const api = createApiClient(useEnvContext());
|
||||
const disabled = !isPaidUser(
|
||||
tierMatrix[TierFeature.AdvancedPublicResources]
|
||||
);
|
||||
|
||||
const { data: targetsResponse, isLoading: isLoadingTargets } = useQuery({
|
||||
queryKey: ["resourceTargets", resource.resourceId, params.orgId, "vnc"],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/resource/${resource.resourceId}/targets`);
|
||||
return res.data.data as ResourceTargetsResponse;
|
||||
}
|
||||
});
|
||||
|
||||
if (isLoadingTargets) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsContainer>
|
||||
<PaidFeaturesAlert
|
||||
tiers={tierMatrix[TierFeature.AdvancedPublicResources]}
|
||||
/>
|
||||
<SshServerForm
|
||||
<VncServerForm
|
||||
orgId={params.orgId}
|
||||
resource={resource}
|
||||
updateResource={updateResource}
|
||||
disabled={disabled}
|
||||
targetsResponse={targetsResponse ?? { targets: [] }}
|
||||
/>
|
||||
</SettingsContainer>
|
||||
);
|
||||
}
|
||||
|
||||
function SshServerForm({
|
||||
function VncServerForm({
|
||||
orgId,
|
||||
resource,
|
||||
updateResource,
|
||||
disabled
|
||||
disabled,
|
||||
targetsResponse
|
||||
}: {
|
||||
orgId: string;
|
||||
resource: GetResourceResponse;
|
||||
updateResource: ResourceContextType["updateResource"];
|
||||
disabled: boolean;
|
||||
targetsResponse: ResourceTargetsResponse;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const api = createApiClient(useEnvContext());
|
||||
const router = useRouter();
|
||||
const targets = targetsResponse.targets.filter((t) => t.mode === "vnc");
|
||||
const firstTarget = targets[0];
|
||||
|
||||
// Standard mode: multi-site
|
||||
const [selectedSites, setSelectedSites] = useState<Selectedsite[]>([]);
|
||||
const [bgDestination, setBgDestination] = useState("");
|
||||
const [bgDestinationPort, setBgDestinationPort] = useState("22");
|
||||
const [existingTargets, setExistingTargets] = useState<ExistingTarget[]>(
|
||||
[]
|
||||
const formSchema = useMemo(
|
||||
() => createBrowserGatewayTargetFormSchema(t),
|
||||
[t]
|
||||
);
|
||||
|
||||
// Native mode: single site
|
||||
const [selectedNativeSite, setSelectedNativeSite] =
|
||||
useState<Selectedsite | null>(null);
|
||||
const [nativeExistingTarget, setNativeExistingTarget] =
|
||||
useState<ExistingTarget | null>(null);
|
||||
|
||||
const { data: bgTargetsResponse } = useQuery({
|
||||
queryKey: ["browserGatewayTargets", resource.resourceId, orgId],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(
|
||||
`/org/${orgId}/resource/${resource.resourceId}/browser-gateway-targets`
|
||||
);
|
||||
return res.data.data as {
|
||||
targets: Array<{
|
||||
browserGatewayTargetId: number;
|
||||
resourceId: number;
|
||||
siteId: number;
|
||||
siteName?: string;
|
||||
type: string;
|
||||
destination: string;
|
||||
destinationPort: number;
|
||||
}>;
|
||||
};
|
||||
const form = useForm<BrowserGatewayTargetFormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
selectedSites: targets.map((target) => ({
|
||||
siteId: target.siteId,
|
||||
name: target.siteName ?? String(target.siteId),
|
||||
type: "newt" as const
|
||||
})),
|
||||
destination: firstTarget?.ip ?? "",
|
||||
destinationPort: firstTarget ? String(firstTarget.port) : "5900"
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!bgTargetsResponse?.targets?.length) return;
|
||||
const targets = bgTargetsResponse.targets;
|
||||
const first = targets[0];
|
||||
|
||||
setBgDestination(first.destination);
|
||||
setBgDestinationPort(String(first.destinationPort));
|
||||
setExistingTargets(
|
||||
targets.map((t) => ({
|
||||
browserGatewayTargetId: t.browserGatewayTargetId,
|
||||
siteId: t.siteId
|
||||
const [existingTargets, setExistingTargets] = useState<ExistingTarget[]>(
|
||||
() =>
|
||||
targets.map((target) => ({
|
||||
targetId: target.targetId,
|
||||
siteId: target.siteId
|
||||
}))
|
||||
);
|
||||
setSelectedSites(
|
||||
targets.map((t) => ({
|
||||
siteId: t.siteId,
|
||||
name: t.siteName ?? String(t.siteId),
|
||||
type: "newt" as const
|
||||
}))
|
||||
);
|
||||
}, [bgTargetsResponse]);
|
||||
);
|
||||
|
||||
const [, formAction, isSubmitting] = useActionState(save, null);
|
||||
|
||||
async function save() {
|
||||
const isValid = await form.trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const { selectedSites, destination, destinationPort } =
|
||||
form.getValues();
|
||||
|
||||
try {
|
||||
if (bgDestination && bgDestinationPort) {
|
||||
const selectedSiteIds = new Set(
|
||||
selectedSites.map((s) => s.siteId)
|
||||
);
|
||||
const existingSiteIds = new Set(
|
||||
existingTargets.map((t) => t.siteId)
|
||||
);
|
||||
const selectedSiteIds = new Set(selectedSites.map((s) => s.siteId));
|
||||
const existingSiteIds = new Set(
|
||||
existingTargets.map((t) => t.siteId)
|
||||
);
|
||||
|
||||
const toDelete = existingTargets.filter(
|
||||
(t) => !selectedSiteIds.has(t.siteId)
|
||||
);
|
||||
await Promise.all(
|
||||
toDelete.map((t) =>
|
||||
api.delete(
|
||||
`/org/${orgId}/browser-gateway-target/${t.browserGatewayTargetId}`
|
||||
)
|
||||
)
|
||||
);
|
||||
const toDelete = existingTargets.filter(
|
||||
(t) => !selectedSiteIds.has(t.siteId)
|
||||
);
|
||||
await Promise.all(toDelete.map((t) => api.delete(`/target/${t.targetId}`)));
|
||||
|
||||
const toUpdate = existingTargets.filter((t) =>
|
||||
selectedSiteIds.has(t.siteId)
|
||||
);
|
||||
await Promise.all(
|
||||
toUpdate.map((t) =>
|
||||
api.post(
|
||||
`/org/${orgId}/browser-gateway-target/${t.browserGatewayTargetId}`,
|
||||
{
|
||||
type: "vnc",
|
||||
destination: bgDestination,
|
||||
destinationPort: Number(bgDestinationPort),
|
||||
siteId: t.siteId
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
const toUpdate = existingTargets.filter((t) =>
|
||||
selectedSiteIds.has(t.siteId)
|
||||
);
|
||||
await Promise.all(
|
||||
toUpdate.map((t) =>
|
||||
api.post(`/target/${t.targetId}`, {
|
||||
mode: "vnc",
|
||||
ip: destination,
|
||||
port: Number(destinationPort),
|
||||
siteId: t.siteId,
|
||||
hcEnabled: false
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const toCreate = selectedSites.filter(
|
||||
(s) => !existingSiteIds.has(s.siteId)
|
||||
);
|
||||
const created = await Promise.all(
|
||||
toCreate.map((s) =>
|
||||
api.put(
|
||||
`/org/${orgId}/resource/${resource.resourceId}/browser-gateway-target`,
|
||||
{
|
||||
siteId: s.siteId,
|
||||
type: "vnc",
|
||||
destination: bgDestination,
|
||||
destinationPort: Number(bgDestinationPort)
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
const toCreate = selectedSites.filter(
|
||||
(s) => !existingSiteIds.has(s.siteId)
|
||||
);
|
||||
const created = await Promise.all(
|
||||
toCreate.map((s) =>
|
||||
api.put(`/resource/${resource.resourceId}/target`, {
|
||||
siteId: s.siteId,
|
||||
mode: "vnc",
|
||||
ip: destination,
|
||||
port: Number(destinationPort),
|
||||
hcEnabled: false
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const newTargets: ExistingTarget[] = created.map((res, i) => ({
|
||||
browserGatewayTargetId:
|
||||
res.data.data.browserGatewayTargetId,
|
||||
siteId: toCreate[i].siteId
|
||||
}));
|
||||
setExistingTargets([...toUpdate, ...newTargets]);
|
||||
}
|
||||
const newTargets: ExistingTarget[] = created.map((res, i) => ({
|
||||
targetId: res.data.data.targetId,
|
||||
siteId: toCreate[i].siteId
|
||||
}));
|
||||
setExistingTargets([...toUpdate, ...newTargets]);
|
||||
|
||||
toast({
|
||||
title: t("settingsUpdated"),
|
||||
@@ -235,31 +219,31 @@ function SshServerForm({
|
||||
disabled={disabled}
|
||||
className={disabled ? "opacity-50 pointer-events-none" : ""}
|
||||
>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm variant="half">
|
||||
<BrowserGatewayTargetForm
|
||||
orgId={orgId}
|
||||
multiSite={true}
|
||||
selectedSites={selectedSites}
|
||||
onSitesChange={setSelectedSites}
|
||||
destination={bgDestination}
|
||||
destinationPort={bgDestinationPort}
|
||||
onDestinationChange={setBgDestination}
|
||||
onDestinationPortChange={setBgDestinationPort}
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/vnc"
|
||||
defaultPort={5900}
|
||||
/>
|
||||
</SettingsSectionForm>
|
||||
</SettingsSectionBody>
|
||||
<form action={formAction} className="flex justify-end mt-4">
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
type="submit"
|
||||
>
|
||||
{t("saveSettings")}
|
||||
</Button>
|
||||
</form>
|
||||
<Form {...form}>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm variant="half">
|
||||
<BrowserGatewayTargetForm
|
||||
control={form.control}
|
||||
orgId={orgId}
|
||||
multiSite={true}
|
||||
sitesField="selectedSites"
|
||||
destinationField="destination"
|
||||
destinationPortField="destinationPort"
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/vnc"
|
||||
defaultPort={5900}
|
||||
/>
|
||||
</SettingsSectionForm>
|
||||
</SettingsSectionBody>
|
||||
<form action={formAction} className="flex justify-end mt-4">
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
type="submit"
|
||||
>
|
||||
{t("saveSettings")}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</fieldset>
|
||||
</SettingsSection>
|
||||
);
|
||||
|
||||
@@ -50,6 +50,12 @@ import { toast } from "@app/hooks/useToast";
|
||||
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
|
||||
import { tierMatrix, TierFeature } from "@server/lib/billing/tierMatrix";
|
||||
import { createApiClient, formatAxiosError } from "@app/lib/api";
|
||||
import {
|
||||
createBrowserGatewayTargetFormSchema,
|
||||
createSshSettingsFormSchema,
|
||||
selectedSiteSchema,
|
||||
type SshSettingsFormValues
|
||||
} from "@app/lib/browserGatewayTargetFormSchema";
|
||||
import { DockerManager, DockerState } from "@app/lib/docker";
|
||||
import { orgQueries } from "@app/lib/queries";
|
||||
import { finalizeSubdomainSanitize } from "@app/lib/subdomain-utils";
|
||||
@@ -79,100 +85,134 @@ import {
|
||||
useTransition,
|
||||
useEffect
|
||||
} from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useForm, type Resolver } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
const baseResourceFormSchema = z.object({
|
||||
name: z.string().min(1).max(255),
|
||||
http: z.boolean()
|
||||
});
|
||||
type TranslateFn = (key: string) => string;
|
||||
|
||||
const httpResourceFormSchema = z.object({
|
||||
domainId: z.string().nonempty(),
|
||||
subdomain: z.string().optional()
|
||||
});
|
||||
function createBaseResourceFormSchema(t: TranslateFn) {
|
||||
return z.object({
|
||||
name: z
|
||||
.string()
|
||||
.min(1, { message: t("nameRequired") })
|
||||
.max(255, {
|
||||
message: t("createInternalResourceDialogNameMaxLength")
|
||||
}),
|
||||
http: z.boolean()
|
||||
});
|
||||
}
|
||||
|
||||
const tcpUdpResourceFormSchema = z.object({
|
||||
protocol: z.string(),
|
||||
proxyPort: z.int().min(1).max(65535)
|
||||
});
|
||||
function createHttpResourceFormSchema(t: TranslateFn) {
|
||||
return z.object({
|
||||
domainId: z.string().min(1, { message: t("domainRequired") }),
|
||||
subdomain: z.string().optional()
|
||||
});
|
||||
}
|
||||
|
||||
const sshDaemonPortSchema = z.object({
|
||||
authDaemonPort: z.string().refine(
|
||||
(val) => {
|
||||
if (!val) return true;
|
||||
const n = Number(val);
|
||||
return Number.isInteger(n) && n >= 1 && n <= 65535;
|
||||
},
|
||||
{ message: "Port must be between 1 and 65535" }
|
||||
)
|
||||
});
|
||||
function createTcpUdpResourceFormSchema(t: TranslateFn) {
|
||||
return z.object({
|
||||
protocol: z.string(),
|
||||
proxyPort: z
|
||||
.number({ error: t("proxyPortRequired") })
|
||||
.int({ error: t("healthCheckPortInvalid") })
|
||||
.min(1, { message: t("healthCheckPortInvalid") })
|
||||
.max(65535, { message: t("healthCheckPortInvalid") })
|
||||
});
|
||||
}
|
||||
|
||||
const addTargetSchema = z
|
||||
.object({
|
||||
ip: z.string().refine(isTargetValid),
|
||||
method: z.string().nullable(),
|
||||
port: z.coerce.number<number>().int().positive(),
|
||||
siteId: z.int().positive(),
|
||||
path: z.string().optional().nullable(),
|
||||
pathMatchType: z
|
||||
.enum(["exact", "prefix", "regex"])
|
||||
.optional()
|
||||
.nullable(),
|
||||
rewritePath: z.string().optional().nullable(),
|
||||
rewritePathType: z
|
||||
.enum(["exact", "prefix", "regex", "stripPrefix"])
|
||||
.optional()
|
||||
.nullable(),
|
||||
priority: z.int().min(1).max(1000).optional()
|
||||
})
|
||||
.refine(
|
||||
(data) => {
|
||||
if (data.path && !data.pathMatchType) {
|
||||
return false;
|
||||
}
|
||||
if (data.pathMatchType && !data.path) {
|
||||
return false;
|
||||
}
|
||||
if (data.path && data.pathMatchType) {
|
||||
switch (data.pathMatchType) {
|
||||
case "exact":
|
||||
case "prefix":
|
||||
return data.path.startsWith("/");
|
||||
case "regex":
|
||||
try {
|
||||
new RegExp(data.path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
error: "Invalid path configuration"
|
||||
}
|
||||
)
|
||||
.refine(
|
||||
(data) => {
|
||||
if (data.rewritePath && !data.rewritePathType) {
|
||||
return false;
|
||||
}
|
||||
if (data.rewritePathType && !data.rewritePath) {
|
||||
if (data.rewritePathType !== "stripPrefix") {
|
||||
function createSshDaemonPortSchema(t: TranslateFn) {
|
||||
return z.object({
|
||||
authDaemonPort: z.string().refine(
|
||||
(val) => {
|
||||
if (!val) return true;
|
||||
const n = Number(val);
|
||||
return Number.isInteger(n) && n >= 1 && n <= 65535;
|
||||
},
|
||||
{ message: t("healthCheckPortInvalid") }
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
function createAddTargetSchema(t: TranslateFn) {
|
||||
return z
|
||||
.object({
|
||||
ip: z.string().refine(isTargetValid, {
|
||||
message: t("targetErrorInvalidIpDescription")
|
||||
}),
|
||||
method: z.string().nullable(),
|
||||
port: z.coerce
|
||||
.number<number>({ error: t("targetErrorInvalidPortDescription") })
|
||||
.int({ error: t("targetErrorInvalidPortDescription") })
|
||||
.positive({ error: t("targetErrorInvalidPortDescription") }),
|
||||
siteId: z
|
||||
.int({ error: t("siteRequired") })
|
||||
.positive({ error: t("siteRequired") }),
|
||||
path: z.string().optional().nullable(),
|
||||
pathMatchType: z
|
||||
.enum(["exact", "prefix", "regex"])
|
||||
.optional()
|
||||
.nullable(),
|
||||
rewritePath: z.string().optional().nullable(),
|
||||
rewritePathType: z
|
||||
.enum(["exact", "prefix", "regex", "stripPrefix"])
|
||||
.optional()
|
||||
.nullable(),
|
||||
priority: z
|
||||
.int()
|
||||
.min(1, { message: t("healthCheckPortInvalid") })
|
||||
.max(1000, { message: t("healthCheckPortInvalid") })
|
||||
.optional()
|
||||
})
|
||||
.refine(
|
||||
(data) => {
|
||||
if (data.path && !data.pathMatchType) {
|
||||
return false;
|
||||
}
|
||||
if (data.pathMatchType && !data.path) {
|
||||
return false;
|
||||
}
|
||||
if (data.path && data.pathMatchType) {
|
||||
switch (data.pathMatchType) {
|
||||
case "exact":
|
||||
case "prefix":
|
||||
return data.path.startsWith("/");
|
||||
case "regex":
|
||||
try {
|
||||
new RegExp(data.path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
message: t("invalidPathConfiguration")
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
error: "Invalid rewrite path configuration"
|
||||
}
|
||||
);
|
||||
)
|
||||
.refine(
|
||||
(data) => {
|
||||
if (data.rewritePath && !data.rewritePathType) {
|
||||
return false;
|
||||
}
|
||||
if (data.rewritePathType && !data.rewritePath) {
|
||||
if (data.rewritePathType !== "stripPrefix") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
message: t("invalidRewritePathConfiguration")
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
type NewResourceType = "http" | "ssh" | "rdp" | "vnc" | "tcp" | "udp";
|
||||
|
||||
type CreateBgTargetFormValues = SshSettingsFormValues;
|
||||
|
||||
export default function Page() {
|
||||
const { env } = useEnvContext();
|
||||
const api = createApiClient({ env });
|
||||
@@ -223,29 +263,6 @@ export default function Page() {
|
||||
useState<Selectedsite | null>(null);
|
||||
const [nativeSiteOpen, setNativeSiteOpen] = useState(false);
|
||||
|
||||
// Browser-gateway targets state (SSH standard, RDP, VNC)
|
||||
const [bgSelectedSites, setBgSelectedSites] = useState<Selectedsite[]>([]);
|
||||
const [bgSelectedSite, setBgSelectedSite] = useState<Selectedsite | null>(
|
||||
null
|
||||
);
|
||||
const [bgDestination, setBgDestination] = useState("");
|
||||
const [bgDestinationPort, setBgDestinationPort] = useState("22");
|
||||
|
||||
// Reset BG state when resource type changes
|
||||
useEffect(() => {
|
||||
if (resourceType === "rdp") {
|
||||
setBgDestinationPort("3389");
|
||||
} else if (resourceType === "vnc") {
|
||||
setBgDestinationPort("5900");
|
||||
} else if (resourceType === "ssh") {
|
||||
setBgDestinationPort("22");
|
||||
}
|
||||
setBgDestination("");
|
||||
setBgSelectedSites([]);
|
||||
setBgSelectedSite(null);
|
||||
setNativeSelectedSite(null);
|
||||
}, [resourceType]);
|
||||
|
||||
useEffect(() => {
|
||||
if (build !== "saas") return;
|
||||
|
||||
@@ -278,6 +295,39 @@ export default function Page() {
|
||||
pamMode === "push" &&
|
||||
standardDaemonLocation === "remote";
|
||||
|
||||
const bgTargetFormSchema = useMemo(() => {
|
||||
if (resourceType === "ssh" && !isNative) {
|
||||
return createSshSettingsFormSchema(t, { isNative: false });
|
||||
}
|
||||
if (resourceType === "rdp" || resourceType === "vnc") {
|
||||
return createBrowserGatewayTargetFormSchema(t);
|
||||
}
|
||||
return z.object({
|
||||
selectedSites: z.array(selectedSiteSchema),
|
||||
selectedSite: selectedSiteSchema.nullable(),
|
||||
destination: z.string(),
|
||||
destinationPort: z.string(),
|
||||
pamMode: z.enum(["passthrough", "push"]),
|
||||
standardDaemonLocation: z.enum(["site", "remote"])
|
||||
});
|
||||
}, [resourceType, isNative, t]);
|
||||
|
||||
const bgTargetForm = useForm<CreateBgTargetFormValues>({
|
||||
resolver: zodResolver(
|
||||
bgTargetFormSchema
|
||||
) as unknown as Resolver<CreateBgTargetFormValues>,
|
||||
defaultValues: {
|
||||
selectedSites: [],
|
||||
selectedSite: null,
|
||||
selectedNativeSite: null,
|
||||
destination: "",
|
||||
destinationPort: "22",
|
||||
pamMode: "passthrough",
|
||||
standardDaemonLocation: "site",
|
||||
authDaemonPort: "22123"
|
||||
}
|
||||
});
|
||||
|
||||
// Whether raw (TCP/UDP) resources are available
|
||||
const rawResourcesAllowed =
|
||||
env.flags.allowRawResources &&
|
||||
@@ -302,6 +352,24 @@ export default function Page() {
|
||||
}
|
||||
}, [availableTypes, resourceType]);
|
||||
|
||||
const baseResourceFormSchema = useMemo(
|
||||
() => createBaseResourceFormSchema(t),
|
||||
[t]
|
||||
);
|
||||
const httpResourceFormSchema = useMemo(
|
||||
() => createHttpResourceFormSchema(t),
|
||||
[t]
|
||||
);
|
||||
const tcpUdpResourceFormSchema = useMemo(
|
||||
() => createTcpUdpResourceFormSchema(t),
|
||||
[t]
|
||||
);
|
||||
const sshDaemonPortSchema = useMemo(
|
||||
() => createSshDaemonPortSchema(t),
|
||||
[t]
|
||||
);
|
||||
const addTargetSchema = useMemo(() => createAddTargetSchema(t), [t]);
|
||||
|
||||
const baseForm = useForm({
|
||||
resolver: zodResolver(baseResourceFormSchema),
|
||||
defaultValues: {
|
||||
@@ -330,6 +398,31 @@ export default function Page() {
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const defaultPort =
|
||||
resourceType === "rdp"
|
||||
? "3389"
|
||||
: resourceType === "vnc"
|
||||
? "5900"
|
||||
: "22";
|
||||
bgTargetForm.reset({
|
||||
selectedSites: [],
|
||||
selectedSite: null,
|
||||
selectedNativeSite: null,
|
||||
destination: "",
|
||||
destinationPort: defaultPort,
|
||||
pamMode,
|
||||
standardDaemonLocation,
|
||||
authDaemonPort: sshDaemonPortForm.getValues().authDaemonPort
|
||||
});
|
||||
setNativeSelectedSite(null);
|
||||
}, [resourceType]);
|
||||
|
||||
useEffect(() => {
|
||||
bgTargetForm.setValue("pamMode", pamMode);
|
||||
bgTargetForm.setValue("standardDaemonLocation", standardDaemonLocation);
|
||||
}, [pamMode, standardDaemonLocation]);
|
||||
|
||||
// Sync form http field with resourceType
|
||||
useEffect(() => {
|
||||
baseForm.setValue("http", isHttpResource);
|
||||
@@ -498,30 +591,35 @@ export default function Page() {
|
||||
if (isNative) {
|
||||
if (nativeSelectedSite) {
|
||||
await api.put(
|
||||
`/org/${orgId}/resource/${id}/browser-gateway-target`,
|
||||
`/resource/${id}/target`,
|
||||
{
|
||||
siteId: nativeSelectedSite.siteId,
|
||||
type: "ssh",
|
||||
destination: "localhost",
|
||||
destinationPort: 22
|
||||
mode: "ssh",
|
||||
ip: "localhost",
|
||||
port: 22,
|
||||
hcEnabled: false
|
||||
}
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const sitesToCreate =
|
||||
standardDaemonLocation !== "site"
|
||||
? bgSelectedSites
|
||||
: bgSelectedSite
|
||||
? [bgSelectedSite]
|
||||
: [];
|
||||
const bgValues = bgTargetForm.getValues();
|
||||
const useMultiSite =
|
||||
standardDaemonLocation !== "site" ||
|
||||
pamMode === "passthrough";
|
||||
const sitesToCreate = useMultiSite
|
||||
? bgValues.selectedSites
|
||||
: bgValues.selectedSite
|
||||
? [bgValues.selectedSite]
|
||||
: [];
|
||||
for (const site of sitesToCreate) {
|
||||
await api.put(
|
||||
`/org/${orgId}/resource/${id}/browser-gateway-target`,
|
||||
`/resource/${id}/target`,
|
||||
{
|
||||
siteId: site.siteId,
|
||||
type: "ssh",
|
||||
destination: bgDestination,
|
||||
destinationPort: Number(bgDestinationPort)
|
||||
mode: "ssh",
|
||||
ip: bgValues.destination,
|
||||
port: Number(bgValues.destinationPort),
|
||||
hcEnabled: false
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -531,16 +629,18 @@ export default function Page() {
|
||||
`/${orgId}/settings/resources/public/${newNiceId}`
|
||||
);
|
||||
} else if (resourceType === "rdp" || resourceType === "vnc") {
|
||||
for (const site of bgSelectedSites) {
|
||||
const bgValues = bgTargetForm.getValues();
|
||||
for (const site of bgValues.selectedSites) {
|
||||
await api.put(
|
||||
`/org/${orgId}/resource/${id}/browser-gateway-target`,
|
||||
`/resource/${id}/target`,
|
||||
{
|
||||
siteId: site.siteId,
|
||||
type: resourceType,
|
||||
destination: bgDestination,
|
||||
destinationPort: Number(bgDestinationPort)
|
||||
mode: resourceType,
|
||||
ip: bgValues.destination,
|
||||
port: Number(bgValues.destinationPort),
|
||||
hcEnabled: false
|
||||
}
|
||||
);
|
||||
);
|
||||
}
|
||||
|
||||
router.push(
|
||||
@@ -760,32 +860,56 @@ export default function Page() {
|
||||
|
||||
{/* Domain/Subdomain (HTTP-based types) */}
|
||||
{isHttpResource && (
|
||||
<div className="space-y-2">
|
||||
<DomainPicker
|
||||
allowWildcard={true}
|
||||
orgId={orgId as string}
|
||||
warnOnProvidedDomain={
|
||||
remoteExitNodes.length >=
|
||||
1
|
||||
}
|
||||
onDomainChange={(res) => {
|
||||
if (!res) return;
|
||||
httpForm.setValue(
|
||||
"subdomain",
|
||||
res.subdomain
|
||||
);
|
||||
httpForm.setValue(
|
||||
"domainId",
|
||||
res.domainId
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t(
|
||||
"resourceDomainDescription"
|
||||
<Form {...httpForm}>
|
||||
<FormField
|
||||
control={httpForm.control}
|
||||
name="domainId"
|
||||
render={() => (
|
||||
<FormItem>
|
||||
<DomainPicker
|
||||
allowWildcard={
|
||||
true
|
||||
}
|
||||
orgId={
|
||||
orgId as string
|
||||
}
|
||||
warnOnProvidedDomain={
|
||||
remoteExitNodes.length >=
|
||||
1
|
||||
}
|
||||
onDomainChange={(
|
||||
res
|
||||
) => {
|
||||
if (!res)
|
||||
return;
|
||||
httpForm.setValue(
|
||||
"subdomain",
|
||||
res.subdomain,
|
||||
{
|
||||
shouldValidate:
|
||||
true
|
||||
}
|
||||
);
|
||||
httpForm.setValue(
|
||||
"domainId",
|
||||
res.domainId,
|
||||
{
|
||||
shouldValidate:
|
||||
true
|
||||
}
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<FormMessage />
|
||||
<FormDescription>
|
||||
{t(
|
||||
"resourceDomainDescription"
|
||||
)}
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
/>
|
||||
</Form>
|
||||
)}
|
||||
|
||||
{/* Proxy Port (TCP/UDP types) */}
|
||||
@@ -883,9 +1007,7 @@ export default function Page() {
|
||||
<SettingsSectionForm variant="half">
|
||||
{/* Mode */}
|
||||
<div className="space-y-2">
|
||||
<SettingsSubsectionTitle>
|
||||
{t("sshServerMode")}
|
||||
</SettingsSubsectionTitle>
|
||||
<p className="font-semibold text-sm">{t("sshServerMode")}</p>
|
||||
<StrategySelect<
|
||||
"standard" | "native"
|
||||
>
|
||||
@@ -897,11 +1019,7 @@ export default function Page() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<SettingsSubsectionTitle>
|
||||
{t(
|
||||
"sshAuthenticationMethod"
|
||||
)}
|
||||
</SettingsSubsectionTitle>
|
||||
<p className="font-semibold text-sm">{t("sshAuthenticationMethod")}</p>
|
||||
<StrategySelect<
|
||||
"passthrough" | "push"
|
||||
>
|
||||
@@ -917,11 +1035,7 @@ export default function Page() {
|
||||
{/* Daemon Location (standard + push) */}
|
||||
{showDaemonLocation && (
|
||||
<div className="space-y-2">
|
||||
<SettingsSubsectionTitle>
|
||||
{t(
|
||||
"sshAuthDaemonLocation"
|
||||
)}
|
||||
</SettingsSubsectionTitle>
|
||||
<p className="font-semibold text-sm">{t("sshAuthDaemonLocation")}</p>
|
||||
<StrategySelect<
|
||||
"site" | "remote"
|
||||
>
|
||||
@@ -1052,55 +1166,39 @@ export default function Page() {
|
||||
"site" ||
|
||||
pamMode ===
|
||||
"passthrough" ? (
|
||||
<BrowserGatewayTargetForm
|
||||
orgId={orgId as string}
|
||||
multiSite={true}
|
||||
selectedSites={
|
||||
bgSelectedSites
|
||||
}
|
||||
onSitesChange={
|
||||
setBgSelectedSites
|
||||
}
|
||||
destination={
|
||||
bgDestination
|
||||
}
|
||||
destinationPort={
|
||||
bgDestinationPort
|
||||
}
|
||||
onDestinationChange={
|
||||
setBgDestination
|
||||
}
|
||||
onDestinationPortChange={
|
||||
setBgDestinationPort
|
||||
}
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh"
|
||||
defaultPort={22}
|
||||
/>
|
||||
<Form {...bgTargetForm}>
|
||||
<BrowserGatewayTargetForm
|
||||
control={
|
||||
bgTargetForm.control
|
||||
}
|
||||
orgId={
|
||||
orgId as string
|
||||
}
|
||||
multiSite={true}
|
||||
sitesField="selectedSites"
|
||||
destinationField="destination"
|
||||
destinationPortField="destinationPort"
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh"
|
||||
defaultPort={22}
|
||||
/>
|
||||
</Form>
|
||||
) : (
|
||||
<BrowserGatewayTargetForm
|
||||
orgId={orgId as string}
|
||||
multiSite={false}
|
||||
selectedSite={
|
||||
bgSelectedSite
|
||||
}
|
||||
onSiteChange={
|
||||
setBgSelectedSite
|
||||
}
|
||||
destination={
|
||||
bgDestination
|
||||
}
|
||||
destinationPort={
|
||||
bgDestinationPort
|
||||
}
|
||||
onDestinationChange={
|
||||
setBgDestination
|
||||
}
|
||||
onDestinationPortChange={
|
||||
setBgDestinationPort
|
||||
}
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh"
|
||||
defaultPort={22}
|
||||
/>
|
||||
<Form {...bgTargetForm}>
|
||||
<BrowserGatewayTargetForm
|
||||
control={
|
||||
bgTargetForm.control
|
||||
}
|
||||
orgId={
|
||||
orgId as string
|
||||
}
|
||||
multiSite={false}
|
||||
siteField="selectedSite"
|
||||
destinationField="destination"
|
||||
destinationPortField="destinationPort"
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh"
|
||||
defaultPort={22}
|
||||
/>
|
||||
</Form>
|
||||
)}
|
||||
</div>
|
||||
</SettingsSectionForm>
|
||||
@@ -1138,26 +1236,18 @@ export default function Page() {
|
||||
>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm variant="half">
|
||||
<BrowserGatewayTargetForm
|
||||
orgId={orgId as string}
|
||||
multiSite={true}
|
||||
selectedSites={bgSelectedSites}
|
||||
onSitesChange={
|
||||
setBgSelectedSites
|
||||
}
|
||||
destination={bgDestination}
|
||||
destinationPort={
|
||||
bgDestinationPort
|
||||
}
|
||||
onDestinationChange={
|
||||
setBgDestination
|
||||
}
|
||||
onDestinationPortChange={
|
||||
setBgDestinationPort
|
||||
}
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/rdp"
|
||||
defaultPort={3389}
|
||||
/>
|
||||
<Form {...bgTargetForm}>
|
||||
<BrowserGatewayTargetForm
|
||||
control={bgTargetForm.control}
|
||||
orgId={orgId as string}
|
||||
multiSite={true}
|
||||
sitesField="selectedSites"
|
||||
destinationField="destination"
|
||||
destinationPortField="destinationPort"
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/rdp"
|
||||
defaultPort={3389}
|
||||
/>
|
||||
</Form>
|
||||
</SettingsSectionForm>
|
||||
</SettingsSectionBody>
|
||||
</fieldset>
|
||||
@@ -1193,26 +1283,18 @@ export default function Page() {
|
||||
>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm variant="half">
|
||||
<BrowserGatewayTargetForm
|
||||
orgId={orgId as string}
|
||||
multiSite={true}
|
||||
selectedSites={bgSelectedSites}
|
||||
onSitesChange={
|
||||
setBgSelectedSites
|
||||
}
|
||||
destination={bgDestination}
|
||||
destinationPort={
|
||||
bgDestinationPort
|
||||
}
|
||||
onDestinationChange={
|
||||
setBgDestination
|
||||
}
|
||||
onDestinationPortChange={
|
||||
setBgDestinationPort
|
||||
}
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/vnc"
|
||||
defaultPort={5900}
|
||||
/>
|
||||
<Form {...bgTargetForm}>
|
||||
<BrowserGatewayTargetForm
|
||||
control={bgTargetForm.control}
|
||||
orgId={orgId as string}
|
||||
multiSite={true}
|
||||
sitesField="selectedSites"
|
||||
destinationField="destination"
|
||||
destinationPortField="destinationPort"
|
||||
learnMoreHref="https://docs.pangolin.net/manage/resources/public/vnc"
|
||||
defaultPort={5900}
|
||||
/>
|
||||
</Form>
|
||||
</SettingsSectionForm>
|
||||
</SettingsSectionBody>
|
||||
</fieldset>
|
||||
@@ -1253,15 +1335,31 @@ export default function Page() {
|
||||
const tcpValid = !isHttpResource
|
||||
? await tcpUdpForm.trigger()
|
||||
: true;
|
||||
const sshPortValid = showDaemonPort
|
||||
? await sshDaemonPortForm.trigger()
|
||||
: true;
|
||||
|
||||
if (
|
||||
resourceType === "ssh" &&
|
||||
!isNative
|
||||
) {
|
||||
bgTargetForm.setValue(
|
||||
"authDaemonPort",
|
||||
sshDaemonPortForm.getValues()
|
||||
.authDaemonPort
|
||||
);
|
||||
}
|
||||
|
||||
const bgValid =
|
||||
resourceType === "rdp" ||
|
||||
resourceType === "vnc" ||
|
||||
(resourceType === "ssh" &&
|
||||
!isNative)
|
||||
? await bgTargetForm.trigger()
|
||||
: true;
|
||||
|
||||
if (
|
||||
baseValid &&
|
||||
domainValid &&
|
||||
tcpValid &&
|
||||
sshPortValid
|
||||
bgValid
|
||||
) {
|
||||
onSubmit();
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { ResourceRow } from "@app/components/ProxyResourcesTable";
|
||||
import ProxyResourcesTable from "@app/components/ProxyResourcesTable";
|
||||
import type { ResourceRow } from "@app/components/PublicResourcesTable";
|
||||
import PublicResourcesTable from "@app/components/PublicResourcesTable";
|
||||
import SettingsSectionTitle from "@app/components/SettingsSectionTitle";
|
||||
import ProxyResourcesBanner from "@app/components/ProxyResourcesBanner";
|
||||
import PublicResourcesBanner from "@app/components/PublicResourcesBanner";
|
||||
import { internal } from "@app/lib/api";
|
||||
import { authCookieHeader } from "@app/lib/api/cookies";
|
||||
import OrgProvider from "@app/providers/OrgProvider";
|
||||
@@ -146,10 +146,10 @@ export default async function ProxyResourcesPage(
|
||||
description={t("proxyResourceDescription")}
|
||||
/>
|
||||
|
||||
<ProxyResourcesBanner />
|
||||
<PublicResourcesBanner />
|
||||
|
||||
<OrgProvider org={org}>
|
||||
<ProxyResourcesTable
|
||||
<PublicResourcesTable
|
||||
resources={resourceRows}
|
||||
orgId={params.orgId}
|
||||
rowCount={pagination.total}
|
||||
|
||||
+2
-2
@@ -22,7 +22,7 @@
|
||||
--accent-foreground: oklch(0.21 0.006 285.885);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--destructive-foreground: oklch(0.985 0 0);
|
||||
--border: oklch(0.92 0.004 286.32);
|
||||
--border: oklch(0.88 0.004 286.32);
|
||||
--input: oklch(0.88 0.004 286.32);
|
||||
--ring: oklch(0.705 0.213 47.604);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
@@ -57,7 +57,7 @@
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.5382 0.1949 22.216);
|
||||
--destructive-foreground: oklch(0.985 0 0);
|
||||
--border: oklch(1 0 0 / 8%);
|
||||
--border: oklch(1 0 0 / 18%);
|
||||
--input: oklch(1 0 0 / 18%);
|
||||
--ring: oklch(0.646 0.222 41.116);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
|
||||
@@ -146,7 +146,7 @@ export const orgNavSections = (
|
||||
items: [
|
||||
{
|
||||
title: "sidebarResourcePolicies",
|
||||
href: "/{orgId}/settings/policies/resource",
|
||||
href: "/{orgId}/settings/policies/resources/public",
|
||||
icon: (
|
||||
<GlobeIcon className="size-4 flex-none" />
|
||||
)
|
||||
|
||||
+36
-22
@@ -35,7 +35,12 @@ import {
|
||||
import { Alert, AlertDescription } from "@app/components/ui/alert";
|
||||
import BrandedAuthSurface from "@app/components/BrandedAuthSurface";
|
||||
import PoweredByPangolin from "@app/components/PoweredByPangolin";
|
||||
import AuthPageFooterNotices from "@app/components/AuthPageFooterNotices";
|
||||
import { useTranslations } from "next-intl";
|
||||
import {
|
||||
loadEncryptedLocalStorage,
|
||||
saveEncryptedLocalStorage
|
||||
} from "@app/lib/secureLocalStorage";
|
||||
|
||||
declare module "react" {
|
||||
namespace JSX {
|
||||
@@ -62,22 +67,14 @@ type RdpCredentialsForm = {
|
||||
enableClipboard: boolean;
|
||||
};
|
||||
|
||||
function loadStoredCredentials(key: string): RdpCredentialsForm {
|
||||
try {
|
||||
const saved = localStorage.getItem(key);
|
||||
if (saved) return JSON.parse(saved) as RdpCredentialsForm;
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return {
|
||||
username: "",
|
||||
password: "",
|
||||
domain: "",
|
||||
kdcProxyUrl: "",
|
||||
pcb: "",
|
||||
enableClipboard: true
|
||||
};
|
||||
}
|
||||
const DEFAULT_RDP_CREDENTIALS: RdpCredentialsForm = {
|
||||
username: "",
|
||||
password: "",
|
||||
domain: "",
|
||||
kdcProxyUrl: "",
|
||||
pcb: "",
|
||||
enableClipboard: true
|
||||
};
|
||||
|
||||
const isIronError = (error: unknown): error is IronError => {
|
||||
return (
|
||||
@@ -112,9 +109,25 @@ export default function RdpClient({
|
||||
|
||||
const form = useForm<RdpCredentialsForm>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: loadStoredCredentials(STORAGE_KEY)
|
||||
defaultValues: DEFAULT_RDP_CREDENTIALS
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
void loadEncryptedLocalStorage<RdpCredentialsForm>(
|
||||
STORAGE_KEY,
|
||||
target?.authToken
|
||||
).then((saved) => {
|
||||
if (cancelled || !saved) return;
|
||||
form.reset({ ...DEFAULT_RDP_CREDENTIALS, ...saved });
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [form, target?.authToken]);
|
||||
|
||||
const [showLogin, setShowLogin] = useState(true);
|
||||
const [moduleReady, setModuleReady] = useState(false);
|
||||
const [connecting, setConnecting] = useState(false);
|
||||
@@ -292,11 +305,11 @@ export default function RdpClient({
|
||||
try {
|
||||
const sessionInfo = await userInteraction.connect(builder.build());
|
||||
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(values));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
void saveEncryptedLocalStorage(
|
||||
STORAGE_KEY,
|
||||
values,
|
||||
target.authToken
|
||||
);
|
||||
setConnecting(false);
|
||||
setShowLogin(false);
|
||||
userInteraction.setVisibility(true);
|
||||
@@ -443,6 +456,7 @@ export default function RdpClient({
|
||||
</Form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<AuthPageFooterNotices />
|
||||
</BrandedAuthSurface>
|
||||
)}
|
||||
|
||||
|
||||
+35
-20
@@ -31,6 +31,11 @@ import type { SignSshKeyResponse } from "@server/routers/ssh/types";
|
||||
import { useTranslations } from "next-intl";
|
||||
import BrandedAuthSurface from "@app/components/BrandedAuthSurface";
|
||||
import PoweredByPangolin from "@app/components/PoweredByPangolin";
|
||||
import AuthPageFooterNotices from "@app/components/AuthPageFooterNotices";
|
||||
import {
|
||||
loadEncryptedLocalStorage,
|
||||
saveEncryptedLocalStorage
|
||||
} from "@app/lib/secureLocalStorage";
|
||||
|
||||
type AuthTab = "password" | "privateKey";
|
||||
|
||||
@@ -47,15 +52,11 @@ type ConnectCredentials = {
|
||||
certificate?: string;
|
||||
};
|
||||
|
||||
function loadStoredCredentials(key: string): SshCredentialsForm {
|
||||
try {
|
||||
const saved = localStorage.getItem(key);
|
||||
if (saved) return JSON.parse(saved) as SshCredentialsForm;
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return { username: "", password: "", privateKey: "" };
|
||||
}
|
||||
const DEFAULT_SSH_CREDENTIALS: SshCredentialsForm = {
|
||||
username: "",
|
||||
password: "",
|
||||
privateKey: ""
|
||||
};
|
||||
|
||||
export default function SshClient({
|
||||
target,
|
||||
@@ -85,9 +86,25 @@ export default function SshClient({
|
||||
});
|
||||
|
||||
const form = useForm<SshCredentialsForm>({
|
||||
defaultValues: loadStoredCredentials(STORAGE_KEY)
|
||||
defaultValues: DEFAULT_SSH_CREDENTIALS
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
void loadEncryptedLocalStorage<SshCredentialsForm>(
|
||||
STORAGE_KEY,
|
||||
target?.authToken
|
||||
).then((saved) => {
|
||||
if (cancelled || !saved) return;
|
||||
form.reset({ ...DEFAULT_SSH_CREDENTIALS, ...saved });
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [form, target?.authToken]);
|
||||
|
||||
function handleKeyFile(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
@@ -251,14 +268,11 @@ export default function SshClient({
|
||||
})
|
||||
);
|
||||
if (!override) {
|
||||
try {
|
||||
localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify(form.getValues())
|
||||
);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
void saveEncryptedLocalStorage(
|
||||
STORAGE_KEY,
|
||||
form.getValues(),
|
||||
target.authToken
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -618,12 +632,13 @@ export default function SshClient({
|
||||
</Form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<AuthPageFooterNotices />
|
||||
</BrandedAuthSurface>
|
||||
)}
|
||||
|
||||
{connected && (
|
||||
<div className="fixed inset-0 z-50 flex flex-col bg-neutral-900">
|
||||
<div className="flex flex-wrap items-center gap-2 bg-black p-2 text-white">
|
||||
{/* <div className="flex flex-wrap items-center gap-2 bg-black p-2 text-white">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
@@ -631,7 +646,7 @@ export default function SshClient({
|
||||
>
|
||||
{t("sshTerminate")}
|
||||
</Button>
|
||||
</div>
|
||||
</div> */}
|
||||
<div
|
||||
ref={terminalRef}
|
||||
className="flex-1 overflow-hidden"
|
||||
|
||||
+31
-15
@@ -26,21 +26,20 @@ import {
|
||||
import { Alert, AlertDescription } from "@app/components/ui/alert";
|
||||
import BrandedAuthSurface from "@app/components/BrandedAuthSurface";
|
||||
import PoweredByPangolin from "@app/components/PoweredByPangolin";
|
||||
import AuthPageFooterNotices from "@app/components/AuthPageFooterNotices";
|
||||
import { useTranslations } from "next-intl";
|
||||
import {
|
||||
loadEncryptedLocalStorage,
|
||||
saveEncryptedLocalStorage
|
||||
} from "@app/lib/secureLocalStorage";
|
||||
|
||||
type VncCredentialsForm = {
|
||||
password: string;
|
||||
};
|
||||
|
||||
function loadStoredCredentials(key: string): VncCredentialsForm {
|
||||
try {
|
||||
const saved = localStorage.getItem(key);
|
||||
if (saved) return JSON.parse(saved) as VncCredentialsForm;
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return { password: "" };
|
||||
}
|
||||
const DEFAULT_VNC_CREDENTIALS: VncCredentialsForm = {
|
||||
password: ""
|
||||
};
|
||||
|
||||
export default function VncClient({
|
||||
target,
|
||||
@@ -61,9 +60,25 @@ export default function VncClient({
|
||||
|
||||
const form = useForm<VncCredentialsForm>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: loadStoredCredentials(STORAGE_KEY)
|
||||
defaultValues: DEFAULT_VNC_CREDENTIALS
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
void loadEncryptedLocalStorage<VncCredentialsForm>(
|
||||
STORAGE_KEY,
|
||||
target?.authToken
|
||||
).then((saved) => {
|
||||
if (cancelled || !saved) return;
|
||||
form.reset({ ...DEFAULT_VNC_CREDENTIALS, ...saved });
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [form, target?.authToken]);
|
||||
|
||||
const [connected, setConnected] = useState(false);
|
||||
const [connectError, setConnectError] = useState<string | null>(null);
|
||||
const rfbRef = useRef<any>(null);
|
||||
@@ -131,11 +146,11 @@ export default function VncClient({
|
||||
rfb.resizeSession = true;
|
||||
|
||||
rfb.addEventListener("connect", () => {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(values));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
void saveEncryptedLocalStorage(
|
||||
STORAGE_KEY,
|
||||
values,
|
||||
target.authToken
|
||||
);
|
||||
setConnected(true);
|
||||
});
|
||||
|
||||
@@ -242,6 +257,7 @@ export default function VncClient({
|
||||
</Form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<AuthPageFooterNotices />
|
||||
</BrandedAuthSurface>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"use client";
|
||||
|
||||
import { useSupporterStatusContext } from "@app/hooks/useSupporterStatusContext";
|
||||
import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { build } from "@server/build";
|
||||
|
||||
export default function AuthPageFooterNotices() {
|
||||
const t = useTranslations();
|
||||
const { supporterStatus } = useSupporterStatusContext();
|
||||
const { isUnlocked, licenseStatus } = useLicenseStatusContext();
|
||||
|
||||
return (
|
||||
<>
|
||||
{supporterStatus?.visible && (
|
||||
<div className="text-center mt-2">
|
||||
<span className="text-sm text-muted-foreground opacity-50">
|
||||
{t("noSupportKey")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{build === "enterprise" && !isUnlocked() ? (
|
||||
<div className="text-center mt-2">
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
{t("instanceIsUnlicensed")}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
{build === "enterprise" &&
|
||||
isUnlocked() &&
|
||||
licenseStatus?.tier === "personal" ? (
|
||||
<div className="text-center mt-2">
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
{t("loginPageLicenseWatermark")}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,128 +1,220 @@
|
||||
"use client";
|
||||
|
||||
import { cn } from "@app/lib/cn";
|
||||
import { ChevronsUpDown, ExternalLink } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
import type { Control, FieldValues, Path } from "react-hook-form";
|
||||
import { useWatch } from "react-hook-form";
|
||||
import {
|
||||
MultiSitesSelector,
|
||||
formatMultiSitesSelectorLabel
|
||||
} from "./multi-site-selector";
|
||||
import { SitesSelector, type Selectedsite } from "./site-selector";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage
|
||||
} from "./ui/form";
|
||||
import { Input } from "./ui/input";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
|
||||
|
||||
type SingleSiteProps = {
|
||||
multiSite?: false;
|
||||
selectedSite: Selectedsite | null;
|
||||
onSiteChange: (site: Selectedsite | null) => void;
|
||||
};
|
||||
|
||||
type MultiSiteProps = {
|
||||
multiSite: true;
|
||||
selectedSites: Selectedsite[];
|
||||
onSitesChange: (sites: Selectedsite[]) => void;
|
||||
};
|
||||
|
||||
export type BrowserGatewayTargetFormProps = {
|
||||
type BaseProps<T extends FieldValues> = {
|
||||
control: Control<T>;
|
||||
orgId: string;
|
||||
destination: string;
|
||||
defaultPort: number;
|
||||
destinationPort: string;
|
||||
onDestinationChange: (v: string) => void;
|
||||
onDestinationPortChange: (v: string) => void;
|
||||
destinationField: Path<T>;
|
||||
destinationPortField: Path<T>;
|
||||
learnMoreHref?: string;
|
||||
} & (SingleSiteProps | MultiSiteProps);
|
||||
defaultPort: number;
|
||||
};
|
||||
|
||||
export function BrowserGatewayTargetForm(props: BrowserGatewayTargetFormProps) {
|
||||
type MultiSiteFormProps<T extends FieldValues> = BaseProps<T> & {
|
||||
multiSite: true;
|
||||
sitesField: Path<T>;
|
||||
};
|
||||
|
||||
type SingleSiteFormProps<T extends FieldValues> = BaseProps<T> & {
|
||||
multiSite?: false;
|
||||
siteField: Path<T>;
|
||||
};
|
||||
|
||||
export type BrowserGatewayTargetFormProps<T extends FieldValues = FieldValues> =
|
||||
| MultiSiteFormProps<T>
|
||||
| SingleSiteFormProps<T>;
|
||||
|
||||
export function BrowserGatewayTargetForm<T extends FieldValues>(
|
||||
props: BrowserGatewayTargetFormProps<T>
|
||||
) {
|
||||
// IDK MAN REMOVING THIS SEEMS TO CAUSE ISSUES
|
||||
// Opt out of the React Compiler for this component.
|
||||
//
|
||||
// The parent (create page) shares a single `bgTargetForm` instance across
|
||||
// multiple conditionally-rendered Form sections (SSH passthrough/push, RDP,
|
||||
// VNC) and calls `bgTargetForm.reset(...)` in a useEffect when the
|
||||
// resource type changes. react-hook-form's Controller uses an external
|
||||
// subscription that the React Compiler cannot statically reason about, so
|
||||
// with `reactCompiler: true` (see next.config.ts) the Compiler can memoize
|
||||
// the render prop and skip re-rendering the <Input> elements when their
|
||||
// bound form values change. The visible symptom is that typing into the
|
||||
// destination/port inputs updates form state but the input itself never
|
||||
// visually updates. The escape hatch is the canonical fix here.
|
||||
"use no memo";
|
||||
const t = useTranslations();
|
||||
const [siteOpen, setSiteOpen] = useState(false);
|
||||
|
||||
const siteSelector =
|
||||
props.multiSite === true ? (
|
||||
<Popover open={siteOpen} onOpenChange={setSiteOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
className="w-full justify-between font-normal"
|
||||
>
|
||||
<span className="truncate">
|
||||
{formatMultiSitesSelectorLabel(
|
||||
props.selectedSites,
|
||||
t
|
||||
)}
|
||||
</span>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
|
||||
<MultiSitesSelector
|
||||
orgId={props.orgId}
|
||||
selectedSites={props.selectedSites}
|
||||
onSelectionChange={props.onSitesChange}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
) : (
|
||||
<Popover open={siteOpen} onOpenChange={setSiteOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
className="w-full justify-between font-normal"
|
||||
>
|
||||
<span className="truncate">
|
||||
{props.selectedSite?.name ?? t("siteSelect")}
|
||||
</span>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
|
||||
<SitesSelector
|
||||
orgId={props.orgId}
|
||||
selectedSite={props.selectedSite}
|
||||
onSelectSite={(site) => {
|
||||
props.onSiteChange(site);
|
||||
setSiteOpen(false);
|
||||
}}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
const sitesFieldName =
|
||||
props.multiSite === true ? props.sitesField : props.siteField;
|
||||
|
||||
// Subscribe to field values via useWatch and drive the controlled <Input>
|
||||
// elements from these values rather than from the `field.value` returned
|
||||
// by the Controller render prop. Combined with the "use no memo" directive
|
||||
// above, this makes the inputs reliably re-render when their bound form
|
||||
// values change.
|
||||
const watchedSites = useWatch({
|
||||
control: props.control,
|
||||
name: sitesFieldName
|
||||
});
|
||||
|
||||
const watchedDestination = useWatch({
|
||||
control: props.control,
|
||||
name: props.destinationField
|
||||
});
|
||||
|
||||
const watchedDestinationPort = useWatch({
|
||||
control: props.control,
|
||||
name: props.destinationPortField
|
||||
});
|
||||
|
||||
const showMultiSiteDisclaimer =
|
||||
props.multiSite === true &&
|
||||
((watchedSites as Selectedsite[] | undefined)?.length ?? 0) > 1;
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold">
|
||||
{t("sites")}
|
||||
</label>
|
||||
{siteSelector}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold">
|
||||
{t("destination")}
|
||||
</label>
|
||||
<Input
|
||||
value={props.destination}
|
||||
onChange={(e) =>
|
||||
props.onDestinationChange(e.target.value)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold">{t("port")}</label>
|
||||
<Input
|
||||
type="number"
|
||||
value={props.destinationPort}
|
||||
onChange={(e) =>
|
||||
props.onDestinationPortChange(e.target.value)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-4 items-start">
|
||||
<FormField
|
||||
control={props.control}
|
||||
name={sitesFieldName}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("sites")}</FormLabel>
|
||||
<Popover open={siteOpen} onOpenChange={setSiteOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<FormControl>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
className={cn(
|
||||
"w-full justify-between font-normal",
|
||||
"aria-invalid:border-destructive aria-invalid:ring-destructive/20",
|
||||
props.multiSite === true
|
||||
? (
|
||||
field.value as Selectedsite[]
|
||||
)?.length === 0 &&
|
||||
"text-muted-foreground"
|
||||
: !field.value &&
|
||||
"text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
<span className="truncate">
|
||||
{props.multiSite === true
|
||||
? formatMultiSitesSelectorLabel(
|
||||
(field.value as Selectedsite[]) ??
|
||||
[],
|
||||
t
|
||||
)
|
||||
: ((
|
||||
field.value as Selectedsite | null
|
||||
)?.name ??
|
||||
t("siteSelect"))}
|
||||
</span>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</FormControl>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
|
||||
{props.multiSite === true ? (
|
||||
<MultiSitesSelector
|
||||
orgId={props.orgId}
|
||||
selectedSites={
|
||||
(field.value as Selectedsite[]) ??
|
||||
[]
|
||||
}
|
||||
onSelectionChange={field.onChange}
|
||||
/>
|
||||
) : (
|
||||
<SitesSelector
|
||||
orgId={props.orgId}
|
||||
selectedSite={
|
||||
field.value as Selectedsite | null
|
||||
}
|
||||
onSelectSite={(site) => {
|
||||
field.onChange(site);
|
||||
setSiteOpen(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={props.control}
|
||||
name={props.destinationField}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("destination")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
onBlur={field.onBlur}
|
||||
onChange={field.onChange}
|
||||
value={
|
||||
(watchedDestination as
|
||||
| string
|
||||
| undefined) ?? ""
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={props.control}
|
||||
name={props.destinationPortField}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("port")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
onBlur={field.onBlur}
|
||||
onChange={field.onChange}
|
||||
value={
|
||||
(watchedDestinationPort as
|
||||
| string
|
||||
| number
|
||||
| undefined) ?? ""
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{props.multiSite === true && props.selectedSites.length > 1 && (
|
||||
{showMultiSiteDisclaimer && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("bgTargetMultiSiteDisclaimer")}{" "}
|
||||
<a
|
||||
|
||||
@@ -408,12 +408,7 @@ export function HealthCheckCredenza(props: HealthCheckCredenzaProps) {
|
||||
? t("standaloneHcEditTitle")
|
||||
: t("standaloneHcCreateTitle");
|
||||
|
||||
const description =
|
||||
mode === "autoSave"
|
||||
? t("configureHealthCheckDescription", {
|
||||
target: (props as any).targetAddress
|
||||
})
|
||||
: t("standaloneHcDescription");
|
||||
const description = t("configureHealthCheckDescription");
|
||||
|
||||
const disableTabInputs = mode === "autoSave" && !watchedEnabled;
|
||||
const isSnmpOrIcmp = watchedMode === "snmp" || watchedMode === "icmp";
|
||||
|
||||
@@ -1813,9 +1813,9 @@ export function PrivateResourceForm({
|
||||
|
||||
{/* Mode */}
|
||||
<div className="space-y-2">
|
||||
<SettingsSubsectionTitle>
|
||||
<p className="font-semibold text-sm">
|
||||
{t("sshServerMode")}
|
||||
</SettingsSubsectionTitle>
|
||||
</p>
|
||||
<StrategySelect<"standard" | "native">
|
||||
value={sshServerMode}
|
||||
options={[
|
||||
@@ -1870,9 +1870,9 @@ export function PrivateResourceForm({
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<SettingsSubsectionTitle>
|
||||
<p className="font-semibold text-sm">
|
||||
{t("sshAuthenticationMethod")}
|
||||
</SettingsSubsectionTitle>
|
||||
</p>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="pamMode"
|
||||
@@ -1965,9 +1965,9 @@ export function PrivateResourceForm({
|
||||
{/* Daemon Location (standard + push) */}
|
||||
{showDaemonLocation && (
|
||||
<div className="space-y-2">
|
||||
<SettingsSubsectionTitle>
|
||||
<p className="font-semibold text-sm">
|
||||
{t("sshAuthDaemonLocation")}
|
||||
</SettingsSubsectionTitle>
|
||||
</p>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="authDaemonMode"
|
||||
|
||||
@@ -363,7 +363,7 @@ export default function PrivateResourcesTable({
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const resourceRow = row.original;
|
||||
if (resourceRow.mode === "host" && resourceRow.alias) {
|
||||
if (resourceRow.alias) {
|
||||
return (
|
||||
<CopyToClipboard
|
||||
text={resourceRow.alias}
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { Globe } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import DismissableBanner from "./DismissableBanner";
|
||||
|
||||
export const ProxyResourcesBanner = () => {
|
||||
export const PublicResourcesBanner = () => {
|
||||
const t = useTranslations();
|
||||
|
||||
return (
|
||||
<DismissableBanner
|
||||
storageKey="proxy-resources-banner-dismissed"
|
||||
version={1}
|
||||
title={t("proxyResourcesBannerTitle")}
|
||||
title={t("publicResourcesBannerTitle")}
|
||||
titleIcon={<Globe className="w-5 h-5 text-primary" />}
|
||||
description={t("proxyResourcesBannerDescription")}
|
||||
description={t("publicResourcesBannerDescription")}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProxyResourcesBanner;
|
||||
export default PublicResourcesBanner;
|
||||
@@ -127,7 +127,7 @@ const booleanSearchFilterSchema = z
|
||||
.optional()
|
||||
.catch(undefined);
|
||||
|
||||
export default function ProxyResourcesTable({
|
||||
export default function PublicResourcesTable({
|
||||
resources,
|
||||
orgId,
|
||||
pagination,
|
||||
@@ -44,7 +44,7 @@ import { toast } from "@app/hooks/useToast";
|
||||
import BrandingLogo from "@app/components/BrandingLogo";
|
||||
import BrandedAuthSurface from "@app/components/BrandedAuthSurface";
|
||||
import PoweredByPangolin from "@app/components/PoweredByPangolin";
|
||||
import { useSupporterStatusContext } from "@app/hooks/useSupporterStatusContext";
|
||||
import AuthPageFooterNotices from "@app/components/AuthPageFooterNotices";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { build } from "@server/build";
|
||||
import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext";
|
||||
@@ -124,8 +124,6 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
|
||||
|
||||
const { env } = useEnvContext();
|
||||
|
||||
const { supporterStatus } = useSupporterStatusContext();
|
||||
|
||||
function getDefaultSelectedMethod() {
|
||||
if (props.methods.sso) {
|
||||
return "sso";
|
||||
@@ -727,29 +725,7 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
|
||||
</Tabs>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{supporterStatus?.visible && (
|
||||
<div className="text-center mt-2">
|
||||
<span className="text-sm text-muted-foreground opacity-50">
|
||||
{t("noSupportKey")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{build === "enterprise" && !isUnlocked() ? (
|
||||
<div className="text-center mt-2">
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
{t("instanceIsUnlicensed")}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
{build === "enterprise" &&
|
||||
isUnlocked() &&
|
||||
licenseStatus?.tier === "personal" ? (
|
||||
<div className="text-center mt-2">
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
{t("loginPageLicenseWatermark")}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
<AuthPageFooterNotices />
|
||||
</div>
|
||||
) : (
|
||||
<ResourceAccessDenied />
|
||||
|
||||
@@ -90,7 +90,7 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
|
||||
</InfoSectionTitle>
|
||||
<InfoSectionContent>
|
||||
<span className="inline-flex items-center">
|
||||
{resource.mode!.toUpperCase()}
|
||||
{resource.ssl ? "HTTPS" : "HTTP"}
|
||||
</span>
|
||||
</InfoSectionContent>
|
||||
</InfoSection>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { Shield } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import DismissableBanner from "./DismissableBanner";
|
||||
|
||||
export const ResourcePoliciesBanner = () => {
|
||||
const t = useTranslations();
|
||||
|
||||
return (
|
||||
<DismissableBanner
|
||||
storageKey="resource-policies-banner-dismissed"
|
||||
version={1}
|
||||
title={t("resourcePoliciesBannerTitle")}
|
||||
titleIcon={<Shield className="w-5 h-5 text-primary" />}
|
||||
description={t("resourcePoliciesBannerDescription")}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default ResourcePoliciesBanner;
|
||||
@@ -8,12 +8,7 @@ import type {
|
||||
ListResourcePoliciesResponse
|
||||
} from "@server/routers/resource/types";
|
||||
import type { PaginationState } from "@tanstack/react-table";
|
||||
import {
|
||||
ArrowRight,
|
||||
ChevronDown,
|
||||
MoreHorizontal,
|
||||
Waypoints
|
||||
} from "lucide-react";
|
||||
import { ArrowRight, ChevronDown, MoreHorizontal } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
@@ -98,55 +93,50 @@ export function ResourcePoliciesTable({
|
||||
};
|
||||
|
||||
function ResourceListCell({
|
||||
orgId,
|
||||
resources
|
||||
}: {
|
||||
orgId: string;
|
||||
resources?: AttachedResource[];
|
||||
}) {
|
||||
if (!resources || resources.length === 0) {
|
||||
return (
|
||||
<div
|
||||
id="LOOK_FOR_ME"
|
||||
className="flex items-center gap-2 text-muted-foreground"
|
||||
>
|
||||
<Waypoints className="size-4 flex-none" />
|
||||
<span className="text-sm">
|
||||
{t("resourcePoliciesAttachedResourcesEmpty")}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
return <span>-</span>;
|
||||
}
|
||||
|
||||
const countLabel = t("resourcePoliciesAttachedResourcesCount", {
|
||||
count: resources.length
|
||||
});
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="flex items-center gap-2 h-8 px-0 font-normal"
|
||||
className="flex h-8 items-center gap-2 px-0 font-normal"
|
||||
>
|
||||
<Waypoints className="size-4 flex-none" />
|
||||
<span className="text-sm">
|
||||
{t("resourcePoliciesAttachedResources", {
|
||||
count: resources.length
|
||||
})}
|
||||
<span className="text-sm tabular-nums">
|
||||
{countLabel}
|
||||
</span>
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
<ChevronDown className="h-3 w-3 shrink-0" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="min-w-70">
|
||||
<DropdownMenuContent align="start" className="min-w-56">
|
||||
{resources.map((resource) => (
|
||||
<DropdownMenuItem
|
||||
key={resource.resourceId}
|
||||
className="flex items-center justify-between gap-4"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{resource.name}
|
||||
</div>
|
||||
<span
|
||||
className={`capitalize text-muted-foreground`}
|
||||
<DropdownMenuItem key={resource.resourceId} asChild>
|
||||
<Link
|
||||
href={`/${orgId}/settings/resources/public/${resource.niceId}`}
|
||||
className="flex cursor-pointer items-center justify-between gap-4"
|
||||
>
|
||||
{resource.fullDomain}
|
||||
</span>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className="truncate">
|
||||
{resource.name}
|
||||
</span>
|
||||
</div>
|
||||
<span className="shrink-0 text-muted-foreground">
|
||||
{resource.fullDomain}
|
||||
</span>
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
@@ -182,7 +172,12 @@ export function ResourcePoliciesTable({
|
||||
</span>
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
return <ResourceListCell resources={row.original.resources} />;
|
||||
return (
|
||||
<ResourceListCell
|
||||
orgId={row.original.orgId}
|
||||
resources={row.original.resources}
|
||||
/>
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -205,7 +200,7 @@ export function ResourcePoliciesTable({
|
||||
<DropdownMenuContent align="end">
|
||||
<Link
|
||||
className="block w-full"
|
||||
href={`/${policyRow.orgId}/settings/policies/resource/${policyRow.niceId}`}
|
||||
href={`/${policyRow.orgId}/settings/policies/resources/public/${policyRow.niceId}`}
|
||||
>
|
||||
<DropdownMenuItem>
|
||||
{t("viewSettings")}
|
||||
@@ -224,7 +219,7 @@ export function ResourcePoliciesTable({
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Link
|
||||
href={`/${policyRow.orgId}/settings/policies/resource/${policyRow.niceId}`}
|
||||
href={`/${policyRow.orgId}/settings/policies/resources/public/${policyRow.niceId}`}
|
||||
>
|
||||
<Button variant={"outline"}>
|
||||
{t("edit")}
|
||||
@@ -288,12 +283,13 @@ export function ResourcePoliciesTable({
|
||||
searchPlaceholder={t("resourcePoliciesSearch")}
|
||||
pagination={pagination}
|
||||
rowCount={rowCount}
|
||||
searchQuery={searchParams.get("query")?.toString()}
|
||||
onSearch={handleSearchChange}
|
||||
onPaginationChange={handlePaginationChange}
|
||||
onAdd={() =>
|
||||
startNavigation(() =>
|
||||
router.push(
|
||||
`/${orgId}/settings/policies/resource/create`
|
||||
`/${orgId}/settings/policies/resources/public/create`
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ export function SettingsSubsectionHeader({
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}) {
|
||||
return <div className={cn("space-y-0.5", className)}>{children}</div>;
|
||||
return <div className={cn("py-3 space-y-0.5", className)}>{children}</div>;
|
||||
}
|
||||
|
||||
export function SettingsSubsectionTitle({
|
||||
@@ -80,9 +80,7 @@ export function SettingsSubsectionTitle({
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<h3 className={cn("text-sm font-semibold", className)}>{children}</h3>
|
||||
);
|
||||
return <h3 className={cn("font-semibold", className)}>{children}</h3>;
|
||||
}
|
||||
|
||||
export function SettingsSubsectionDescription({
|
||||
|
||||
@@ -514,6 +514,16 @@ export default function SitesTable({
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
</Link>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setSelectedSite(siteRow);
|
||||
setIsDeleteModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<span className="text-red-500">
|
||||
{t("delete")}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Link
|
||||
|
||||
@@ -157,7 +157,7 @@ export function LabelsSelector({
|
||||
/>
|
||||
|
||||
<Select defaultValue={randomColor} name="color">
|
||||
<SelectTrigger className="w-18 [&_[data-name]]:hidden [&_[svg]]:hidden!">
|
||||
<SelectTrigger className="w-auto min-w-24">
|
||||
<SelectValue
|
||||
placeholder={t("selectColor")}
|
||||
/>
|
||||
|
||||
@@ -1,530 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
SettingsSection,
|
||||
SettingsSectionBody,
|
||||
SettingsSectionDescription,
|
||||
SettingsSectionForm,
|
||||
SettingsSectionHeader,
|
||||
SettingsSectionTitle
|
||||
} from "@app/components/Settings";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
import z from "zod";
|
||||
|
||||
import { createPolicySchema, type PolicyFormValues } from ".";
|
||||
|
||||
import { SwitchInput } from "@app/components/SwitchInput";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import {
|
||||
Credenza,
|
||||
CredenzaBody,
|
||||
CredenzaClose,
|
||||
CredenzaContent,
|
||||
CredenzaDescription,
|
||||
CredenzaFooter,
|
||||
CredenzaHeader,
|
||||
CredenzaTitle
|
||||
} from "@app/components/Credenza";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage
|
||||
} from "@app/components/ui/form";
|
||||
import { Input } from "@app/components/ui/input";
|
||||
import {
|
||||
InputOTP,
|
||||
InputOTPGroup,
|
||||
InputOTPSlot
|
||||
} from "@app/components/ui/input-otp";
|
||||
|
||||
import { cn } from "@app/lib/cn";
|
||||
import { Binary, Bot, Key, Plus } from "lucide-react";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { type UseFormReturn, useForm, useWatch } from "react-hook-form";
|
||||
|
||||
// ─── CreatePolicyAuthMethodsSectionForm ───────────────────────────────────────
|
||||
|
||||
const setPasswordSchema = z.object({
|
||||
password: z.string().min(4).max(100)
|
||||
});
|
||||
|
||||
const setPincodeSchema = z.object({
|
||||
pincode: z.string().length(6)
|
||||
});
|
||||
|
||||
const setHeaderAuthSchema = z.object({
|
||||
user: z.string().min(4).max(100),
|
||||
password: z.string().min(4).max(100),
|
||||
extendedCompatibility: z.boolean()
|
||||
});
|
||||
|
||||
export type CreatePolicyAuthMethodsSectionFormProps = {
|
||||
form: UseFormReturn<PolicyFormValues, any, any>;
|
||||
};
|
||||
|
||||
export function CreatePolicyAuthMethodsSectionForm({
|
||||
form: parentForm
|
||||
}: CreatePolicyAuthMethodsSectionFormProps) {
|
||||
const t = useTranslations();
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
const [isSetPasswordOpen, setIsSetPasswordOpen] = useState(false);
|
||||
const [isSetPincodeOpen, setIsSetPincodeOpen] = useState(false);
|
||||
const [isSetHeaderAuthOpen, setIsSetHeaderAuthOpen] = useState(false);
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(
|
||||
createPolicySchema.pick({
|
||||
password: true,
|
||||
pincode: true,
|
||||
headerAuth: true
|
||||
})
|
||||
),
|
||||
defaultValues: {
|
||||
password: null,
|
||||
pincode: null,
|
||||
headerAuth: null
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const subscription = form.watch((values) => {
|
||||
parentForm.setValue("password", values.password as any);
|
||||
parentForm.setValue("pincode", values.pincode as any);
|
||||
parentForm.setValue("headerAuth", values.headerAuth as any);
|
||||
});
|
||||
return () => subscription.unsubscribe();
|
||||
}, [form, parentForm]);
|
||||
|
||||
const password = useWatch({
|
||||
control: form.control,
|
||||
name: "password"
|
||||
});
|
||||
const pincode = useWatch({
|
||||
control: form.control,
|
||||
name: "pincode"
|
||||
});
|
||||
const headerAuth = useWatch({
|
||||
control: form.control,
|
||||
name: "headerAuth"
|
||||
});
|
||||
|
||||
const passwordForm = useForm({
|
||||
resolver: zodResolver(setPasswordSchema),
|
||||
defaultValues: { password: "" }
|
||||
});
|
||||
|
||||
const pincodeForm = useForm({
|
||||
resolver: zodResolver(setPincodeSchema),
|
||||
defaultValues: { pincode: "" }
|
||||
});
|
||||
|
||||
const headerAuthForm = useForm({
|
||||
resolver: zodResolver(setHeaderAuthSchema),
|
||||
defaultValues: { user: "", password: "", extendedCompatibility: true }
|
||||
});
|
||||
|
||||
if (!isExpanded) {
|
||||
return (
|
||||
<SettingsSection>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>
|
||||
{t("resourceAuthMethods")}
|
||||
</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
{t("resourcePolicyAuthMethodsDescription")}
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setIsExpanded(true)}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
{t("resourcePolicyAuthMethodAdd")}
|
||||
</Button>
|
||||
</SettingsSectionBody>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Password Credenza */}
|
||||
<Credenza
|
||||
open={isSetPasswordOpen}
|
||||
onOpenChange={(val) => {
|
||||
setIsSetPasswordOpen(val);
|
||||
if (!val) passwordForm.reset();
|
||||
}}
|
||||
>
|
||||
<CredenzaContent>
|
||||
<CredenzaHeader>
|
||||
<CredenzaTitle>
|
||||
{t("resourcePasswordSetupTitle")}
|
||||
</CredenzaTitle>
|
||||
<CredenzaDescription>
|
||||
{t("resourcePasswordSetupTitleDescription")}
|
||||
</CredenzaDescription>
|
||||
</CredenzaHeader>
|
||||
<CredenzaBody>
|
||||
<Form {...passwordForm}>
|
||||
<form
|
||||
onSubmit={passwordForm.handleSubmit((data) => {
|
||||
form.setValue("password", data);
|
||||
setIsSetPasswordOpen(false);
|
||||
passwordForm.reset();
|
||||
})}
|
||||
className="space-y-4"
|
||||
id="set-password-form"
|
||||
>
|
||||
<FormField
|
||||
control={passwordForm.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("password")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
type="password"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</CredenzaBody>
|
||||
<CredenzaFooter>
|
||||
<CredenzaClose asChild>
|
||||
<Button variant="outline">{t("close")}</Button>
|
||||
</CredenzaClose>
|
||||
<Button type="submit" form="set-password-form">
|
||||
{t("resourcePasswordSubmit")}
|
||||
</Button>
|
||||
</CredenzaFooter>
|
||||
</CredenzaContent>
|
||||
</Credenza>
|
||||
|
||||
{/* Pincode Credenza */}
|
||||
<Credenza
|
||||
open={isSetPincodeOpen}
|
||||
onOpenChange={(val) => {
|
||||
setIsSetPincodeOpen(val);
|
||||
if (!val) pincodeForm.reset();
|
||||
}}
|
||||
>
|
||||
<CredenzaContent>
|
||||
<CredenzaHeader>
|
||||
<CredenzaTitle>
|
||||
{t("resourcePincodeSetupTitle")}
|
||||
</CredenzaTitle>
|
||||
<CredenzaDescription>
|
||||
{t("resourcePincodeSetupTitleDescription")}
|
||||
</CredenzaDescription>
|
||||
</CredenzaHeader>
|
||||
<CredenzaBody>
|
||||
<Form {...pincodeForm}>
|
||||
<form
|
||||
onSubmit={pincodeForm.handleSubmit((data) => {
|
||||
form.setValue("pincode", data);
|
||||
setIsSetPincodeOpen(false);
|
||||
pincodeForm.reset();
|
||||
})}
|
||||
className="space-y-4"
|
||||
id="set-pincode-form"
|
||||
>
|
||||
<FormField
|
||||
control={pincodeForm.control}
|
||||
name="pincode"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("resourcePincode")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<div className="flex justify-center">
|
||||
<InputOTP
|
||||
autoComplete="false"
|
||||
maxLength={6}
|
||||
{...field}
|
||||
>
|
||||
<InputOTPGroup className="flex">
|
||||
<InputOTPSlot
|
||||
index={0}
|
||||
obscured
|
||||
/>
|
||||
<InputOTPSlot
|
||||
index={1}
|
||||
obscured
|
||||
/>
|
||||
<InputOTPSlot
|
||||
index={2}
|
||||
obscured
|
||||
/>
|
||||
<InputOTPSlot
|
||||
index={3}
|
||||
obscured
|
||||
/>
|
||||
<InputOTPSlot
|
||||
index={4}
|
||||
obscured
|
||||
/>
|
||||
<InputOTPSlot
|
||||
index={5}
|
||||
obscured
|
||||
/>
|
||||
</InputOTPGroup>
|
||||
</InputOTP>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</CredenzaBody>
|
||||
<CredenzaFooter>
|
||||
<CredenzaClose asChild>
|
||||
<Button variant="outline">{t("close")}</Button>
|
||||
</CredenzaClose>
|
||||
<Button type="submit" form="set-pincode-form">
|
||||
{t("resourcePincodeSubmit")}
|
||||
</Button>
|
||||
</CredenzaFooter>
|
||||
</CredenzaContent>
|
||||
</Credenza>
|
||||
|
||||
{/* Header Auth Credenza */}
|
||||
<Credenza
|
||||
open={isSetHeaderAuthOpen}
|
||||
onOpenChange={(val) => {
|
||||
setIsSetHeaderAuthOpen(val);
|
||||
if (!val) headerAuthForm.reset();
|
||||
}}
|
||||
>
|
||||
<CredenzaContent>
|
||||
<CredenzaHeader>
|
||||
<CredenzaTitle>
|
||||
{t("resourceHeaderAuthSetupTitle")}
|
||||
</CredenzaTitle>
|
||||
<CredenzaDescription>
|
||||
{t("resourceHeaderAuthSetupTitleDescription")}
|
||||
</CredenzaDescription>
|
||||
</CredenzaHeader>
|
||||
<CredenzaBody>
|
||||
<Form {...headerAuthForm}>
|
||||
<form
|
||||
onSubmit={headerAuthForm.handleSubmit(
|
||||
(data) => {
|
||||
form.setValue("headerAuth", data);
|
||||
setIsSetHeaderAuthOpen(false);
|
||||
headerAuthForm.reset();
|
||||
}
|
||||
)}
|
||||
className="space-y-4"
|
||||
id="set-header-auth-form"
|
||||
>
|
||||
<FormField
|
||||
control={headerAuthForm.control}
|
||||
name="user"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("user")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
type="text"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={headerAuthForm.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("password")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
type="password"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={headerAuthForm.control}
|
||||
name="extendedCompatibility"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<SwitchInput
|
||||
id="header-auth-compatibility-toggle"
|
||||
label={t(
|
||||
"headerAuthCompatibility"
|
||||
)}
|
||||
description={t(
|
||||
"headerAuthCompatibilityInfo"
|
||||
)}
|
||||
checked={field.value}
|
||||
onCheckedChange={
|
||||
field.onChange
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</CredenzaBody>
|
||||
<CredenzaFooter>
|
||||
<CredenzaClose asChild>
|
||||
<Button variant="outline">{t("close")}</Button>
|
||||
</CredenzaClose>
|
||||
<Button type="submit" form="set-header-auth-form">
|
||||
{t("resourceHeaderAuthSubmit")}
|
||||
</Button>
|
||||
</CredenzaFooter>
|
||||
</CredenzaContent>
|
||||
</Credenza>
|
||||
|
||||
<SettingsSection>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>
|
||||
{t("resourceAuthMethods")}
|
||||
</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
{t("resourcePolicyAuthMethodsDescription")}
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm>
|
||||
{/* Password row */}
|
||||
<div className="flex items-center justify-between border rounded-md p-2 mb-4">
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center text-sm space-x-2",
|
||||
password && "text-green-500"
|
||||
)}
|
||||
>
|
||||
<Key size="14" />
|
||||
<span>
|
||||
{t("resourcePasswordProtection", {
|
||||
status: password
|
||||
? t("enabled")
|
||||
: t("disabled")
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={
|
||||
password
|
||||
? () => form.setValue("password", null)
|
||||
: () => setIsSetPasswordOpen(true)
|
||||
}
|
||||
>
|
||||
{password
|
||||
? t("passwordRemove")
|
||||
: t("passwordAdd")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Pincode row */}
|
||||
<div className="flex items-center justify-between border rounded-md p-2">
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center space-x-2 text-sm",
|
||||
pincode && "text-green-500"
|
||||
)}
|
||||
>
|
||||
<Binary size="14" />
|
||||
<span>
|
||||
{t("resourcePincodeProtection", {
|
||||
status: pincode
|
||||
? t("enabled")
|
||||
: t("disabled")
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={
|
||||
pincode
|
||||
? () => form.setValue("pincode", null)
|
||||
: () => setIsSetPincodeOpen(true)
|
||||
}
|
||||
>
|
||||
{pincode ? t("pincodeRemove") : t("pincodeAdd")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Header auth row */}
|
||||
<div className="flex items-center justify-between border rounded-md p-2">
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center space-x-2 text-sm",
|
||||
headerAuth && "text-green-500"
|
||||
)}
|
||||
>
|
||||
<Bot size="14" />
|
||||
<span>
|
||||
{headerAuth
|
||||
? t(
|
||||
"resourceHeaderAuthProtectionEnabled"
|
||||
)
|
||||
: t(
|
||||
"resourceHeaderAuthProtectionDisabled"
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={
|
||||
headerAuth
|
||||
? () =>
|
||||
form.setValue("headerAuth", null)
|
||||
: () => setIsSetHeaderAuthOpen(true)
|
||||
}
|
||||
>
|
||||
{headerAuth
|
||||
? t("headerAuthRemove")
|
||||
: t("headerAuthAdd")}
|
||||
</Button>
|
||||
</div>
|
||||
</SettingsSectionForm>
|
||||
</SettingsSectionBody>
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -19,7 +19,11 @@ import { build } from "@server/build";
|
||||
import { UserType } from "@server/types/UserTypes";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { type PolicyFormValues, createPolicySchema } from ".";
|
||||
import {
|
||||
type PolicyFormValues,
|
||||
createPolicySchema,
|
||||
createPolicySchemaWithI18n
|
||||
} from ".";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { createApiClient, formatAxiosError } from "@app/lib/api";
|
||||
import { orgs, type ResourcePolicy } from "@server/db";
|
||||
@@ -37,10 +41,8 @@ import {
|
||||
import { Input } from "@app/components/ui/input";
|
||||
import { useMemo, useTransition } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { CreatePolicyUsersRolesSectionForm } from "./CreatePolicyUserRolesSectionForm";
|
||||
import { CreatePolicyAuthMethodsSectionForm } from "./CreatePolicyAuthMethodsSectionForm";
|
||||
import { CreatePolicyOtpEmailSectionForm } from "./CreatePolicyOtpEmailSectionForm";
|
||||
import { CreatePolicyRulesSectionForm } from "./CreatePolicyRulesSectionForm";
|
||||
import { PolicyAuthStackSection } from "./PolicyAuthStackSection";
|
||||
import { PolicyAccessRulesSection } from "./PolicyAccessRulesSection";
|
||||
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
|
||||
import { tierMatrix, TierFeature } from "@server/lib/billing/tierMatrix";
|
||||
|
||||
@@ -78,8 +80,13 @@ export function CreatePolicyForm({}: CreatePolicyFormProps) {
|
||||
})
|
||||
);
|
||||
|
||||
const policySchema = useMemo(
|
||||
() => createPolicySchemaWithI18n(t, createPolicySchema),
|
||||
[t]
|
||||
);
|
||||
|
||||
const form = useForm<PolicyFormValues>({
|
||||
resolver: zodResolver(createPolicySchema) as any,
|
||||
resolver: zodResolver(policySchema) as any,
|
||||
defaultValues: {
|
||||
name: "",
|
||||
sso: true,
|
||||
@@ -140,7 +147,7 @@ export function CreatePolicyForm({}: CreatePolicyFormProps) {
|
||||
if (res && res.status === 201) {
|
||||
const niceId = res.data.data.niceId;
|
||||
router.push(
|
||||
`/${org.org.orgId}/settings/policies/resource/${niceId}`
|
||||
`/${org.org.orgId}/settings/policies/resources/public/${niceId}/general`
|
||||
);
|
||||
toast({
|
||||
title: t("success"),
|
||||
@@ -220,7 +227,7 @@ export function CreatePolicyForm({}: CreatePolicyFormProps) {
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm>
|
||||
<SettingsSectionForm variant="half">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
@@ -230,12 +237,7 @@ export function CreatePolicyForm({}: CreatePolicyFormProps) {
|
||||
{t("name")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
placeholder={t(
|
||||
"resourcePolicyNamePlaceholder"
|
||||
)}
|
||||
/>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -245,18 +247,17 @@ export function CreatePolicyForm({}: CreatePolicyFormProps) {
|
||||
</SettingsSectionBody>
|
||||
</SettingsSection>
|
||||
|
||||
<CreatePolicyUsersRolesSectionForm
|
||||
<PolicyAuthStackSection
|
||||
mode="create"
|
||||
form={form}
|
||||
orgId={org.org.orgId}
|
||||
allIdps={allIdps}
|
||||
allRoles={allRoles}
|
||||
allUsers={allUsers}
|
||||
allIdps={allIdps}
|
||||
/>
|
||||
<CreatePolicyAuthMethodsSectionForm form={form} />
|
||||
<CreatePolicyOtpEmailSectionForm
|
||||
form={form}
|
||||
emailEnabled={env.email.emailEnabled}
|
||||
/>
|
||||
<CreatePolicyRulesSectionForm
|
||||
<PolicyAccessRulesSection
|
||||
mode="create"
|
||||
form={form}
|
||||
isMaxmindAvailable={isMaxmindAvailable}
|
||||
isMaxmindAsnAvailable={isMaxmindAsnAvailable}
|
||||
|
||||
@@ -1,213 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
SettingsSection,
|
||||
SettingsSectionBody,
|
||||
SettingsSectionDescription,
|
||||
SettingsSectionForm,
|
||||
SettingsSectionHeader,
|
||||
SettingsSectionTitle
|
||||
} from "@app/components/Settings";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
import z from "zod";
|
||||
|
||||
import { createPolicySchema, type PolicyFormValues } from ".";
|
||||
|
||||
import { SwitchInput } from "@app/components/SwitchInput";
|
||||
import { Tag, TagInput } from "@app/components/tags/tag-input";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@app/components/ui/alert";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel
|
||||
} from "@app/components/ui/form";
|
||||
import { InfoPopup } from "@app/components/ui/info-popup";
|
||||
|
||||
import { InfoIcon, Plus } from "lucide-react";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { type UseFormReturn, useForm, useWatch } from "react-hook-form";
|
||||
|
||||
// ─── CreatePolicyOtpEmailSectionForm ──────────────────────────────────────────
|
||||
|
||||
export type CreatePolicyOtpEmailSectionFormProps = {
|
||||
form: UseFormReturn<PolicyFormValues, any, any>;
|
||||
emailEnabled: boolean;
|
||||
};
|
||||
|
||||
export function CreatePolicyOtpEmailSectionForm({
|
||||
form: parentForm,
|
||||
emailEnabled
|
||||
}: CreatePolicyOtpEmailSectionFormProps) {
|
||||
const t = useTranslations();
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
const [activeEmailTagIndex, setActiveEmailTagIndex] = useState<
|
||||
number | null
|
||||
>(null);
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(
|
||||
createPolicySchema.pick({
|
||||
emailWhitelistEnabled: true,
|
||||
emails: true
|
||||
})
|
||||
),
|
||||
defaultValues: {
|
||||
emailWhitelistEnabled: false,
|
||||
emails: []
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const subscription = form.watch((values) => {
|
||||
parentForm.setValue(
|
||||
"emailWhitelistEnabled",
|
||||
values.emailWhitelistEnabled as boolean
|
||||
);
|
||||
parentForm.setValue("emails", values.emails as [Tag, ...Tag[]]);
|
||||
});
|
||||
return () => subscription.unsubscribe();
|
||||
}, [form, parentForm]);
|
||||
|
||||
const whitelistEnabled = useWatch({
|
||||
control: form.control,
|
||||
name: "emailWhitelistEnabled"
|
||||
});
|
||||
|
||||
if (!isExpanded) {
|
||||
return (
|
||||
<SettingsSection>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>
|
||||
{t("otpEmailTitle")}
|
||||
</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
{t("otpEmailTitleDescription")}
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setIsExpanded(true)}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
{t("resourcePolicyOtpEmailAdd")}
|
||||
</Button>
|
||||
</SettingsSectionBody>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<SettingsSection>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>
|
||||
{t("otpEmailTitle")}
|
||||
</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
{t("otpEmailTitleDescription")}
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm>
|
||||
{!emailEnabled && (
|
||||
<Alert variant="neutral" className="mb-4">
|
||||
<InfoIcon className="h-4 w-4" />
|
||||
<AlertTitle className="font-semibold">
|
||||
{t("otpEmailSmtpRequired")}
|
||||
</AlertTitle>
|
||||
<AlertDescription>
|
||||
{t("otpEmailSmtpRequiredDescription")}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<SwitchInput
|
||||
id="whitelist-toggle"
|
||||
label={t("otpEmailWhitelist")}
|
||||
defaultChecked={false}
|
||||
onCheckedChange={(val) => {
|
||||
form.setValue("emailWhitelistEnabled", val);
|
||||
}}
|
||||
disabled={!emailEnabled}
|
||||
/>
|
||||
|
||||
{whitelistEnabled && emailEnabled && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="emails"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
<InfoPopup
|
||||
text={t("otpEmailWhitelistList")}
|
||||
info={t(
|
||||
"otpEmailWhitelistListDescription"
|
||||
)}
|
||||
/>
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
{/* @ts-ignore */}
|
||||
<TagInput
|
||||
{...field}
|
||||
activeTagIndex={
|
||||
activeEmailTagIndex
|
||||
}
|
||||
size="sm"
|
||||
validateTag={(tag) => {
|
||||
return z
|
||||
.email()
|
||||
.or(
|
||||
z
|
||||
.string()
|
||||
.regex(
|
||||
/^\*@[\w.-]+\.[a-zA-Z]{2,}$/,
|
||||
{
|
||||
message:
|
||||
t(
|
||||
"otpEmailErrorInvalid"
|
||||
)
|
||||
}
|
||||
)
|
||||
)
|
||||
.safeParse(tag).success;
|
||||
}}
|
||||
setActiveTagIndex={
|
||||
setActiveEmailTagIndex
|
||||
}
|
||||
placeholder={t("otpEmailEnter")}
|
||||
tags={form.getValues().emails}
|
||||
setTags={(newEmails) => {
|
||||
form.setValue(
|
||||
"emails",
|
||||
newEmails as [
|
||||
Tag,
|
||||
...Tag[]
|
||||
]
|
||||
);
|
||||
}}
|
||||
allowDuplicates={false}
|
||||
sortTags={true}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t("otpEmailEnterDescription")}
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</SettingsSectionForm>
|
||||
</SettingsSectionBody>
|
||||
</SettingsSection>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,257 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
SettingsSection,
|
||||
SettingsSectionBody,
|
||||
SettingsSectionDescription,
|
||||
SettingsSectionForm,
|
||||
SettingsSectionHeader,
|
||||
SettingsSectionTitle
|
||||
} from "@app/components/Settings";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { SwitchInput } from "@app/components/SwitchInput";
|
||||
import { Tag, TagInput } from "@app/components/tags/tag-input";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage
|
||||
} from "@app/components/ui/form";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from "@app/components/ui/select";
|
||||
import { createPolicySchema, type PolicyFormValues } from ".";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useEffect, useState } from "react";
|
||||
import { type UseFormReturn, useForm, useWatch } from "react-hook-form";
|
||||
|
||||
// ─── CreatePolicyUsersRolesSectionForm ────────────────────────────────────────
|
||||
|
||||
export type CreatePolicyUsersRolesSectionFormProps = {
|
||||
form: UseFormReturn<PolicyFormValues, any, any>;
|
||||
allRoles: { id: string; text: string }[];
|
||||
allUsers: { id: string; text: string }[];
|
||||
allIdps: { id: number; text: string }[];
|
||||
};
|
||||
|
||||
export function CreatePolicyUsersRolesSectionForm({
|
||||
form: parentForm,
|
||||
allRoles,
|
||||
allUsers,
|
||||
allIdps
|
||||
}: CreatePolicyUsersRolesSectionFormProps) {
|
||||
const t = useTranslations();
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(
|
||||
createPolicySchema.pick({
|
||||
sso: true,
|
||||
skipToIdpId: true,
|
||||
roles: true,
|
||||
users: true
|
||||
})
|
||||
),
|
||||
defaultValues: {
|
||||
sso: true,
|
||||
skipToIdpId: null,
|
||||
roles: [],
|
||||
users: []
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const subscription = form.watch((values) => {
|
||||
parentForm.setValue("sso", values.sso as boolean);
|
||||
parentForm.setValue("skipToIdpId", values.skipToIdpId as number | null);
|
||||
parentForm.setValue("roles", values.roles as [Tag, ...Tag[]]);
|
||||
parentForm.setValue("users", values.users as [Tag, ...Tag[]]);
|
||||
});
|
||||
return () => subscription.unsubscribe();
|
||||
}, [form, parentForm]);
|
||||
|
||||
const ssoEnabled = useWatch({ control: form.control, name: "sso" });
|
||||
const selectedIdpId = useWatch({
|
||||
control: form.control,
|
||||
name: "skipToIdpId"
|
||||
});
|
||||
const [activeRolesTagIndex, setActiveRolesTagIndex] = useState<
|
||||
number | null
|
||||
>(null);
|
||||
const [activeUsersTagIndex, setActiveUsersTagIndex] = useState<
|
||||
number | null
|
||||
>(null);
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<SettingsSection>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>
|
||||
{t("resourceUsersRoles")}
|
||||
</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
{t("resourcePolicyUsersRolesDescription")}
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm>
|
||||
<SwitchInput
|
||||
id="sso-toggle"
|
||||
label={t("ssoUse")}
|
||||
defaultChecked={ssoEnabled}
|
||||
onCheckedChange={(val) => {
|
||||
form.setValue("sso", val);
|
||||
}}
|
||||
/>
|
||||
|
||||
{ssoEnabled && (
|
||||
<>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="roles"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-col items-start">
|
||||
<FormLabel>{t("roles")}</FormLabel>
|
||||
<FormControl>
|
||||
<TagInput
|
||||
{...field}
|
||||
activeTagIndex={
|
||||
activeRolesTagIndex
|
||||
}
|
||||
setActiveTagIndex={
|
||||
setActiveRolesTagIndex
|
||||
}
|
||||
placeholder={t(
|
||||
"accessRoleSelect2"
|
||||
)}
|
||||
size="sm"
|
||||
tags={form.getValues().roles}
|
||||
setTags={(newRoles) => {
|
||||
form.setValue(
|
||||
"roles",
|
||||
newRoles as [
|
||||
Tag,
|
||||
...Tag[]
|
||||
]
|
||||
);
|
||||
}}
|
||||
enableAutocomplete={true}
|
||||
autocompleteOptions={allRoles}
|
||||
allowDuplicates={false}
|
||||
restrictTagsToAutocompleteOptions={
|
||||
true
|
||||
}
|
||||
sortTags={true}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
<FormDescription>
|
||||
{t("resourceRoleDescription")}
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="users"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-col items-start">
|
||||
<FormLabel>{t("users")}</FormLabel>
|
||||
<FormControl>
|
||||
<TagInput
|
||||
{...field}
|
||||
activeTagIndex={
|
||||
activeUsersTagIndex
|
||||
}
|
||||
setActiveTagIndex={
|
||||
setActiveUsersTagIndex
|
||||
}
|
||||
placeholder={t(
|
||||
"accessUserSelect"
|
||||
)}
|
||||
size="sm"
|
||||
tags={form.getValues().users}
|
||||
setTags={(newUsers) => {
|
||||
form.setValue(
|
||||
"users",
|
||||
newUsers as [
|
||||
Tag,
|
||||
...Tag[]
|
||||
]
|
||||
);
|
||||
}}
|
||||
enableAutocomplete={true}
|
||||
autocompleteOptions={allUsers}
|
||||
allowDuplicates={false}
|
||||
restrictTagsToAutocompleteOptions={
|
||||
true
|
||||
}
|
||||
sortTags={true}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{ssoEnabled && allIdps.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">
|
||||
{t("defaultIdentityProvider")}
|
||||
</label>
|
||||
<Select
|
||||
onValueChange={(value) => {
|
||||
if (value === "none") {
|
||||
form.setValue("skipToIdpId", null);
|
||||
} else {
|
||||
const id = parseInt(value);
|
||||
form.setValue("skipToIdpId", id);
|
||||
}
|
||||
}}
|
||||
value={
|
||||
selectedIdpId
|
||||
? selectedIdpId.toString()
|
||||
: "none"
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full mt-1">
|
||||
<SelectValue
|
||||
placeholder={t(
|
||||
"selectIdpPlaceholder"
|
||||
)}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">
|
||||
{t("none")}
|
||||
</SelectItem>
|
||||
{allIdps.map((idp) => (
|
||||
<SelectItem
|
||||
key={idp.id}
|
||||
value={idp.id.toString()}
|
||||
>
|
||||
{idp.text}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("defaultIdentityProviderDescription")}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</SettingsSectionForm>
|
||||
</SettingsSectionBody>
|
||||
</SettingsSection>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
@@ -1,671 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
SettingsSection,
|
||||
SettingsSectionBody,
|
||||
SettingsSectionDescription,
|
||||
SettingsSectionFooter,
|
||||
SettingsSectionForm,
|
||||
SettingsSectionHeader,
|
||||
SettingsSectionTitle
|
||||
} from "@app/components/Settings";
|
||||
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
import z from "zod";
|
||||
|
||||
import { createApiClient, formatAxiosError } from "@app/lib/api";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { createPolicySchema } from ".";
|
||||
|
||||
import {
|
||||
Credenza,
|
||||
CredenzaBody,
|
||||
CredenzaClose,
|
||||
CredenzaContent,
|
||||
CredenzaDescription,
|
||||
CredenzaFooter,
|
||||
CredenzaHeader,
|
||||
CredenzaTitle
|
||||
} from "@app/components/Credenza";
|
||||
import { SwitchInput } from "@app/components/SwitchInput";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage
|
||||
} from "@app/components/ui/form";
|
||||
import { Input } from "@app/components/ui/input";
|
||||
import {
|
||||
InputOTP,
|
||||
InputOTPGroup,
|
||||
InputOTPSlot
|
||||
} from "@app/components/ui/input-otp";
|
||||
|
||||
import { Binary, Bot, Key, Plus } from "lucide-react";
|
||||
|
||||
import { cn } from "@app/lib/cn";
|
||||
import { useResourcePolicyContext } from "@app/providers/ResourcePolicyProvider";
|
||||
import { useActionState, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import type { AxiosResponse } from "axios";
|
||||
|
||||
// ─── PolicyAuthMethodsSection ─────────────────────────────────────────────────
|
||||
|
||||
const setPasswordSchema = z.object({
|
||||
password: z.string().min(4).max(100)
|
||||
});
|
||||
|
||||
const setPincodeSchema = z.object({
|
||||
pincode: z.string().length(6)
|
||||
});
|
||||
|
||||
const setHeaderAuthSchema = z.object({
|
||||
user: z.string().min(4).max(100),
|
||||
password: z.string().min(4).max(100),
|
||||
extendedCompatibility: z.boolean()
|
||||
});
|
||||
|
||||
export function EditPolicyAuthMethodsSectionForm({
|
||||
readonly
|
||||
}: {
|
||||
readonly?: boolean;
|
||||
}) {
|
||||
const { policy } = useResourcePolicyContext();
|
||||
const router = useRouter();
|
||||
|
||||
const api = createApiClient(useEnvContext());
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(
|
||||
createPolicySchema.pick({
|
||||
password: true,
|
||||
pincode: true,
|
||||
headerAuth: true
|
||||
})
|
||||
)
|
||||
});
|
||||
|
||||
const t = useTranslations();
|
||||
const [isSetPasswordOpen, setIsSetPasswordOpen] = useState(false);
|
||||
const [isSetPincodeOpen, setIsSetPincodeOpen] = useState(false);
|
||||
const [isSetHeaderAuthOpen, setIsSetHeaderAuthOpen] = useState(false);
|
||||
|
||||
const password = form.watch("password");
|
||||
const pincode = form.watch("pincode");
|
||||
const headerAuth = form.watch("headerAuth");
|
||||
|
||||
// If explicitly removed (set to `null`) it means the value has been removed
|
||||
// in the other case (`undefined` or object value), check if the value has been modified
|
||||
// and fallback to the policy default value
|
||||
const hasPassword =
|
||||
password !== null ? Boolean(password ?? policy.passwordId) : false;
|
||||
|
||||
const hasPincode =
|
||||
pincode !== null ? Boolean(pincode ?? policy.pincodeId) : false;
|
||||
|
||||
const hasHeaderAuth =
|
||||
headerAuth !== null ? Boolean(headerAuth ?? policy.headerAuth) : false;
|
||||
|
||||
const [isExpanded, setIsExpanded] = useState(
|
||||
hasPassword || hasPincode || hasHeaderAuth
|
||||
);
|
||||
|
||||
const passwordForm = useForm({
|
||||
resolver: zodResolver(setPasswordSchema),
|
||||
defaultValues: { password: "" }
|
||||
});
|
||||
|
||||
const pincodeForm = useForm({
|
||||
resolver: zodResolver(setPincodeSchema),
|
||||
defaultValues: { pincode: "" }
|
||||
});
|
||||
|
||||
const headerAuthForm = useForm({
|
||||
resolver: zodResolver(setHeaderAuthSchema),
|
||||
defaultValues: { user: "", password: "", extendedCompatibility: true }
|
||||
});
|
||||
|
||||
const [, formAction, isSubmitting] = useActionState(onSubmit, null);
|
||||
|
||||
async function onSubmit() {
|
||||
if (readonly) return;
|
||||
const isValid = await form.trigger();
|
||||
|
||||
if (!isValid) return;
|
||||
|
||||
const payload = form.getValues();
|
||||
|
||||
const responseArray: Array<Promise<AxiosResponse<{}> | void>> = [];
|
||||
|
||||
if (typeof payload.password !== "undefined") {
|
||||
responseArray.push(
|
||||
api
|
||||
.put<AxiosResponse<{}>>(
|
||||
`/resource-policy/${policy.resourcePolicyId}/password`,
|
||||
{
|
||||
password: payload.password?.password ?? null
|
||||
}
|
||||
)
|
||||
.catch((e) => {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t("policyErrorUpdate"),
|
||||
description: formatAxiosError(
|
||||
e,
|
||||
t("policyErrorUpdateDescription")
|
||||
)
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof payload.pincode !== "undefined") {
|
||||
responseArray.push(
|
||||
api
|
||||
.put<AxiosResponse<{}>>(
|
||||
`/resource-policy/${policy.resourcePolicyId}/pincode`,
|
||||
{
|
||||
pincode: payload.pincode?.pincode ?? null
|
||||
}
|
||||
)
|
||||
.catch((e) => {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t("policyErrorUpdate"),
|
||||
description: formatAxiosError(
|
||||
e,
|
||||
t("policyErrorUpdateDescription")
|
||||
)
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof payload.headerAuth !== "undefined") {
|
||||
responseArray.push(
|
||||
api
|
||||
.put<AxiosResponse<{}>>(
|
||||
`/resource-policy/${policy.resourcePolicyId}/header-auth`,
|
||||
{
|
||||
headerAuth: payload.headerAuth
|
||||
}
|
||||
)
|
||||
.catch((e) => {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t("policyErrorUpdate"),
|
||||
description: formatAxiosError(
|
||||
e,
|
||||
t("policyErrorUpdateDescription")
|
||||
)
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const responseList = await Promise.all(responseArray);
|
||||
|
||||
if (responseList.every((res) => res && res.status === 200)) {
|
||||
toast({
|
||||
title: t("success"),
|
||||
description: t("policyUpdatedSuccess")
|
||||
});
|
||||
router.refresh();
|
||||
}
|
||||
} catch (e) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t("policyErrorUpdate"),
|
||||
description: t("policyErrorUpdateMessageDescription")
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!isExpanded) {
|
||||
return (
|
||||
<SettingsSection>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>
|
||||
{t("resourceAuthMethods")}
|
||||
</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
{t("resourcePolicyAuthMethodsDescription")}
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
{!readonly ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setIsExpanded(true)}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
{t("resourcePolicyAuthMethodAdd")}
|
||||
</Button>
|
||||
) : (
|
||||
<div className="text-muted-foreground flex items-center h-full size-full bg-muted rounded-md px-8 py-6 border-dashed text-sm">
|
||||
<p>{t("resourcePolicyAuthMethodsEmpty")}</p>
|
||||
</div>
|
||||
)}
|
||||
</SettingsSectionBody>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Password Credenza */}
|
||||
<Credenza
|
||||
open={isSetPasswordOpen}
|
||||
onOpenChange={(val) => {
|
||||
setIsSetPasswordOpen(val);
|
||||
if (!val) passwordForm.reset();
|
||||
}}
|
||||
>
|
||||
<CredenzaContent>
|
||||
<CredenzaHeader>
|
||||
<CredenzaTitle>
|
||||
{t("resourcePasswordSetupTitle")}
|
||||
</CredenzaTitle>
|
||||
<CredenzaDescription>
|
||||
{t("resourcePasswordSetupTitleDescription")}
|
||||
</CredenzaDescription>
|
||||
</CredenzaHeader>
|
||||
<CredenzaBody>
|
||||
<Form {...passwordForm}>
|
||||
<form
|
||||
onSubmit={passwordForm.handleSubmit((data) => {
|
||||
form.setValue("password", data);
|
||||
setIsSetPasswordOpen(false);
|
||||
passwordForm.reset();
|
||||
})}
|
||||
className="space-y-4"
|
||||
id="set-password-form"
|
||||
>
|
||||
<FormField
|
||||
control={passwordForm.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("password")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
type="password"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</CredenzaBody>
|
||||
<CredenzaFooter>
|
||||
<CredenzaClose asChild>
|
||||
<Button variant="outline">{t("close")}</Button>
|
||||
</CredenzaClose>
|
||||
<Button type="submit" form="set-password-form">
|
||||
{t("resourcePasswordSubmit")}
|
||||
</Button>
|
||||
</CredenzaFooter>
|
||||
</CredenzaContent>
|
||||
</Credenza>
|
||||
|
||||
{/* Pincode Credenza */}
|
||||
<Credenza
|
||||
open={isSetPincodeOpen}
|
||||
onOpenChange={(val) => {
|
||||
setIsSetPincodeOpen(val);
|
||||
if (!val) pincodeForm.reset();
|
||||
}}
|
||||
>
|
||||
<CredenzaContent>
|
||||
<CredenzaHeader>
|
||||
<CredenzaTitle>
|
||||
{t("resourcePincodeSetupTitle")}
|
||||
</CredenzaTitle>
|
||||
<CredenzaDescription>
|
||||
{t("resourcePincodeSetupTitleDescription")}
|
||||
</CredenzaDescription>
|
||||
</CredenzaHeader>
|
||||
<CredenzaBody>
|
||||
<Form {...pincodeForm}>
|
||||
<form
|
||||
onSubmit={pincodeForm.handleSubmit((data) => {
|
||||
form.setValue("pincode", data);
|
||||
setIsSetPincodeOpen(false);
|
||||
pincodeForm.reset();
|
||||
})}
|
||||
className="space-y-4"
|
||||
id="set-pincode-form"
|
||||
>
|
||||
<FormField
|
||||
control={pincodeForm.control}
|
||||
name="pincode"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("resourcePincode")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<div className="flex justify-center">
|
||||
<InputOTP
|
||||
autoComplete="false"
|
||||
maxLength={6}
|
||||
{...field}
|
||||
>
|
||||
<InputOTPGroup className="flex">
|
||||
<InputOTPSlot
|
||||
index={0}
|
||||
obscured
|
||||
/>
|
||||
<InputOTPSlot
|
||||
index={1}
|
||||
obscured
|
||||
/>
|
||||
<InputOTPSlot
|
||||
index={2}
|
||||
obscured
|
||||
/>
|
||||
<InputOTPSlot
|
||||
index={3}
|
||||
obscured
|
||||
/>
|
||||
<InputOTPSlot
|
||||
index={4}
|
||||
obscured
|
||||
/>
|
||||
<InputOTPSlot
|
||||
index={5}
|
||||
obscured
|
||||
/>
|
||||
</InputOTPGroup>
|
||||
</InputOTP>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</CredenzaBody>
|
||||
<CredenzaFooter>
|
||||
<CredenzaClose asChild>
|
||||
<Button variant="outline">{t("close")}</Button>
|
||||
</CredenzaClose>
|
||||
<Button type="submit" form="set-pincode-form">
|
||||
{t("resourcePincodeSubmit")}
|
||||
</Button>
|
||||
</CredenzaFooter>
|
||||
</CredenzaContent>
|
||||
</Credenza>
|
||||
|
||||
{/* Header Auth Credenza */}
|
||||
<Credenza
|
||||
open={isSetHeaderAuthOpen}
|
||||
onOpenChange={(val) => {
|
||||
setIsSetHeaderAuthOpen(val);
|
||||
if (!val) headerAuthForm.reset();
|
||||
}}
|
||||
>
|
||||
<CredenzaContent>
|
||||
<CredenzaHeader>
|
||||
<CredenzaTitle>
|
||||
{t("resourceHeaderAuthSetupTitle")}
|
||||
</CredenzaTitle>
|
||||
<CredenzaDescription>
|
||||
{t("resourceHeaderAuthSetupTitleDescription")}
|
||||
</CredenzaDescription>
|
||||
</CredenzaHeader>
|
||||
<CredenzaBody>
|
||||
<Form {...headerAuthForm}>
|
||||
<form
|
||||
onSubmit={headerAuthForm.handleSubmit(
|
||||
(data) => {
|
||||
form.setValue("headerAuth", data);
|
||||
setIsSetHeaderAuthOpen(false);
|
||||
headerAuthForm.reset();
|
||||
}
|
||||
)}
|
||||
className="space-y-4"
|
||||
id="set-header-auth-form"
|
||||
>
|
||||
<FormField
|
||||
control={headerAuthForm.control}
|
||||
name="user"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("user")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
type="text"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={headerAuthForm.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("password")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
type="password"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={headerAuthForm.control}
|
||||
name="extendedCompatibility"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<SwitchInput
|
||||
id="header-auth-compatibility-toggle"
|
||||
label={t(
|
||||
"headerAuthCompatibility"
|
||||
)}
|
||||
description={t(
|
||||
"headerAuthCompatibilityInfo"
|
||||
)}
|
||||
checked={field.value}
|
||||
onCheckedChange={
|
||||
field.onChange
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</CredenzaBody>
|
||||
<CredenzaFooter>
|
||||
<CredenzaClose asChild>
|
||||
<Button variant="outline">{t("close")}</Button>
|
||||
</CredenzaClose>
|
||||
<Button type="submit" form="set-header-auth-form">
|
||||
{t("resourceHeaderAuthSubmit")}
|
||||
</Button>
|
||||
</CredenzaFooter>
|
||||
</CredenzaContent>
|
||||
</Credenza>
|
||||
|
||||
<Form {...form}>
|
||||
<form action={formAction}>
|
||||
<SettingsSection>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>
|
||||
{t("resourceAuthMethods")}
|
||||
</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
{t("resourcePolicyAuthMethodsDescription")}
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm>
|
||||
{/* Password row */}
|
||||
<div className="flex items-center justify-between border rounded-md p-2 mb-4">
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center text-sm gap-x-2",
|
||||
hasPassword && "text-green-500"
|
||||
)}
|
||||
>
|
||||
<Key size="14" />
|
||||
<span>
|
||||
{t("resourcePasswordProtection", {
|
||||
status: hasPassword
|
||||
? t("enabled")
|
||||
: t("disabled")
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
disabled={readonly}
|
||||
onClick={
|
||||
hasPassword
|
||||
? () =>
|
||||
form.setValue(
|
||||
"password",
|
||||
null
|
||||
)
|
||||
: () =>
|
||||
setIsSetPasswordOpen(true)
|
||||
}
|
||||
>
|
||||
{hasPassword
|
||||
? t("passwordRemove")
|
||||
: t("passwordAdd")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Pincode row */}
|
||||
<div className="flex items-center justify-between border rounded-md p-2">
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-x-2 text-sm",
|
||||
hasPincode && "text-green-500"
|
||||
)}
|
||||
>
|
||||
<Binary size="14" />
|
||||
<span>
|
||||
{t("resourcePincodeProtection", {
|
||||
status: hasPincode
|
||||
? t("enabled")
|
||||
: t("disabled")
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
disabled={readonly}
|
||||
onClick={
|
||||
hasPincode
|
||||
? () =>
|
||||
form.setValue(
|
||||
"pincode",
|
||||
null
|
||||
)
|
||||
: () =>
|
||||
setIsSetPincodeOpen(true)
|
||||
}
|
||||
>
|
||||
{hasPincode
|
||||
? t("pincodeRemove")
|
||||
: t("pincodeAdd")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Header auth row */}
|
||||
<div className="flex items-center justify-between border rounded-md p-2">
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-x-2 text-sm",
|
||||
hasHeaderAuth && "text-green-500"
|
||||
)}
|
||||
>
|
||||
<Bot size="14" />
|
||||
<span>
|
||||
{hasHeaderAuth
|
||||
? t(
|
||||
"resourceHeaderAuthProtectionEnabled"
|
||||
)
|
||||
: t(
|
||||
"resourceHeaderAuthProtectionDisabled"
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
disabled={readonly}
|
||||
onClick={
|
||||
hasHeaderAuth
|
||||
? () =>
|
||||
form.setValue(
|
||||
"headerAuth",
|
||||
null
|
||||
)
|
||||
: () =>
|
||||
setIsSetHeaderAuthOpen(
|
||||
true
|
||||
)
|
||||
}
|
||||
>
|
||||
{hasHeaderAuth
|
||||
? t("headerAuthRemove")
|
||||
: t("headerAuthAdd")}
|
||||
</Button>
|
||||
</div>
|
||||
</SettingsSectionForm>
|
||||
</SettingsSectionBody>
|
||||
|
||||
<SettingsSectionFooter>
|
||||
<Button
|
||||
type="submit"
|
||||
loading={isSubmitting}
|
||||
disabled={readonly || isSubmitting}
|
||||
>
|
||||
{t("authMethodsSave")}
|
||||
</Button>
|
||||
</SettingsSectionFooter>
|
||||
</SettingsSection>
|
||||
</form>
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -10,44 +10,34 @@ import { orgQueries } from "@app/lib/queries";
|
||||
import { build } from "@server/build";
|
||||
import { tierMatrix } from "@server/lib/billing/tierMatrix";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
import { createApiClient } from "@app/lib/api";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import { EditPolicyAuthMethodsSectionForm } from "./EditPolicyAuthMethodsSectionForm";
|
||||
import { EditPolicyNameSectionForm } from "./EditPolicyNameSectionForm";
|
||||
import { EditPolicyUsersRolesSectionForm } from "./EditPolicyUserRolesSectionForm";
|
||||
import { EditPolicyOtpEmailSectionForm } from "./EditPolicyOtpEmailSectionForm";
|
||||
import { EditPolicyRulesSectionForm } from "./EditPolicyRulesSectionForm";
|
||||
import { PolicyAuthStackSection } from "./PolicyAuthStackSection";
|
||||
import { PolicyAccessRulesSection } from "./PolicyAccessRulesSection";
|
||||
|
||||
// ─── EditPolicyForm ─────────────────────────────────────────────────────────
|
||||
export type EditPolicyFormSection = "general" | "authentication" | "rules";
|
||||
|
||||
export type EditPolicyFormProps = {
|
||||
hidePolicyNameForm?: boolean;
|
||||
readonly?: boolean;
|
||||
resourceId?: number;
|
||||
section?: EditPolicyFormSection;
|
||||
};
|
||||
|
||||
export function EditPolicyForm({
|
||||
hidePolicyNameForm,
|
||||
readonly,
|
||||
resourceId
|
||||
resourceId,
|
||||
section
|
||||
}: EditPolicyFormProps) {
|
||||
const { org } = useOrgContext();
|
||||
const t = useTranslations();
|
||||
const { env } = useEnvContext();
|
||||
const api = createApiClient({ env });
|
||||
// const [, formAction, isSubmitting] = useActionState(onSubmit, null);
|
||||
const { isPaidUser } = usePaidStatus();
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
// In overlay mode (resourceId provided), policy-level sections are locked.
|
||||
// Rules and users/roles sections handle their own hybrid logic via resourceId.
|
||||
const isOverlay = resourceId !== undefined;
|
||||
const policyLevelReadonly = readonly || isOverlay;
|
||||
|
||||
const isMaxmindAvailable = !!(
|
||||
env.server.maxmind_db_path && env.server.maxmind_db_path.length > 0
|
||||
@@ -81,32 +71,48 @@ export function EditPolicyForm({
|
||||
return <></>;
|
||||
}
|
||||
|
||||
const authSection = (
|
||||
<PolicyAuthStackSection
|
||||
mode="edit"
|
||||
orgId={org.org.orgId}
|
||||
allIdps={allIdps}
|
||||
emailEnabled={env.email.emailEnabled}
|
||||
readonly={readonly}
|
||||
resourceId={resourceId}
|
||||
/>
|
||||
);
|
||||
|
||||
const rulesSection = (
|
||||
<PolicyAccessRulesSection
|
||||
mode="edit"
|
||||
isMaxmindAvailable={isMaxmindAvailable}
|
||||
isMaxmindAsnAvailable={isMaxmindASNAvailable}
|
||||
readonly={readonly}
|
||||
resourceId={resourceId}
|
||||
/>
|
||||
);
|
||||
|
||||
if (section === "general") {
|
||||
return <EditPolicyNameSectionForm readonly={readonly} />;
|
||||
}
|
||||
|
||||
if (section === "authentication") {
|
||||
return authSection;
|
||||
}
|
||||
|
||||
if (section === "rules") {
|
||||
return rulesSection;
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsContainer>
|
||||
{!hidePolicyNameForm && (
|
||||
<EditPolicyNameSectionForm readonly={policyLevelReadonly} />
|
||||
{!hidePolicyNameForm && !isOverlay && (
|
||||
<EditPolicyNameSectionForm readonly={readonly} />
|
||||
)}
|
||||
|
||||
<EditPolicyUsersRolesSectionForm
|
||||
orgId={org.org.orgId}
|
||||
allIdps={allIdps}
|
||||
readonly={readonly}
|
||||
resourceId={resourceId}
|
||||
/>
|
||||
{authSection}
|
||||
|
||||
<EditPolicyAuthMethodsSectionForm readonly={policyLevelReadonly} />
|
||||
|
||||
<EditPolicyOtpEmailSectionForm
|
||||
emailEnabled={env.email.emailEnabled}
|
||||
readonly={policyLevelReadonly}
|
||||
/>
|
||||
|
||||
<EditPolicyRulesSectionForm
|
||||
isMaxmindAvailable={isMaxmindAvailable}
|
||||
isMaxmindAsnAvailable={isMaxmindASNAvailable}
|
||||
readonly={readonly}
|
||||
resourceId={resourceId}
|
||||
/>
|
||||
{rulesSection}
|
||||
</SettingsContainer>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from "@app/components/Settings";
|
||||
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { useOrgContext } from "@app/hooks/useOrgContext";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useTranslations } from "next-intl";
|
||||
@@ -40,21 +41,28 @@ import { useForm } from "react-hook-form";
|
||||
|
||||
// ─── PolicyNameSection ──────────────────────────────────────────────────
|
||||
|
||||
export function EditPolicyNameSectionForm({ readonly }: { readonly?: boolean }) {
|
||||
const PolicyNameFormSchema = z.object({
|
||||
name: z.string(),
|
||||
niceId: z.string().min(1).max(255).optional()
|
||||
});
|
||||
|
||||
export function EditPolicyNameSectionForm({
|
||||
readonly
|
||||
}: {
|
||||
readonly?: boolean;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const api = createApiClient(useEnvContext());
|
||||
const router = useRouter();
|
||||
const { org } = useOrgContext();
|
||||
|
||||
const { policy } = useResourcePolicyContext();
|
||||
const { policy, updatePolicy } = useResourcePolicyContext();
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(
|
||||
z.object({
|
||||
name: z.string()
|
||||
})
|
||||
),
|
||||
resolver: zodResolver(PolicyNameFormSchema),
|
||||
defaultValues: {
|
||||
name: policy.name
|
||||
name: policy.name,
|
||||
niceId: policy.niceId || ""
|
||||
}
|
||||
});
|
||||
|
||||
@@ -73,7 +81,8 @@ export function EditPolicyNameSectionForm({ readonly }: { readonly?: boolean })
|
||||
.put<AxiosResponse<ResourcePolicy>>(
|
||||
`/resource-policy/${policy.resourcePolicyId}`,
|
||||
{
|
||||
name: payload.name
|
||||
name: payload.name,
|
||||
niceId: payload.niceId
|
||||
}
|
||||
)
|
||||
.catch((e) => {
|
||||
@@ -88,10 +97,22 @@ export function EditPolicyNameSectionForm({ readonly }: { readonly?: boolean })
|
||||
});
|
||||
|
||||
if (res && res.status === 200) {
|
||||
updatePolicy({
|
||||
name: payload.name,
|
||||
niceId: payload.niceId
|
||||
});
|
||||
|
||||
toast({
|
||||
title: t("success"),
|
||||
description: t("policyUpdatedSuccess")
|
||||
});
|
||||
|
||||
if (payload.niceId && payload.niceId !== policy.niceId) {
|
||||
router.replace(
|
||||
`/${org.org.orgId}/settings/policies/resources/public/${payload.niceId}/general`
|
||||
);
|
||||
}
|
||||
|
||||
router.refresh();
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -116,7 +137,7 @@ export function EditPolicyNameSectionForm({ readonly }: { readonly?: boolean })
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm>
|
||||
<SettingsSectionForm variant="half">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
@@ -136,6 +157,26 @@ export function EditPolicyNameSectionForm({ readonly }: { readonly?: boolean })
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="niceId"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("identifier")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
disabled={readonly}
|
||||
placeholder={t(
|
||||
"enterIdentifier"
|
||||
)}
|
||||
className="flex-1"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</SettingsSectionForm>
|
||||
</SettingsSectionBody>
|
||||
|
||||
|
||||
@@ -1,294 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
SettingsSection,
|
||||
SettingsSectionBody,
|
||||
SettingsSectionDescription,
|
||||
SettingsSectionFooter,
|
||||
SettingsSectionForm,
|
||||
SettingsSectionHeader,
|
||||
SettingsSectionTitle
|
||||
} from "@app/components/Settings";
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
import z from "zod";
|
||||
|
||||
import { createPolicySchema, type PolicyFormValues } from ".";
|
||||
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { createApiClient, formatAxiosError } from "@app/lib/api";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import type { AxiosResponse } from "axios";
|
||||
import { SwitchInput } from "@app/components/SwitchInput";
|
||||
import { Tag, TagInput } from "@app/components/tags/tag-input";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@app/components/ui/alert";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel
|
||||
} from "@app/components/ui/form";
|
||||
import { InfoPopup } from "@app/components/ui/info-popup";
|
||||
|
||||
import { InfoIcon, Plus } from "lucide-react";
|
||||
|
||||
import { useActionState, useState } from "react";
|
||||
import { useForm, UseFormReturn, useWatch } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useResourcePolicyContext } from "@app/providers/ResourcePolicyProvider";
|
||||
|
||||
// ─── PolicyOtpEmailSection ────────────────────────────────────────────────────
|
||||
|
||||
type PolicyOtpEmailSectionProps = {
|
||||
emailEnabled: boolean;
|
||||
readonly?: boolean;
|
||||
};
|
||||
|
||||
export function EditPolicyOtpEmailSectionForm({
|
||||
emailEnabled,
|
||||
readonly
|
||||
}: PolicyOtpEmailSectionProps) {
|
||||
const t = useTranslations();
|
||||
|
||||
const { policy } = useResourcePolicyContext();
|
||||
const router = useRouter();
|
||||
|
||||
const api = createApiClient(useEnvContext());
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(
|
||||
createPolicySchema.pick({
|
||||
emailWhitelistEnabled: true,
|
||||
emails: true
|
||||
})
|
||||
),
|
||||
defaultValues: {
|
||||
emailWhitelistEnabled: policy.emailWhitelistEnabled,
|
||||
emails: policy.emailWhiteList.map((email) => ({
|
||||
id: email.whiteListId.toString(),
|
||||
text: email.email
|
||||
}))
|
||||
}
|
||||
});
|
||||
|
||||
const whitelistEnabled = useWatch({
|
||||
control: form.control,
|
||||
name: "emailWhitelistEnabled"
|
||||
});
|
||||
|
||||
const [isExpanded, setIsExpanded] = useState(whitelistEnabled);
|
||||
const [activeEmailTagIndex, setActiveEmailTagIndex] = useState<
|
||||
number | null
|
||||
>(null);
|
||||
|
||||
const [, formAction, isSubmitting] = useActionState(onSubmit, null);
|
||||
|
||||
async function onSubmit() {
|
||||
if (readonly) return;
|
||||
const isValid = await form.trigger();
|
||||
|
||||
if (!isValid) return;
|
||||
|
||||
const payload = form.getValues();
|
||||
|
||||
try {
|
||||
const res = await api
|
||||
.put<AxiosResponse<{}>>(
|
||||
`/resource-policy/${policy.resourcePolicyId}/whitelist`,
|
||||
{
|
||||
emailWhitelistEnabled: payload.emailWhitelistEnabled,
|
||||
emails: payload.emails?.map((e) => e.text) ?? []
|
||||
}
|
||||
)
|
||||
.catch((e) => {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t("policyErrorUpdate"),
|
||||
description: formatAxiosError(
|
||||
e,
|
||||
t("policyErrorUpdateDescription")
|
||||
)
|
||||
});
|
||||
});
|
||||
|
||||
if (res && res.status === 200) {
|
||||
toast({
|
||||
title: t("success"),
|
||||
description: t("policyUpdatedSuccess")
|
||||
});
|
||||
router.refresh();
|
||||
}
|
||||
} catch (e) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t("policyErrorUpdate"),
|
||||
description: t("policyErrorUpdateMessageDescription")
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!isExpanded) {
|
||||
return (
|
||||
<SettingsSection>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>
|
||||
{t("otpEmailTitle")}
|
||||
</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
{t("otpEmailTitleDescription")}
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
{!readonly ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setIsExpanded(true)}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
{t("resourcePolicyOtpEmailAdd")}
|
||||
</Button>
|
||||
) : (
|
||||
<div className="text-muted-foreground flex items-center h-full size-full bg-muted rounded-md px-8 py-6 border-dashed text-sm">
|
||||
<p>{t("resourcePolicyOtpEmpty")}</p>
|
||||
</div>
|
||||
)}
|
||||
</SettingsSectionBody>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form action={formAction}>
|
||||
<SettingsSection>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>
|
||||
{t("otpEmailTitle")}
|
||||
</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
{t("otpEmailTitleDescription")}
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm>
|
||||
{!emailEnabled && (
|
||||
<Alert variant="neutral" className="mb-4">
|
||||
<InfoIcon className="h-4 w-4" />
|
||||
<AlertTitle className="font-semibold">
|
||||
{t("otpEmailSmtpRequired")}
|
||||
</AlertTitle>
|
||||
<AlertDescription>
|
||||
{t("otpEmailSmtpRequiredDescription")}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<SwitchInput
|
||||
id="whitelist-toggle"
|
||||
label={t("otpEmailWhitelist")}
|
||||
defaultChecked={whitelistEnabled}
|
||||
onCheckedChange={(val) => {
|
||||
form.setValue("emailWhitelistEnabled", val);
|
||||
}}
|
||||
disabled={readonly || !emailEnabled}
|
||||
/>
|
||||
|
||||
{whitelistEnabled && emailEnabled && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="emails"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
<InfoPopup
|
||||
text={t(
|
||||
"otpEmailWhitelistList"
|
||||
)}
|
||||
info={t(
|
||||
"otpEmailWhitelistListDescription"
|
||||
)}
|
||||
/>
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
{/* @ts-ignore */}
|
||||
<TagInput
|
||||
{...field}
|
||||
activeTagIndex={
|
||||
activeEmailTagIndex
|
||||
}
|
||||
size="sm"
|
||||
validateTag={(tag) => {
|
||||
return z
|
||||
.email()
|
||||
.or(
|
||||
z
|
||||
.string()
|
||||
.regex(
|
||||
/^\*@[\w.-]+\.[a-zA-Z]{2,}$/,
|
||||
{
|
||||
message:
|
||||
t(
|
||||
"otpEmailErrorInvalid"
|
||||
)
|
||||
}
|
||||
)
|
||||
)
|
||||
.safeParse(tag)
|
||||
.success;
|
||||
}}
|
||||
setActiveTagIndex={
|
||||
setActiveEmailTagIndex
|
||||
}
|
||||
placeholder={t(
|
||||
"otpEmailEnter"
|
||||
)}
|
||||
tags={
|
||||
form.getValues()
|
||||
.emails ?? []
|
||||
}
|
||||
setTags={(newEmails) => {
|
||||
if (!readonly) {
|
||||
form.setValue(
|
||||
"emails",
|
||||
newEmails as [
|
||||
Tag,
|
||||
...Tag[]
|
||||
]
|
||||
);
|
||||
}
|
||||
}}
|
||||
allowDuplicates={false}
|
||||
sortTags={true}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t("otpEmailEnterDescription")}
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</SettingsSectionForm>
|
||||
|
||||
<SettingsSectionFooter>
|
||||
<Button
|
||||
type="submit"
|
||||
loading={isSubmitting}
|
||||
disabled={
|
||||
readonly || isSubmitting || !emailEnabled
|
||||
}
|
||||
>
|
||||
{t("otpEmailWhitelistSave")}
|
||||
</Button>
|
||||
</SettingsSectionFooter>
|
||||
</SettingsSectionBody>
|
||||
</SettingsSection>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user