Compare commits

...

59 Commits
main ... dev-ms

Author SHA1 Message Date
Owen
e19b267fd4 Merge branch 'dev-ms' of github.com:fosrl/pangolin into dev-ms 2025-11-13 21:44:23 -05:00
miloschwartz
b3ecec5cbe restyle maintenance mode screen 2025-11-13 21:40:18 -05:00
Owen
918e91123e Restrict license 2025-11-13 21:11:05 -05:00
Owen
b1a76f889a Update form 2025-11-13 21:05:13 -05:00
Owen Schwartz
08892f4e8e Merge pull request #1789 from Pallavikumarimdb/feat/down-for-maintenance
Down for maintenance screen
2025-11-13 18:32:45 -05:00
Owen
3dc119d31e Make private 2025-11-13 18:27:04 -05:00
miloschwartz
8674ca931b remove from address in saas suppport email 2025-11-13 17:34:49 -05:00
Owen Schwartz
864b587b89 Merge pull request #1858 from Pallavikumarimdb/role-in-headers
Role in headers
2025-11-13 17:16:31 -05:00
Owen Schwartz
ca89aa7ce8 Merge pull request #1847 from Pallavikumarimdb/fix/ipv6-validation
Fix: Improve IPv6 and IPV4 validation to support all variants using ipaddr.js
2025-11-13 17:10:47 -05:00
Pallavi Kumari
63a1ecfb86 role in header 2025-11-13 23:31:29 +05:30
Pallavi Kumari
c004e969cb improve IPv6 validation to support all variants using ipaddr.js 2025-11-12 00:30:08 +05:30
Pallavi Kumari
2997117df1 redirect everything to maintenance page 2025-11-11 01:17:59 +05:30
Pallavi Kumari
87acfcdb26 add to priv route 2025-11-11 00:56:13 +05:30
Pallavi Kumari
e314dbd1aa add backend API maintenance screen 2025-11-10 21:59:17 +05:30
Pallavi Kumari
177223e0ad Lazy-Load DB for maintenance-screen 2025-11-10 20:40:34 +05:30
Pallavi Kumari
1023b0664c Skip config fetch during build 2025-11-10 19:48:22 +05:30
Pallavi Kumari
63d366e277 add logger 2025-11-10 19:48:22 +05:30
Pallavi Kumari
ca4513e418 add tooltip 2025-11-10 19:48:22 +05:30
Pallavi Kumari
df1a00d449 point the resource to the nextjs server for maintenance screen 2025-11-10 19:47:52 +05:30
Pallavi Kumari
93bfd18706 remove maintenance mode from oss traefik config generator 2025-11-10 19:47:31 +05:30
Pallavi Kumari
cdbf7d9d4e move settings into a new SettingsSection card 2025-11-10 19:46:40 +05:30
Pallavi Kumari
f8aa30304b add en-Us strings 2025-11-10 19:46:40 +05:30
Pallavi Kumari
8ca3d3fa74 refactor files and add func to private traefik config generator file 2025-11-10 19:46:17 +05:30
Pallavi Kumari
9d14dbe9cc fix maintenance router name 2025-11-10 19:46:17 +05:30
Pallavi Kumari
5473c134c6 add pg schema 2025-11-10 19:46:17 +05:30
Pallavi Kumari
d3b95f5b1e generate traefik config for maintenance ui 2025-11-10 19:46:17 +05:30
Pallavi Kumari
f64f889e2e backend for updating maintenance screen 2025-11-10 19:44:50 +05:30
Pallavi Kumari
79cd9079f6 ui to enable down for maintenance screen 2025-11-10 19:44:50 +05:30
Pallavi Kumari
0022663d59 db schema for maintenance 2025-11-10 19:44:50 +05:30
Owen
bdf1625976 Add headers 2025-11-09 10:46:46 -08:00
Owen
0a5dc17800 Merge branch 'dev' into feat/option-to-regenerate-keys 2025-11-09 10:43:26 -08:00
Owen
fa7aa508ea Merge branch 'dev' into pallavi/feat/make-niceId-editable 2025-11-09 10:39:30 -08:00
Pallavi Kumari
0af51cebbe scope niceid to the orgId 2025-11-08 19:44:23 +05:30
Pallavi Kumari
abc5f8ec68 show the identifier in the info box 2025-11-08 19:44:23 +05:30
Owen
ddc14d164e Rename nice id to Identifier in the ui 2025-11-08 19:44:23 +05:30
Pallavi Kumari
aeda85fcfb move resource niceid update to general page 2025-11-08 19:44:23 +05:30
Pallavi Kumari
66124f09c4 move site niceId details to general setting page 2025-11-08 19:44:23 +05:30
Pallavi Kumari
ac5fe1486a update url to prevent page redirect 2025-11-08 19:44:23 +05:30
Pallavi Kumari
50ac52d316 fix lint 2025-11-08 19:44:22 +05:30
Pallavi Kumari
f85d9f8b6e fix col 2025-11-08 19:44:22 +05:30
Pallavi Kumari
feb0bd58c8 make resource niceid editable 2025-11-08 19:44:22 +05:30
Pallavi Kumari
32949127d2 Make site niceId editable 2025-11-08 19:44:22 +05:30
Pallavi Kumari
84d24d9bf5 niceId inside resource info 2025-11-08 19:44:22 +05:30
Pallavi Kumari
8e1bb6a6fd add niceId inside info box 2025-11-08 19:44:22 +05:30
Pallavi Kumari
b6e98632b5 move re-key API routes to private api 2025-11-08 02:43:47 +05:30
Pallavi Kumari
8a5f59cb9f disable re-key button for non licensed 2025-11-08 01:38:47 +05:30
Pallavi Kumari
2b8204fdc8 seperate credentials rekeying in modal for reuse 2025-11-07 23:30:24 +05:30
Pallavi Kumari
90e72c6aca hide credentials tab for local sites 2025-11-07 19:27:03 +05:30
Pallavi Kumari
62e2b7ca9e change alert text 2025-11-07 19:27:03 +05:30
Pallavi Kumari
f7e7993fd4 regenerate secret for wireguard 2025-11-07 19:27:03 +05:30
Pallavi Kumari
18cdf070c7 add view setting options 2025-11-07 19:27:03 +05:30
Pallavi Kumari
563a5b3e7e disable credential regenerate button for local and wireguard 2025-11-07 19:27:03 +05:30
Pallavi Kumari
3756aaecda change file naming structure to reGenerate exit node keys 2025-11-07 19:27:03 +05:30
Pallavi Kumari
58a13de0ff fix lint 2025-11-07 19:27:03 +05:30
Pallavi Kumari
d32505a833 Option to regenerate Newt keys 2025-11-07 19:27:03 +05:30
Pallavi Kumari
42091e88cb rename exit node tab to credentials 2025-11-07 19:27:03 +05:30
Pallavi Kumari
c2f607bb9a Option to regenerate olm keys inside client 2025-11-07 19:27:03 +05:30
Pallavi Kumari
3f38080b46 fix lint 2025-11-07 19:27:03 +05:30
Pallavi Kumari
9f9aa07c2d Option to regenerate remote-nodes keys 2025-11-07 19:27:03 +05:30
52 changed files with 3400 additions and 1075 deletions

View File

@@ -2095,5 +2095,56 @@
"selectedResources": "Selected Resources",
"enableSelected": "Enable Selected",
"disableSelected": "Disable Selected",
"checkSelectedStatus": "Check Status of Selected"
}
"checkSelectedStatus": "Check Status of Selected",
"credentials": "Credentials",
"savecredentials": "Save Credentials",
"regeneratecredentials": "Re-key",
"regenerateCredentials": "Regenerate and save your credentials",
"generatedcredentials": "Generated Credentials",
"copyandsavethesecredentials": "Copy and save these credentials",
"copyandsavethesecredentialsdescription": "These credentials will not be shown again after you leave this page. Save them securely now.",
"credentialsSaved" : "Credentials Saved",
"credentialsSavedDescription": "Credentials have been regenerated and saved successfully.",
"credentialsSaveError": "Credentials Save Error",
"credentialsSaveErrorDescription": "An error occurred while regenerating and saving the credentials.",
"regenerateCredentialsWarning": "Regenerating credentials will invalidate the previous ones. Make sure to update any configurations that use these credentials.",
"confirm": "Confirm",
"regenerateCredentialsConfirmation": "Are you sure you want to regenerate the credentials?",
"endpoint": "Endpoint",
"Id": "Id",
"SecretKey": "Secret Key",
"featureDisabledTooltip": "This feature is only available in the enterprise plan and require a license to use it.",
"niceId": "Nice ID",
"niceIdUpdated": "Nice ID Updated",
"niceIdUpdatedSuccessfully": "Nice ID Updated Successfully",
"niceIdUpdateError": "Error updating Nice ID",
"niceIdUpdateErrorDescription": "An error occurred while updating the Nice ID.",
"niceIdCannotBeEmpty": "Nice ID cannot be empty",
"enterIdentifier": "Enter identifier",
"identifier": "Identifier",
"maintenanceMode": "Maintenance Mode",
"maintenanceModeDescription": "Display a maintenance page to visitors",
"maintenanceModeType": "Maintenance Mode Type",
"showMaintenancePage": "Show a maintenance page to visitors",
"enableMaintenanceMode": "Enable Maintenance Mode",
"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",
"forcedModeDescription": "Always show the maintenance page regardless of backend health. Use this for planned maintenance when you want to prevent all access.",
"warning:" : "Warning:",
"forcedeModeWarning": "All traffic will be directed to the maintenance page. Your backend resources will not receive any requests.",
"pageTitle": "Page Title",
"pageTitleDescription": "The main heading displayed on the maintenance page",
"maintenancePageMessage": "Maintenance Message",
"maintenancePageMessagePlaceholder": "We'll be back soon! Our site is currently undergoing scheduled maintenance.",
"maintenancePageMessageDescription": "Detailed message explaining the maintenance",
"maintenancePageTimeTitle": "Estimated Completion Time (Optional)",
"maintenanceTime": "e.g., 2 hours, Nov 1 at 5:00 PM",
"maintenanceEstimatedTimeDescription": "When you expect maintenance to be completed",
"editDomain": "Edit Domain",
"editDomainDescription": "Select a domain for your resource",
"maintenanceModeDisabledTooltip": "This feature requires a valid license to enable.",
"maintenanceScreenTitle": "Service Temporarily Unavailable",
"maintenanceScreenMessage": "We are currently experiencing technical difficulties. Please check back soon.",
"maintenanceScreenEstimatedCompletion": "Estimated Completion:"
}

1796
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -19,6 +19,7 @@ export enum ActionsEnum {
getSite = "getSite",
listSites = "listSites",
updateSite = "updateSite",
reGenerateSecret = "reGenerateSecret",
createResource = "createResource",
deleteResource = "deleteResource",
getResource = "getResource",

View File

@@ -130,7 +130,15 @@ export const resources = pgTable("resources", {
}),
headers: text("headers"), // comma-separated list of headers to add to the request
proxyProtocol: boolean("proxyProtocol").notNull().default(false),
proxyProtocolVersion: integer("proxyProtocolVersion").default(1)
proxyProtocolVersion: integer("proxyProtocolVersion").default(1),
maintenanceModeEnabled: boolean("maintenanceModeEnabled").notNull().default(false),
maintenanceModeType: text("maintenanceModeType", {
enum: ["forced", "automatic"]
}).default("forced"), // "forced" = always show, "automatic" = only when down
maintenanceTitle: text("maintenanceTitle"),
maintenanceMessage: text("maintenanceMessage"),
maintenanceEstimatedTime: text("maintenanceEstimatedTime"),
});
export const targets = pgTable("targets", {

View File

@@ -25,7 +25,7 @@ export const dnsRecords = sqliteTable("dnsRecords", {
recordType: text("recordType").notNull(), // "NS" | "CNAME" | "A" | "TXT"
baseDomain: text("baseDomain"),
value: text("value").notNull(),
value: text("value").notNull(),
verified: integer("verified", { mode: "boolean" }).notNull().default(false),
});
@@ -143,7 +143,17 @@ export const resources = sqliteTable("resources", {
}),
headers: text("headers"), // comma-separated list of headers to add to the request
proxyProtocol: integer("proxyProtocol", { mode: "boolean" }).notNull().default(false),
proxyProtocolVersion: integer("proxyProtocolVersion").default(1)
proxyProtocolVersion: integer("proxyProtocolVersion").default(1),
maintenanceModeEnabled: integer("maintenanceModeEnabled", { mode: "boolean" })
.notNull()
.default(false),
maintenanceModeType: text("maintenanceModeType", {
enum: ["forced", "automatic"]
}).default("forced"), // "forced" = always show, "automatic" = only when down
maintenanceTitle: text("maintenanceTitle"),
maintenanceMessage: text("maintenanceMessage"),
maintenanceEstimatedTime: text("maintenanceEstimatedTime"),
});

View File

@@ -0,0 +1,23 @@
import { build } from "@server/build";
import license from "@server/license/license";
import { getOrgTierData } from "#dynamic/lib/billing";
import { TierId } from "./billing/tiers";
export async function isLicensedOrSubscribed(orgId: string): Promise<boolean> {
if (build === "enterprise") {
const isUnlocked = await license.isUnlocked();
if (!isUnlocked) {
return false;
}
}
if (build === "saas") {
const { tier } = await getOrgTierData(orgId);
const subscribed = tier === TierId.STANDARD;
if (!subscribed) {
return false;
}
}
return true;
}

View File

@@ -205,7 +205,9 @@ export const configSchema = z
.default(["newt", "wireguard", "local"]),
allow_raw_resources: z.boolean().optional().default(true),
file_mode: z.boolean().optional().default(false),
pp_transport_prefix: z.string().optional().default("pp-transport-v")
pp_transport_prefix: z.string().optional().default("pp-transport-v"),
maintenance_host: z.string().optional(),
maintenance_port: z.number().optional().default(3002)
})
.optional()
.default({}),

View File

@@ -59,6 +59,7 @@ export async function getTraefikConfig(
headers: resources.headers,
proxyProtocol: resources.proxyProtocol,
proxyProtocolVersion: resources.proxyProtocolVersion,
// Target fields
targetId: targets.targetId,
targetEnabled: targets.enabled,
@@ -184,7 +185,6 @@ export async function getTraefikConfig(
});
}
// Add target with its associated site data
resourcesMap.get(key).targets.push({
resourceId: row.resourceId,
targetId: row.targetId,
@@ -289,12 +289,12 @@ export async function getTraefikConfig(
certResolver: resolverName,
...(preferWildcard
? {
domains: [
{
main: wildCard
}
]
}
domains: [
{
main: wildCard
}
]
}
: {})
};
@@ -535,14 +535,14 @@ export async function getTraefikConfig(
})(),
...(resource.stickySession
? {
sticky: {
cookie: {
name: "p_sticky", // TODO: make this configurable via config.yml like other cookies
secure: resource.ssl,
httpOnly: true
}
}
}
sticky: {
cookie: {
name: "p_sticky", // TODO: make this configurable via config.yml like other cookies
secure: resource.ssl,
httpOnly: true
}
}
}
: {})
}
};
@@ -645,18 +645,18 @@ export async function getTraefikConfig(
})(),
...(resource.proxyProtocol && protocol == "tcp"
? {
serversTransport: `${ppPrefix}${resource.proxyProtocolVersion || 1}@file` // TODO: does @file here cause issues?
}
serversTransport: `${ppPrefix}${resource.proxyProtocolVersion || 1}@file` // TODO: does @file here cause issues?
}
: {}),
...(resource.stickySession
? {
sticky: {
ipStrategy: {
depth: 0,
sourcePort: true
}
}
}
sticky: {
ipStrategy: {
depth: 0,
sourcePort: true
}
}
}
: {})
}
};

View File

@@ -1,4 +1,5 @@
import z from "zod";
import ipaddr from "ipaddr.js";
export function isValidCIDR(cidr: string): boolean {
return z.string().cidr().safeParse(cidr).success;
@@ -68,11 +69,11 @@ 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(
"^(https?:\\/\\/)?" + // protocol
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name
"((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
"(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
"(\\#[-a-z\\d_]*)?$",
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name
"((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
"(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
"(\\#[-a-z\\d_]*)?$",
"i"
);
return !!pattern.test(url);
@@ -83,12 +84,15 @@ export function isTargetValid(value: string | undefined) {
const DOMAIN_REGEX =
/^[a-zA-Z0-9_](?:[a-zA-Z0-9-_]{0,61}[a-zA-Z0-9_])?(?:\.[a-zA-Z0-9_](?:[a-zA-Z0-9-_]{0,61}[a-zA-Z0-9_])?)*$/;
const IPV4_REGEX =
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
const IPV6_REGEX = /^(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}$/i;
// const IPV4_REGEX =
// /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
// const IPV6_REGEX = /^(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}$/i;
if (IPV4_REGEX.test(value) || IPV6_REGEX.test(value)) {
return true;
try {
const addr = ipaddr.parse(value);
return addr.kind() === "ipv4" || addr.kind() === "ipv6";
} catch {
// fall through to domain regex check
}
return DOMAIN_REGEX.test(value);
@@ -169,10 +173,10 @@ export function isSecondLevelDomain(domain: string): boolean {
}
const trimmedDomain = domain.trim().toLowerCase();
// Split into parts
const parts = trimmedDomain.split('.');
// Should have exactly 2 parts for a second-level domain (e.g., "example.com")
if (parts.length !== 2) {
return false;

View File

@@ -87,6 +87,13 @@ export async function getTraefikConfig(
headers: resources.headers,
proxyProtocol: resources.proxyProtocol,
proxyProtocolVersion: resources.proxyProtocolVersion,
maintenanceModeEnabled: resources.maintenanceModeEnabled,
maintenanceModeType: resources.maintenanceModeType,
maintenanceTitle: resources.maintenanceTitle,
maintenanceMessage: resources.maintenanceMessage,
maintenanceEstimatedTime: resources.maintenanceEstimatedTime,
// Target fields
targetId: targets.targetId,
targetEnabled: targets.enabled,
@@ -220,7 +227,13 @@ export async function getTraefikConfig(
rewritePathType: row.rewritePathType,
priority: priority, // may be null, we fallback later
domainCertResolver: row.domainCertResolver,
preferWildcardCert: row.preferWildcardCert
preferWildcardCert: row.preferWildcardCert,
maintenanceModeEnabled: row.maintenanceModeEnabled,
maintenanceModeType: row.maintenanceModeType,
maintenanceTitle: row.maintenanceTitle,
maintenanceMessage: row.maintenanceMessage,
maintenanceEstimatedTime: row.maintenanceEstimatedTime,
});
}
@@ -308,6 +321,115 @@ export async function getTraefikConfig(
config_output.http.services = {};
}
const availableServers = (targets as TargetWithSite[]).filter(
(target: TargetWithSite) => {
if (!target.enabled) return false;
const anySitesOnline = (targets as TargetWithSite[]).some(
(t: TargetWithSite) => t.site.online
);
if (anySitesOnline && !target.site.online) return false;
if (target.site.type === "local" || target.site.type === "wireguard") {
return target.ip && target.port && target.method;
} else if (target.site.type === "newt") {
return target.internalPort && target.method && target.site.subnet;
}
return false;
}
);
const hasHealthyServers = availableServers.length > 0;
let showMaintenancePage = false;
if (resource.maintenanceModeEnabled) {
if (resource.maintenanceModeType === "forced") {
showMaintenancePage = true;
logger.debug(
`Resource ${resource.name} (${fullDomain}) is in FORCED maintenance mode`
);
} else if (resource.maintenanceModeType === "automatic") {
showMaintenancePage = !hasHealthyServers;
if (showMaintenancePage) {
logger.warn(
`Resource ${resource.name} (${fullDomain}) has no healthy servers - showing maintenance page (AUTOMATIC mode)`
);
}
}
}
if (showMaintenancePage) {
const maintenanceServiceName = `${key}-maintenance-service`;
const maintenanceRouterName = `${key}-maintenance-router`;
const rewriteMiddlewareName = `${key}-maintenance-rewrite`;
const entrypointHttp = config.getRawConfig().traefik.http_entrypoint;
const entrypointHttps = config.getRawConfig().traefik.https_entrypoint;
const fullDomain = resource.fullDomain;
const domainParts = fullDomain.split(".");
const wildCard = resource.subdomain
? `*.${domainParts.slice(1).join(".")}`
: fullDomain;
const tls = {
certResolver: resource.domainCertResolver?.trim() ||
config.getRawConfig().traefik.cert_resolver,
...(config.getRawConfig().traefik.prefer_wildcard_cert
? { domains: [{ main: wildCard }] }
: {})
};
const maintenancePort = config.getRawConfig().traefik?.maintenance_port;
const maintenanceHost = config.getRawConfig().traefik?.maintenance_host || 'dev_pangolin';
config_output.http.services[maintenanceServiceName] = {
loadBalancer: {
servers: [{ url: `http://${maintenanceHost}:${maintenancePort}` }],
passHostHeader: true
}
};
// middleware to rewrite path to /maintenance-screen
if (!config_output.http.middlewares) {
config_output.http.middlewares = {};
}
config_output.http.middlewares[rewriteMiddlewareName] = {
replacePathRegex: {
regex: "^/(.*)",
replacement: "/maintenance-screen"
}
};
const rule = `Host(\`${fullDomain}\`)`;
console.log('DEBUG: Generated rule:', rule); // Should show: Host(`pangolin.pallavi.fosrl.io`)
config_output.http.routers[maintenanceRouterName] = {
entryPoints: [resource.ssl ? entrypointHttps : entrypointHttp],
service: maintenanceServiceName,
middlewares: [rewriteMiddlewareName],
rule: rule,
priority: 2000,
...(resource.ssl ? { tls } : {})
};
if (resource.ssl) {
config_output.http.routers[`${maintenanceRouterName}-redirect`] = {
entryPoints: [entrypointHttp],
middlewares: [redirectHttpsMiddlewareName, rewriteMiddlewareName],
service: maintenanceServiceName,
rule: rule,
priority: 2000
};
}
logger.info(`Maintenance mode active for ${fullDomain}`);
continue;
}
const domainParts = fullDomain.split(".");
let wildCard;
if (domainParts.length <= 2) {
@@ -366,12 +488,12 @@ export async function getTraefikConfig(
certResolver: resolverName,
...(preferWildcard
? {
domains: [
{
main: wildCard
}
]
}
domains: [
{
main: wildCard
}
]
}
: {})
};
} else {
@@ -624,14 +746,14 @@ export async function getTraefikConfig(
})(),
...(resource.stickySession
? {
sticky: {
cookie: {
name: "p_sticky", // TODO: make this configurable via config.yml like other cookies
secure: resource.ssl,
httpOnly: true
}
}
}
sticky: {
cookie: {
name: "p_sticky", // TODO: make this configurable via config.yml like other cookies
secure: resource.ssl,
httpOnly: true
}
}
}
: {})
}
};
@@ -734,18 +856,18 @@ export async function getTraefikConfig(
})(),
...(resource.proxyProtocol && protocol == "tcp" // proxy protocol only works for tcp
? {
serversTransport: `${ppPrefix}${resource.proxyProtocolVersion || 1}@file` // TODO: does @file here cause issues?
}
serversTransport: `${ppPrefix}${resource.proxyProtocolVersion || 1}@file` // TODO: does @file here cause issues?
}
: {}),
...(resource.stickySession
? {
sticky: {
ipStrategy: {
depth: 0,
sourcePort: true
}
}
}
sticky: {
ipStrategy: {
depth: 0,
sourcePort: true
}
}
}
: {})
}
};
@@ -793,10 +915,9 @@ export async function getTraefikConfig(
loadBalancer: {
servers: [
{
url: `http://${
config.getRawConfig().server
.internal_hostname
}:${config.getRawConfig().server.next_port}`
url: `http://${config.getRawConfig().server
.internal_hostname
}:${config.getRawConfig().server.next_port}`
}
]
}

View File

@@ -23,11 +23,15 @@ import * as license from "#private/routers/license";
import * as generateLicense from "./generatedLicense";
import * as logs from "#private/routers/auditLogs";
import * as misc from "#private/routers/misc";
import * as reKey from "#private/routers/re-key";
import {
verifyOrgAccess,
verifyUserHasAction,
verifyUserIsServerAdmin
verifyUserIsServerAdmin,
verifySiteAccess,
verifyClientAccess,
verifyClientsEnabled,
} from "@server/middlewares";
import { ActionsEnum } from "@server/auth/actions";
import {
@@ -403,3 +407,26 @@ authenticated.get(
logActionAudit(ActionsEnum.exportLogs),
logs.exportAccessAuditLogs
);
authenticated.post(
"/re-key/:clientId/regenerate-client-secret",
verifyClientsEnabled,
verifyClientAccess,
verifyUserHasAction(ActionsEnum.reGenerateSecret),
reKey.reGenerateClientSecret
);
authenticated.post(
"/re-key/:siteId/regenerate-site-secret",
verifySiteAccess,
verifyUserHasAction(ActionsEnum.reGenerateSecret),
reKey.reGenerateSiteSecret
);
authenticated.put(
"/re-key/:orgId/reGenerate-remote-exit-node-secret",
verifyValidLicense,
verifyOrgAccess,
verifyUserHasAction(ActionsEnum.updateRemoteExitNode),
reKey.reGenerateExitNodeSecret
);

View File

@@ -16,6 +16,7 @@ import * as auth from "#private/routers/auth";
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 { verifySessionUserMiddleware } from "@server/middlewares";
@@ -36,3 +37,5 @@ internalRouter.post(
);
internalRouter.get(`/license/status`, license.getLicenseStatus);
internalRouter.get("/maintenance/info", resource.getMaintenanceInfo);

View File

@@ -68,7 +68,7 @@ export async function sendSupportEmail(
{
name: req.user?.email || "Support User",
to: "support@pangolin.net",
from: req.user?.email || config.getNoReplyEmail(),
from: config.getNoReplyEmail(),
subject: `Support Request: ${subject}`
}
);

View File

@@ -0,0 +1,16 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
export * from "./reGenerateClientSecret";
export * from "./reGenerateSiteSecret";
export * from "./reGenerateExitNodeSecret";

View File

@@ -0,0 +1,143 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db, olms, } from "@server/db";
import { clients } from "@server/db";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { eq, and } from "drizzle-orm";
import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi";
import { hashPassword } from "@server/auth/password";
const reGenerateSecretParamsSchema = z
.object({
clientId: z.string().transform(Number).pipe(z.number().int().positive())
})
.strict();
const reGenerateSecretBodySchema = z
.object({
olmId: z.string().min(1).optional(),
secret: z.string().min(1).optional(),
})
.strict();
export type ReGenerateSecretBody = z.infer<typeof reGenerateSecretBodySchema>;
registry.registerPath({
method: "post",
path: "/re-key/{clientId}/regenerate-client-secret",
description: "Regenerate a client's OLM credentials by its client ID.",
tags: [OpenAPITags.Client],
request: {
params: reGenerateSecretParamsSchema,
body: {
content: {
"application/json": {
schema: reGenerateSecretBodySchema
}
}
}
},
responses: {}
});
export async function reGenerateClientSecret(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedBody = reGenerateSecretBodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { olmId, secret } = parsedBody.data;
const parsedParams = reGenerateSecretParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { clientId } = parsedParams.data;
let secretHash = undefined;
if (secret) {
secretHash = await hashPassword(secret);
}
// Fetch the client to make sure it exists and the user has access to it
const [client] = await db
.select()
.from(clients)
.where(eq(clients.clientId, clientId))
.limit(1);
if (!client) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Client with ID ${clientId} not found`
)
);
}
const [existingOlm] = await db
.select()
.from(olms)
.where(eq(olms.clientId, clientId))
.limit(1);
if (existingOlm && olmId && secretHash) {
await db
.update(olms)
.set({
olmId,
secretHash
})
.where(eq(olms.clientId, clientId));
}
return response(res, {
data: existingOlm,
success: true,
error: false,
message: "Credentials regenerated successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View File

@@ -0,0 +1,129 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 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 { NextFunction, Request, Response } from "express";
import { db, exitNodes, exitNodeOrgs, ExitNode, ExitNodeOrg } from "@server/db";
import HttpCode from "@server/types/HttpCode";
import { z } from "zod";
import { remoteExitNodes } from "@server/db";
import createHttpError from "http-errors";
import response from "@server/lib/response";
import { fromError } from "zod-validation-error";
import { hashPassword } from "@server/auth/password";
import logger from "@server/logger";
import { and, eq } from "drizzle-orm";
import { UpdateRemoteExitNodeResponse } from "@server/routers/remoteExitNode/types";
import { OpenAPITags, registry } from "@server/openApi";
export const paramsSchema = z.object({
orgId: z.string()
});
const bodySchema = z
.object({
remoteExitNodeId: z.string().length(15),
secret: z.string().length(48)
})
.strict();
registry.registerPath({
method: "post",
path: "/re-key/{orgId}/regenerate-secret",
description: "Regenerate a exit node credentials by its org ID.",
tags: [OpenAPITags.Org],
request: {
params: paramsSchema,
body: {
content: {
"application/json": {
schema: bodySchema
}
}
}
},
responses: {}
});
export async function reGenerateExitNodeSecret(
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 parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { remoteExitNodeId, secret } = parsedBody.data;
if (req.user && !req.userOrgRoleId) {
return next(
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
);
}
const [existingRemoteExitNode] = await db
.select()
.from(remoteExitNodes)
.where(eq(remoteExitNodes.remoteExitNodeId, remoteExitNodeId));
if (!existingRemoteExitNode) {
return next(
createHttpError(HttpCode.NOT_FOUND, "Remote Exit Node does not exist")
);
}
const secretHash = await hashPassword(secret);
await db
.update(remoteExitNodes)
.set({ secretHash })
.where(eq(remoteExitNodes.remoteExitNodeId, remoteExitNodeId));
return response<UpdateRemoteExitNodeResponse>(res, {
data: {
remoteExitNodeId,
secret,
},
success: true,
error: false,
message: "Remote Exit Node secret updated successfully",
status: HttpCode.OK,
});
} catch (e) {
logger.error("Failed to update remoteExitNode", e);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to update remoteExitNode"
)
);
}
}

View File

@@ -0,0 +1,168 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db, newts, sites } from "@server/db";
import { eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi";
import { hashPassword } from "@server/auth/password";
import { addPeer } from "@server/routers/gerbil/peers";
const updateSiteParamsSchema = z
.object({
siteId: z.string().transform(Number).pipe(z.number().int().positive())
})
.strict();
const updateSiteBodySchema = z
.object({
type: z.enum(["newt", "wireguard"]),
newtId: z.string().min(1).max(255).optional(),
newtSecret: z.string().min(1).max(255).optional(),
exitNodeId: z.number().int().positive().optional(),
pubKey: z.string().optional(),
subnet: z.string().optional(),
})
.strict();
registry.registerPath({
method: "post",
path: "/re-key/{siteId}/regenerate-site-secret",
description: "Regenerate a site's Newt or WireGuard credentials by its site ID.",
tags: [OpenAPITags.Site],
request: {
params: updateSiteParamsSchema,
body: {
content: {
"application/json": {
schema: updateSiteBodySchema,
},
},
},
},
responses: {},
});
export async function reGenerateSiteSecret(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = updateSiteParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(HttpCode.BAD_REQUEST, fromError(parsedParams.error).toString())
);
}
const parsedBody = updateSiteBodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(HttpCode.BAD_REQUEST, fromError(parsedBody.error).toString())
);
}
const { siteId } = parsedParams.data;
const { type, exitNodeId, pubKey, subnet, newtId, newtSecret } = parsedBody.data;
let updatedSite = undefined;
if (type === "newt") {
if (!newtSecret) {
return next(
createHttpError(HttpCode.BAD_REQUEST, "newtSecret is required for newt sites")
);
}
const secretHash = await hashPassword(newtSecret);
updatedSite = await db
.update(newts)
.set({
newtId,
secretHash,
})
.where(eq(newts.siteId, siteId))
.returning();
logger.info(`Regenerated Newt credentials for site ${siteId}`);
} else if (type === "wireguard") {
if (!pubKey) {
return next(
createHttpError(HttpCode.BAD_REQUEST, "Public key is required for wireguard sites")
);
}
if (!exitNodeId) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Exit node ID is required for wireguard sites"
)
);
}
try {
updatedSite = await db.transaction(async (tx) => {
await addPeer(exitNodeId, {
publicKey: pubKey,
allowedIps: subnet ? [subnet] : [],
});
const result = await tx
.update(sites)
.set({ pubKey })
.where(eq(sites.siteId, siteId))
.returning();
return result;
});
logger.info(`Regenerated WireGuard credentials for site ${siteId}`);
} catch (err) {
logger.error(
`Transaction failed while regenerating WireGuard secret for site ${siteId}`,
err
);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to regenerate WireGuard credentials. Rolled back transaction."
)
);
}
}
return response(res, {
data: updatedSite,
success: true,
error: false,
message: "Credentials regenerated successfully",
status: HttpCode.OK,
});
} catch (error) {
logger.error("Unexpected error in reGenerateSiteSecret", error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An unexpected error occurred")
);
}
}

View File

@@ -0,0 +1,113 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { resources } from "@server/db";
import { eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import { fromError } from "zod-validation-error";
import logger from "@server/logger";
import { OpenAPITags, registry } from "@server/openApi";
import { GetMaintenanceInfoResponse } from "@server/routers/resource/types";
const getMaintenanceInfoSchema = z
.object({
fullDomain: z.string().min(1, "Domain is required")
})
.strict();
async function query(fullDomain: string) {
const [res] = await db
.select({
resourceId: resources.resourceId,
name: resources.name,
fullDomain: resources.fullDomain,
maintenanceModeEnabled: resources.maintenanceModeEnabled,
maintenanceModeType: resources.maintenanceModeType,
maintenanceTitle: resources.maintenanceTitle,
maintenanceMessage: resources.maintenanceMessage,
maintenanceEstimatedTime: resources.maintenanceEstimatedTime
})
.from(resources)
.where(eq(resources.fullDomain, fullDomain))
.limit(1);
return res;
}
registry.registerPath({
method: "get",
path: "/maintenance/info",
description: "Get maintenance information for a resource by domain.",
tags: [OpenAPITags.Resource],
request: {
query: z.object({
fullDomain: z.string()
})
},
responses: {
200: {
description: "Maintenance information retrieved successfully"
},
404: {
description: "Resource not found"
}
}
});
export async function getMaintenanceInfo(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedQuery = getMaintenanceInfoSchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedQuery.error).toString()
)
);
}
const { fullDomain } = parsedQuery.data;
const maintenanceInfo = await query(fullDomain);
if (!maintenanceInfo) {
return next(
createHttpError(HttpCode.NOT_FOUND, "Resource not found")
);
}
return response<GetMaintenanceInfoResponse>(res, {
data: maintenanceInfo,
success: true,
error: false,
message: "Maintenance information retrieved successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"An error occurred while retrieving maintenance information"
)
);
}
}

View File

@@ -0,0 +1,14 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
export * from "./getMaintenanceInfo";

View File

@@ -60,6 +60,7 @@ type BasicUserData = {
username: string;
email: string | null;
name: string | null;
role: string | null;
};
export type VerifyUserResponse = {
@@ -883,7 +884,8 @@ async function isUserAllowedToAccessResource(
return {
username: user.username,
email: user.email,
name: user.name
name: user.name,
role: user.role
};
}
@@ -896,7 +898,8 @@ async function isUserAllowedToAccessResource(
return {
username: user.username,
email: user.email,
name: user.name
name: user.name,
role: user.role
};
}

View File

@@ -1,6 +1,6 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { Client, db, exitNodes, sites } from "@server/db";
import { Client, db, exitNodes, olms, sites } from "@server/db";
import { clients, clientSites } from "@server/db";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
@@ -18,6 +18,7 @@ import {
deletePeer as olmDeletePeer
} from "../olm/peers";
import { sendToExitNode } from "#dynamic/lib/exitNodes";
import { hashPassword } from "@server/auth/password";
const updateClientParamsSchema = z
.object({
@@ -30,7 +31,7 @@ const updateClientSchema = z
name: z.string().min(1).max(255).optional(),
siteIds: z
.array(z.number().int().positive())
.optional()
.optional(),
})
.strict();
@@ -89,6 +90,7 @@ export async function updateClient(
const { clientId } = parsedParams.data;
// Fetch the client to make sure it exists and the user has access to it
const [client] = await db
.select()

View File

@@ -47,7 +47,6 @@ import createHttpError from "http-errors";
import { build } from "@server/build";
import { createStore } from "#dynamic/lib/rateLimitStore";
import { logActionAudit } from "#dynamic/middlewares";
import { log } from "console";
// Root routes
export const unauthenticated = Router();
@@ -178,6 +177,7 @@ authenticated.post(
client.updateClient,
);
// authenticated.get(
// "/site/:siteId/roles",
// verifySiteAccess,
@@ -191,6 +191,7 @@ authenticated.post(
logActionAudit(ActionsEnum.updateSite),
site.updateSite,
);
authenticated.delete(
"/site/:siteId",
verifySiteAccess,

View File

@@ -10,10 +10,10 @@ import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi";
import { build } from "@server/build";
import license from "#dynamic/license/license";
import { getOrgTierData } from "#dynamic/lib/billing";
import { TierId } from "@server/lib/billing/tiers";
import { cache } from "@server/lib/cache";
import { isLicensedOrSubscribed } from "@server/lib/isLicencedOrSubscribed";
const updateOrgParamsSchema = z
.object({
@@ -157,23 +157,4 @@ export async function updateOrg(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}
async function isLicensedOrSubscribed(orgId: string): Promise<boolean> {
if (build === "enterprise") {
const isUnlocked = await license.isUnlocked();
if (!isUnlocked) {
return false;
}
}
if (build === "saas") {
const { tier } = await getOrgTierData(orgId);
const subscribed = tier === TierId.STANDARD;
if (!subscribed) {
return false;
}
}
return true;
}
}

View File

@@ -6,6 +6,11 @@ export type CreateRemoteExitNodeResponse = {
secret: string;
};
export type UpdateRemoteExitNodeResponse = {
remoteExitNodeId: string;
secret: string;
}
export type PickRemoteExitNodeDefaultsResponse = {
remoteExitNodeId: string;
secret: string;

View File

@@ -24,4 +24,4 @@ export * from "./updateResourceRule";
export * from "./getUserResources";
export * from "./setResourceHeaderAuth";
export * from "./addEmailToResourceWhitelist";
export * from "./removeEmailFromResourceWhitelist";
export * from "./removeEmailFromResourceWhitelist";

View File

@@ -0,0 +1,10 @@
export type GetMaintenanceInfoResponse = {
resourceId: number;
name: string;
fullDomain: string | null;
maintenanceModeEnabled: boolean;
maintenanceModeType: "forced" | "automatic" | null;
maintenanceTitle: string | null;
maintenanceMessage: string | null;
maintenanceEstimatedTime: string | null;
}

View File

@@ -22,8 +22,8 @@ import { registry } from "@server/openApi";
import { OpenAPITags } from "@server/openApi";
import { createCertificate } from "#dynamic/routers/certificates/createCertificate";
import { validateAndConstructDomain } from "@server/lib/domainUtils";
import { validateHeaders } from "@server/lib/validators";
import { build } from "@server/build";
import { isLicensedOrSubscribed } from "@server/lib/isLicencedOrSubscribed";
const updateResourceParamsSchema = z
.object({
@@ -37,6 +37,7 @@ const updateResourceParamsSchema = z
const updateHttpResourceBodySchema = z
.object({
name: z.string().min(1).max(255).optional(),
niceId: z.string().min(1).max(255).optional(),
subdomain: subdomainSchema.nullable().optional(),
ssl: z.boolean().optional(),
sso: z.boolean().optional(),
@@ -52,7 +53,13 @@ const updateHttpResourceBodySchema = z
headers: z
.array(z.object({ name: z.string(), value: z.string() }))
.nullable()
.optional()
.optional(),
// Maintenance mode fields
maintenanceModeEnabled: z.boolean().optional(),
maintenanceModeType: z.enum(["forced", "automatic"]).optional(),
maintenanceTitle: z.string().max(255).nullable().optional(),
maintenanceMessage: z.string().max(2000).nullable().optional(),
maintenanceEstimatedTime: z.string().max(100).nullable().optional()
})
.strict()
.refine((data) => Object.keys(data).length > 0, {
@@ -97,6 +104,7 @@ export type UpdateResourceResponse = Resource;
const updateRawResourceBodySchema = z
.object({
name: z.string().min(1).max(255).optional(),
niceId: z.string().min(1).max(255).optional(),
proxyPort: z.number().int().min(1).max(65535).optional(),
stickySession: z.boolean().optional(),
enabled: z.boolean().optional(),
@@ -236,6 +244,30 @@ async function updateHttpResource(
const updateData = parsedBody.data;
if (updateData.niceId) {
const [existingResource] = await db
.select()
.from(resources)
.where(
and(
eq(resources.niceId, updateData.niceId),
eq(resources.orgId, resource.orgId)
)
);
if (
existingResource &&
existingResource.resourceId !== resource.resourceId
) {
return next(
createHttpError(
HttpCode.CONFLICT,
`A resource with niceId "${updateData.niceId}" already exists`
)
);
}
}
if (updateData.domainId) {
const domainId = updateData.domainId;
@@ -312,6 +344,16 @@ async function updateHttpResource(
headers = JSON.stringify(updateData.headers);
}
const isLicensed = await isLicensedOrSubscribed(resource.orgId);
if (build == "enterprise" && !isLicensed) {
// null the maintenance mode fields if not licensed
updateData.maintenanceModeEnabled = undefined;
updateData.maintenanceModeType = undefined;
updateData.maintenanceTitle = undefined;
updateData.maintenanceMessage = undefined;
updateData.maintenanceEstimatedTime = undefined;
}
const updatedResource = await db
.update(resources)
.set({ ...updateData, headers })
@@ -362,6 +404,30 @@ async function updateRawResource(
const updateData = parsedBody.data;
if (updateData.niceId) {
const [existingResource] = await db
.select()
.from(resources)
.where(
and(
eq(resources.niceId, updateData.niceId),
eq(resources.orgId, resource.orgId)
)
);
if (
existingResource &&
existingResource.resourceId !== resource.resourceId
) {
return next(
createHttpError(
HttpCode.CONFLICT,
`A resource with niceId "${updateData.niceId}" already exists`
)
);
}
}
const updatedResource = await db
.update(resources)
.set(updateData)

View File

@@ -5,4 +5,4 @@ export * from "./updateSite";
export * from "./listSites";
export * from "./listSiteRoles";
export * from "./pickSiteDefaults";
export * from "./socketIntegration";
export * from "./socketIntegration";

View File

@@ -2,7 +2,7 @@ import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { sites } from "@server/db";
import { eq } from "drizzle-orm";
import { eq, and } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
@@ -20,6 +20,7 @@ const updateSiteParamsSchema = z
const updateSiteBodySchema = z
.object({
name: z.string().min(1).max(255).optional(),
niceId: z.string().min(1).max(255).optional(),
dockerSocketEnabled: z.boolean().optional(),
remoteSubnets: z
.string()
@@ -89,6 +90,29 @@ export async function updateSite(
const { siteId } = parsedParams.data;
const updateData = parsedBody.data;
// if niceId is provided, check if it's already in use by another site
if (updateData.niceId) {
const existingSite = await db
.select()
.from(sites)
.where(
and(
eq(sites.niceId, updateData.niceId),
eq(sites.orgId, sites.orgId)
)
)
.limit(1);
if (existingSite.length > 0 && existingSite[0].siteId !== siteId) {
return next(
createHttpError(
HttpCode.CONFLICT,
`A site with niceId "${updateData.niceId}" already exists`
)
);
}
}
// if remoteSubnets is provided, ensure it's a valid comma-separated list of cidrs
if (updateData.remoteSubnets) {
const subnets = updateData.remoteSubnets.split(",").map((s) => s.trim());

View File

@@ -232,6 +232,7 @@ export default function ExitNodesTable({
id: "actions",
cell: ({ row }) => {
const nodeRow = row.original;
const remoteExitNodeId = nodeRow.id;
return (
<div className="flex items-center justify-end gap-2">
<DropdownMenu>
@@ -242,6 +243,14 @@ export default function ExitNodesTable({
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<Link
className="block w-full"
href={`/${nodeRow.orgId}/settings/remote-exit-nodes/${remoteExitNodeId}`}
>
<DropdownMenuItem>
{t("viewSettings")}
</DropdownMenuItem>
</Link>
<DropdownMenuItem
onClick={() => {
setSelectedNode(nodeRow);
@@ -254,6 +263,14 @@ export default function ExitNodesTable({
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Link
href={`/${nodeRow.orgId}/settings/remote-exit-nodes/${remoteExitNodeId}`}
>
<Button variant={"secondary"} size="sm">
{t("edit")}
<ArrowRight className="ml-2 w-4 h-4" />
</Button>
</Link>
</div>
);
}

View File

@@ -0,0 +1,133 @@
"use client";
import { useState } from "react";
import {
SettingsContainer,
SettingsSection,
SettingsSectionBody,
SettingsSectionDescription,
SettingsSectionHeader,
SettingsSectionTitle
} from "@app/components/Settings";
import { Button } from "@app/components/ui/button";
import { createApiClient, formatAxiosError } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { toast } from "@app/hooks/useToast";
import { useParams, useRouter } from "next/navigation";
import { AxiosResponse } from "axios";
import { useTranslations } from "next-intl";
import {
PickRemoteExitNodeDefaultsResponse,
QuickStartRemoteExitNodeResponse
} from "@server/routers/remoteExitNode/types";
import { useRemoteExitNodeContext } from "@app/hooks/useRemoteExitNodeContext";
import RegenerateCredentialsModal from "@app/components/RegenerateCredentialsModal";
import { useSubscriptionStatusContext } from "@app/hooks/useSubscriptionStatusContext";
import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext";
import { build } from "@server/build";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@app/components/ui/tooltip";
export default function CredentialsPage() {
const { env } = useEnvContext();
const api = createApiClient({ env });
const { orgId } = useParams();
const router = useRouter();
const t = useTranslations();
const { remoteExitNode } = useRemoteExitNodeContext();
const [modalOpen, setModalOpen] = useState(false);
const [credentials, setCredentials] = useState<PickRemoteExitNodeDefaultsResponse | null>(null);
const { licenseStatus, isUnlocked } = useLicenseStatusContext();
const subscription = useSubscriptionStatusContext();
const isSecurityFeatureDisabled = () => {
const isEnterpriseNotLicensed = build === "enterprise" && !isUnlocked();
const isSaasNotSubscribed =
build === "saas" && !subscription?.isSubscribed();
return isEnterpriseNotLicensed || isSaasNotSubscribed;
};
const handleConfirmRegenerate = async () => {
const response = await api.get<AxiosResponse<PickRemoteExitNodeDefaultsResponse>>(
`/org/${orgId}/pick-remote-exit-node-defaults`
);
const data = response.data.data;
setCredentials(data);
await api.put<AxiosResponse<QuickStartRemoteExitNodeResponse>>(
`/re-key/${orgId}/reGenerate-remote-exit-node-secret`,
{
remoteExitNodeId: remoteExitNode.remoteExitNodeId,
secret: data.secret,
}
);
toast({
title: t("credentialsSaved"),
description: t("credentialsSavedDescription")
});
router.refresh();
};
const getCredentials = () => {
if (credentials) {
return {
Id: remoteExitNode.remoteExitNodeId,
Secret: credentials.secret
};
}
return undefined;
};
return (
<SettingsContainer>
<SettingsSection>
<SettingsSectionHeader>
<SettingsSectionTitle>
{t("generatedcredentials")}
</SettingsSectionTitle>
<SettingsSectionDescription>
{t("regenerateCredentials")}
</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsSectionBody>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="inline-block">
<Button
onClick={() => setModalOpen(true)}
disabled={isSecurityFeatureDisabled()}
>
{t("regeneratecredentials")}
</Button>
</div>
</TooltipTrigger>
{isSecurityFeatureDisabled() && (
<TooltipContent side="top">
{t("featureDisabledTooltip")}
</TooltipContent>
)}
</Tooltip>
</TooltipProvider>
</SettingsSectionBody>
</SettingsSection>
<RegenerateCredentialsModal
open={modalOpen}
onOpenChange={setModalOpen}
type="remote-exit-node"
onConfirmRegenerate={handleConfirmRegenerate}
dashboardUrl={env.app.dashboardUrl}
credentials={getCredentials()}
/>
</SettingsContainer>
);
}

View File

@@ -1,3 +0,0 @@
export default function GeneralPage() {
return <></>;
}

View File

@@ -6,6 +6,8 @@ import { authCookieHeader } from "@app/lib/api/cookies";
import SettingsSectionTitle from "@app/components/SettingsSectionTitle";
import { getTranslations } from "next-intl/server";
import RemoteExitNodeProvider from "@app/providers/RemoteExitNodeProvider";
import { HorizontalTabs } from "@app/components/HorizontalTabs";
import ExitNodeInfoCard from "@app/components/ExitNodeInfoCard";
interface SettingsLayoutProps {
children: React.ReactNode;
@@ -31,6 +33,13 @@ export default async function SettingsLayout(props: SettingsLayoutProps) {
const t = await getTranslations();
const navItems = [
{
title: t('credentials'),
href: "/{orgId}/settings/remote-exit-nodes/{remoteExitNodeId}/credentials"
}
];
return (
<>
<SettingsSectionTitle
@@ -39,7 +48,10 @@ export default async function SettingsLayout(props: SettingsLayoutProps) {
/>
<RemoteExitNodeProvider remoteExitNode={remoteExitNode}>
<div className="space-y-6">{children}</div>
<div className="space-y-6">
<ExitNodeInfoCard />
<HorizontalTabs items={navItems}>{children}</HorizontalTabs>
</div>
</RemoteExitNodeProvider>
</>
);

View File

@@ -5,6 +5,6 @@ export default async function RemoteExitNodePage(props: {
}) {
const params = await props.params;
redirect(
`/${params.orgId}/settings/remote-exit-nodes/${params.remoteExitNodeId}/general`
`/${params.orgId}/settings/remote-exit-nodes/${params.remoteExitNodeId}/credentials`
);
}

View File

@@ -0,0 +1,124 @@
"use client";
import { useState } from "react";
import {
SettingsContainer,
SettingsSection,
SettingsSectionBody,
SettingsSectionDescription,
SettingsSectionHeader,
SettingsSectionTitle
} from "@app/components/Settings";
import { Button } from "@app/components/ui/button";
import { createApiClient, formatAxiosError } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { toast } from "@app/hooks/useToast";
import { useParams, useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { PickClientDefaultsResponse } from "@server/routers/client";
import { useClientContext } from "@app/hooks/useClientContext";
import RegenerateCredentialsModal from "@app/components/RegenerateCredentialsModal";
import { build } from "@server/build";
import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext";
import { useSubscriptionStatusContext } from "@app/hooks/useSubscriptionStatusContext";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@app/components/ui/tooltip";
export default function CredentialsPage() {
const { env } = useEnvContext();
const api = createApiClient({ env });
const { orgId } = useParams();
const router = useRouter();
const t = useTranslations();
const { client } = useClientContext();
const [modalOpen, setModalOpen] = useState(false);
const [clientDefaults, setClientDefaults] = useState<PickClientDefaultsResponse | null>(null);
const { licenseStatus, isUnlocked } = useLicenseStatusContext();
const subscription = useSubscriptionStatusContext();
const isSecurityFeatureDisabled = () => {
const isEnterpriseNotLicensed = build === "enterprise" && !isUnlocked();
const isSaasNotSubscribed =
build === "saas" && !subscription?.isSubscribed();
return isEnterpriseNotLicensed || isSaasNotSubscribed;
};
const handleConfirmRegenerate = async () => {
const res = await api.get(`/org/${orgId}/pick-client-defaults`);
if (res && res.status === 200) {
const data = res.data.data;
setClientDefaults(data);
await api.post(`/re-key/${client?.clientId}/regenerate-client-secret`, {
olmId: data.olmId,
secret: data.olmSecret,
});
toast({
title: t("credentialsSaved"),
description: t("credentialsSavedDescription")
});
router.refresh();
}
};
const getCredentials = () => {
if (clientDefaults) {
return {
Id: clientDefaults.olmId,
Secret: clientDefaults.olmSecret
};
}
return undefined;
};
return (
<SettingsContainer>
<SettingsSection>
<SettingsSectionHeader>
<SettingsSectionTitle>
{t("generatedcredentials")}
</SettingsSectionTitle>
<SettingsSectionDescription>
{t("regenerateCredentials")}
</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsSectionBody>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="inline-block">
<Button
onClick={() => setModalOpen(true)}
disabled={isSecurityFeatureDisabled()}>
{t("regeneratecredentials")}
</Button>
</div>
</TooltipTrigger>
{isSecurityFeatureDisabled() && (
<TooltipContent side="top">
{t("featureDisabledTooltip")}
</TooltipContent>
)}
</Tooltip>
</TooltipProvider>
</SettingsSectionBody>
</SettingsSection>
<RegenerateCredentialsModal
open={modalOpen}
onOpenChange={setModalOpen}
type="client-olm"
onConfirmRegenerate={handleConfirmRegenerate}
dashboardUrl={env.app.dashboardUrl}
credentials={getCredentials()}
/>
</SettingsContainer>
);
}

View File

@@ -7,6 +7,8 @@ import ClientInfoCard from "../../../../../components/ClientInfoCard";
import ClientProvider from "@app/providers/ClientProvider";
import { redirect } from "next/navigation";
import { HorizontalTabs } from "@app/components/HorizontalTabs";
import { getTranslations } from "next-intl/server";
import { build } from "@server/build";
type SettingsLayoutProps = {
children: React.ReactNode;
@@ -30,11 +32,20 @@ export default async function SettingsLayout(props: SettingsLayoutProps) {
redirect(`/${params.orgId}/settings/clients`);
}
const t = await getTranslations();
const navItems = [
{
title: "General",
title: t('general'),
href: `/{orgId}/settings/clients/{clientId}/general`
}
},
...(build === 'enterprise'
? [{
title: t('credentials'),
href: `/{orgId}/settings/clients/{clientId}/credentials`
},
]
: []),
];
return (

View File

@@ -50,7 +50,7 @@ import { useUserContext } from "@app/hooks/useUserContext";
import { useTranslations } from "next-intl";
import { build } from "@server/build";
import { SwitchInput } from "@app/components/SwitchInput";
import { SecurityFeaturesAlert } from "@app/components/SecurityFeaturesAlert";
import { LicenseOrSubscriptionRequiredAlert } from "@app/components/SecurityFeaturesAlert";
import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext";
import { useSubscriptionStatusContext } from "@app/hooks/useSubscriptionStatusContext";
@@ -440,7 +440,7 @@ export default function GeneralPage() {
{build != "oss" && (
<>
<SecurityFeaturesAlert />
<LicenseOrSubscriptionRequiredAlert />
<FormField
control={form.control}
@@ -600,7 +600,7 @@ export default function GeneralPage() {
</SettingsSectionHeader>
<SettingsSectionBody>
<SettingsSectionForm>
<SecurityFeaturesAlert />
<LicenseOrSubscriptionRequiredAlert />
<FormField
control={form.control}
name="requireTwoFactor"

View File

@@ -14,6 +14,7 @@ import {
FormMessage
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { useResourceContext } from "@app/hooks/useResourceContext";
import { ListSitesResponse } from "@server/routers/site";
import { useEffect, useState } from "react";
@@ -39,7 +40,6 @@ import { ListDomainsResponse } from "@server/routers/domain";
import { UpdateResourceResponse } from "@server/routers/resource";
import { SwitchInput } from "@app/components/SwitchInput";
import { useTranslations } from "next-intl";
import { Checkbox } from "@app/components/ui/checkbox";
import {
Credenza,
CredenzaBody,
@@ -51,7 +51,7 @@ import {
CredenzaTitle
} from "@app/components/Credenza";
import DomainPicker from "@app/components/DomainPicker";
import { Globe } from "lucide-react";
import { AlertCircle, Globe, Info } from "lucide-react";
import { build } from "@server/build";
import { finalizeSubdomainSanitize } from "@app/lib/subdomain-utils";
import { DomainRow } from "../../../../../../components/DomainsTable";
@@ -59,6 +59,15 @@ import { toASCII, toUnicode } from "punycode";
import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext";
import { useSubscriptionStatusContext } from "@app/hooks/useSubscriptionStatusContext";
import { useUserContext } from "@app/hooks/useUserContext";
import { Alert, AlertDescription } from "@app/components/ui/alert";
import { RadioGroup, RadioGroupItem } from "@app/components/ui/radio-group";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger
} from "@app/components/ui/tooltip";
import { LicenseOrSubscriptionRequiredAlert } from "@app/components/SecurityFeaturesAlert";
export default function GeneralForm() {
const [formKey, setFormKey] = useState(0);
@@ -68,9 +77,10 @@ export default function GeneralForm() {
const router = useRouter();
const t = useTranslations();
const [editDomainOpen, setEditDomainOpen] = useState(false);
const {licenseStatus } = useLicenseStatusContext();
const subscriptionStatus = useSubscriptionStatusContext();
const {user} = useUserContext();
const { licenseStatus, isUnlocked } = useLicenseStatusContext();
const subscription = useSubscriptionStatusContext();
const { user } = useUserContext();
const { env } = useEnvContext();
@@ -97,14 +107,28 @@ export default function GeneralForm() {
baseDomain: string;
} | null>(null);
// Check if security features are disabled due to licensing/subscription
const isSecurityFeatureDisabled = () => {
const isEnterpriseNotLicensed = build === "enterprise" && !isUnlocked();
const isSaasNotSubscribed =
build === "saas" && !subscription?.isSubscribed();
return isEnterpriseNotLicensed || isSaasNotSubscribed;
};
const GeneralFormSchema = z
.object({
enabled: z.boolean(),
subdomain: z.string().optional(),
name: z.string().min(1).max(255),
niceId: z.string().min(1).max(255).optional(),
domainId: z.string().optional(),
proxyPort: z.number().int().min(1).max(65535).optional(),
// enableProxy: z.boolean().optional()
maintenanceModeEnabled: z.boolean().optional(),
maintenanceModeType: z.enum(["forced", "automatic"]).optional(),
maintenanceTitle: z.string().max(255).optional(),
maintenanceMessage: z.string().max(2000).optional(),
maintenanceEstimatedTime: z.string().max(100).optional()
})
.refine(
(data) => {
@@ -130,14 +154,26 @@ export default function GeneralForm() {
defaultValues: {
enabled: resource.enabled,
name: resource.name,
niceId: resource.niceId,
subdomain: resource.subdomain ? resource.subdomain : undefined,
domainId: resource.domainId || undefined,
proxyPort: resource.proxyPort || undefined,
// enableProxy: resource.enableProxy || false
maintenanceModeEnabled: resource.maintenanceModeEnabled || false,
maintenanceModeType: resource.maintenanceModeType || "automatic",
maintenanceTitle:
resource.maintenanceTitle || "We'll be back soon!",
maintenanceMessage:
resource.maintenanceMessage ||
"We are currently performing scheduled maintenance. Please check back soon.",
maintenanceEstimatedTime: resource.maintenanceEstimatedTime || ""
},
mode: "onChange"
});
const isMaintenanceEnabled = form.watch("maintenanceModeEnabled");
const maintenanceModeType = form.watch("maintenanceModeType");
useEffect(() => {
const fetchSites = async () => {
const res = await api.get<AxiosResponse<ListSitesResponse>>(
@@ -166,7 +202,7 @@ export default function GeneralForm() {
const rawDomains = res.data.data.domains as DomainRow[];
const domains = rawDomains.map((domain) => ({
...domain,
baseDomain: toUnicode(domain.baseDomain),
baseDomain: toUnicode(domain.baseDomain)
}));
setBaseDomains(domains);
setFormKey((key) => key + 1);
@@ -192,12 +228,21 @@ export default function GeneralForm() {
{
enabled: data.enabled,
name: data.name,
subdomain: data.subdomain ? toASCII(data.subdomain) : undefined,
niceId: data.niceId,
subdomain: data.subdomain
? toASCII(data.subdomain)
: undefined,
domainId: data.domainId,
proxyPort: data.proxyPort,
// ...(!resource.http && {
// enableProxy: data.enableProxy
// })
maintenanceModeEnabled: data.maintenanceModeEnabled,
maintenanceModeType: data.maintenanceModeType,
maintenanceTitle: data.maintenanceTitle || null,
maintenanceMessage: data.maintenanceMessage || null,
maintenanceEstimatedTime:
data.maintenanceEstimatedTime || null
}
)
.catch((e) => {
@@ -212,26 +257,41 @@ export default function GeneralForm() {
});
if (res && res.status === 200) {
toast({
title: t("resourceUpdated"),
description: t("resourceUpdatedDescription")
});
const resource = res.data.data;
const updated = res.data.data;
updateResource({
enabled: data.enabled,
name: data.name,
niceId: data.niceId,
subdomain: data.subdomain,
fullDomain: resource.fullDomain,
proxyPort: data.proxyPort,
// ...(!resource.http && {
// enableProxy: data.enableProxy
// })
maintenanceModeEnabled: data.maintenanceModeEnabled,
maintenanceModeType: data.maintenanceModeType,
maintenanceTitle: data.maintenanceTitle || null,
maintenanceMessage: data.maintenanceMessage || null,
maintenanceEstimatedTime: data.maintenanceEstimatedTime || null
});
router.refresh();
toast({
title: t("resourceUpdated"),
description: t("resourceUpdatedDescription")
});
if (data.niceId && data.niceId !== resource?.niceId) {
router.replace(
`/${updated.orgId}/settings/resources/${data.niceId}/general`
);
} else {
router.refresh();
}
setSaveLoading(false);
}
setSaveLoading(false);
}
@@ -304,6 +364,28 @@ export default function GeneralForm() {
)}
/>
<FormField
control={form.control}
name="niceId"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("identifier")}
</FormLabel>
<FormControl>
<Input
{...field}
placeholder={t(
"enterIdentifier"
)}
className="flex-1"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{!resource.http && (
<>
<FormField
@@ -331,10 +413,10 @@ export default function GeneralForm() {
.target
.value
? parseInt(
e
.target
.value
)
e
.target
.value
)
: undefined
)
}
@@ -389,62 +471,326 @@ export default function GeneralForm() {
)}
{resource.http && (
<div className="space-y-2">
<Label>
{t("resourceDomain")}
</Label>
<div className="border p-2 rounded-md flex items-center justify-between">
<span className="text-sm text-muted-foreground flex items-center gap-2">
<Globe size="14" />
{resourceFullDomain}
</span>
<Button
variant="secondary"
type="button"
size="sm"
onClick={() =>
setEditDomainOpen(
true
)
}
>
{t(
"resourceEditDomain"
)}
</Button>
<>
<div className="space-y-2">
<Label>
{t("resourceDomain")}
</Label>
<div className="border p-2 rounded-md flex items-center justify-between">
<span className="text-sm text-muted-foreground flex items-center gap-2">
<Globe size="14" />
{resourceFullDomain}
</span>
<Button
variant="secondary"
type="button"
size="sm"
onClick={() =>
setEditDomainOpen(
true
)
}
>
{t(
"resourceEditDomain"
)}
</Button>
</div>
</div>
</div>
</>
)}
</form>
</Form>
</SettingsSectionForm>
</SettingsSectionBody>
<SettingsSectionFooter>
<Button
type="submit"
onClick={() => {
console.log(form.getValues());
}}
loading={saveLoading}
disabled={saveLoading}
form="general-settings-form"
>
{t("saveSettings")}
</Button>
</SettingsSectionFooter>
</SettingsSection>
</SettingsContainer>
{build !== "oss" && resource.http && (
<SettingsContainer>
<SettingsSection>
<SettingsSectionHeader>
<SettingsSectionTitle>
{t("maintenanceMode")}
</SettingsSectionTitle>
<SettingsSectionDescription>
{t("maintenanceModeDescription")}
</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsSectionBody>
<LicenseOrSubscriptionRequiredAlert />
<SettingsSectionForm>
<Form {...form}>
<form className="space-y-4">
<FormField
control={form.control}
name="maintenanceModeEnabled"
render={({ field }) => {
const isDisabled =
isSecurityFeatureDisabled();
return (
<FormItem>
<div className="flex items-center space-x-2">
<FormControl>
<TooltipProvider>
<Tooltip>
<TooltipTrigger
asChild
>
<div className="flex items-center gap-2">
<SwitchInput
id="enable-maintenance"
checked={
field.value
}
label={t(
"enableMaintenanceMode"
)}
disabled={
isDisabled
}
onCheckedChange={(
val
) => {
if (
!isDisabled
) {
form.setValue(
"maintenanceModeEnabled",
val
);
}
}}
/>
</div>
</TooltipTrigger>
</Tooltip>
</TooltipProvider>
</FormControl>
</div>
<FormDescription>
{t(
"showMaintenancePage"
)}
</FormDescription>
<FormMessage />
</FormItem>
);
}}
/>
{isMaintenanceEnabled && (
<div className="space-y-4">
<FormField
control={form.control}
name="maintenanceModeType"
render={({ field }) => (
<FormItem className="space-y-3">
<FormLabel>
{t(
"maintenanceModeType"
)}
</FormLabel>
<FormControl>
<RadioGroup
onValueChange={
field.onChange
}
defaultValue={
field.value
}
disabled={isSecurityFeatureDisabled()}
className="flex flex-col space-y-1"
>
<FormItem className="flex items-start space-x-3 space-y-0">
<FormControl>
<RadioGroupItem value="automatic" />
</FormControl>
<div className="space-y-1 leading-none">
<FormLabel className="font-normal">
<strong>
{t(
"automatic"
)}
</strong>{" "}
(
{t(
"recommended"
)}
)
</FormLabel>
<FormDescription>
{t(
"automaticModeDescription"
)}
</FormDescription>
</div>
</FormItem>
<FormItem className="flex items-start space-x-3 space-y-0">
<FormControl>
<RadioGroupItem value="forced" />
</FormControl>
<div className="space-y-1 leading-none">
<FormLabel className="font-normal">
<strong>
{t(
"forced"
)}
</strong>
</FormLabel>
<FormDescription>
{t(
"forcedModeDescription"
)}
</FormDescription>
</div>
</FormItem>
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{maintenanceModeType ===
"forced" && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
<strong>
{t(
"warning:"
)}
</strong>{" "}
{t(
"forcedeModeWarning"
)}
</AlertDescription>
</Alert>
)}
<FormField
control={form.control}
name="maintenanceTitle"
render={({ field }) => (
<FormItem>
<FormLabel>
{t(
"pageTitle"
)}
</FormLabel>
<FormControl>
<Input
{...field}
disabled={isSecurityFeatureDisabled()}
placeholder="We'll be back soon!"
/>
</FormControl>
<FormDescription>
{t(
"pageTitleDescription"
)}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="maintenanceMessage"
render={({ field }) => (
<FormItem>
<FormLabel>
{t(
"maintenancePageMessage"
)}
</FormLabel>
<FormControl>
<Textarea
{...field}
rows={4}
disabled={isSecurityFeatureDisabled()}
placeholder={t(
"maintenancePageMessagePlaceholder"
)}
/>
</FormControl>
<FormDescription>
{t(
"maintenancePageMessageDescription"
)}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="maintenanceEstimatedTime"
render={({ field }) => (
<FormItem>
<FormLabel>
{t(
"maintenancePageTimeTitle"
)}
</FormLabel>
<FormControl>
<Input
{...field}
disabled={isSecurityFeatureDisabled()}
placeholder={t(
"maintenanceTime"
)}
/>
</FormControl>
<FormDescription>
{t(
"maintenanceEstimatedTimeDescription"
)}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</div>
)}
</form>
</Form>
</SettingsSectionForm>
</SettingsSectionBody>
</SettingsSection>
</SettingsContainer>
)}
<div className="flex justify-end">
<Button
type="submit"
onClick={() => {
console.log(form.getValues());
}}
loading={saveLoading}
disabled={saveLoading}
form="general-settings-form"
>
{t("saveSettings")}
</Button>
</div>
<Credenza
open={editDomainOpen}
onOpenChange={(setOpen) => setEditDomainOpen(setOpen)}
>
<CredenzaContent>
<CredenzaHeader>
<CredenzaTitle>Edit Domain</CredenzaTitle>
<CredenzaTitle>{t("editDomain")}</CredenzaTitle>
<CredenzaDescription>
Select a domain for your resource
{t("editDomainDescription")}
</CredenzaDescription>
</CredenzaHeader>
<CredenzaBody>
@@ -469,23 +815,35 @@ export default function GeneralForm() {
<Button
onClick={() => {
if (selectedDomain) {
const sanitizedSubdomain = selectedDomain.subdomain
? finalizeSubdomainSanitize(selectedDomain.subdomain)
: "";
const sanitizedSubdomain =
selectedDomain.subdomain
? finalizeSubdomainSanitize(
selectedDomain.subdomain
)
: "";
const sanitizedFullDomain = sanitizedSubdomain
? `${sanitizedSubdomain}.${selectedDomain.baseDomain}`
: selectedDomain.baseDomain;
const sanitizedFullDomain =
sanitizedSubdomain
? `${sanitizedSubdomain}.${selectedDomain.baseDomain}`
: selectedDomain.baseDomain;
setResourceFullDomain(`${resource.ssl ? "https" : "http"}://${sanitizedFullDomain}`);
form.setValue("domainId", selectedDomain.domainId);
form.setValue("subdomain", sanitizedSubdomain);
setResourceFullDomain(
`${resource.ssl ? "https" : "http"}://${sanitizedFullDomain}`
);
form.setValue(
"domainId",
selectedDomain.domainId
);
form.setValue(
"subdomain",
sanitizedSubdomain
);
setEditDomainOpen(false);
}
}}
>
Select Domain
{t("selectDomain")}
</Button>
</CredenzaFooter>
</CredenzaContent>

View File

@@ -0,0 +1,193 @@
"use client";
import { useState } from "react";
import {
SettingsContainer,
SettingsSection,
SettingsSectionBody,
SettingsSectionDescription,
SettingsSectionHeader,
SettingsSectionTitle
} from "@app/components/Settings";
import { Button } from "@app/components/ui/button";
import { createApiClient, formatAxiosError } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { toast } from "@app/hooks/useToast";
import { useParams, useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { PickSiteDefaultsResponse } from "@server/routers/site";
import { useSiteContext } from "@app/hooks/useSiteContext";
import { generateKeypair } from "../wireguardConfig";
import RegenerateCredentialsModal from "@app/components/RegenerateCredentialsModal";
import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext";
import { useSubscriptionStatusContext } from "@app/hooks/useSubscriptionStatusContext";
import { build } from "@server/build";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@app/components/ui/tooltip";
export default function CredentialsPage() {
const { env } = useEnvContext();
const api = createApiClient({ env });
const { orgId } = useParams();
const router = useRouter();
const t = useTranslations();
const { site } = useSiteContext();
const [modalOpen, setModalOpen] = useState(false);
const [siteDefaults, setSiteDefaults] = useState<PickSiteDefaultsResponse | null>(null);
const [wgConfig, setWgConfig] = useState("");
const [publicKey, setPublicKey] = useState("");
const { licenseStatus, isUnlocked } = useLicenseStatusContext();
const subscription = useSubscriptionStatusContext();
const isSecurityFeatureDisabled = () => {
const isEnterpriseNotLicensed = build === "enterprise" && !isUnlocked();
const isSaasNotSubscribed =
build === "saas" && !subscription?.isSubscribed();
return isEnterpriseNotLicensed || isSaasNotSubscribed;
};
const hydrateWireGuardConfig = (
privateKey: string,
publicKey: string,
subnet: string,
address: string,
endpoint: string,
listenPort: string
) => {
const config = `[Interface]
Address = ${subnet}
ListenPort = 51820
PrivateKey = ${privateKey}
[Peer]
PublicKey = ${publicKey}
AllowedIPs = ${address.split("/")[0]}/32
Endpoint = ${endpoint}:${listenPort}
PersistentKeepalive = 5`;
setWgConfig(config);
return config;
};
const handleConfirmRegenerate = async () => {
let generatedPublicKey = "";
let generatedWgConfig = "";
if (site?.type === "wireguard") {
const generatedKeypair = generateKeypair();
generatedPublicKey = generatedKeypair.publicKey;
setPublicKey(generatedPublicKey);
const res = await api.get(`/org/${orgId}/pick-site-defaults`);
if (res && res.status === 200) {
const data = res.data.data;
setSiteDefaults(data);
// generate config with the fetched data
generatedWgConfig = hydrateWireGuardConfig(
generatedKeypair.privateKey,
data.publicKey,
data.subnet,
data.address,
data.endpoint,
data.listenPort
);
}
await api.post(`/re-key/${site?.siteId}/regenerate-site-secret`, {
type: "wireguard",
subnet: res.data.data.subnet,
exitNodeId: res.data.data.exitNodeId,
pubKey: generatedPublicKey
});
}
if (site?.type === "newt") {
const res = await api.get(`/org/${orgId}/pick-site-defaults`);
if (res && res.status === 200) {
const data = res.data.data;
setSiteDefaults(data);
await api.post(`/re-key/${site?.siteId}/regenerate-site-secret`, {
type: "newt",
newtId: data.newtId,
newtSecret: data.newtSecret
});
}
}
toast({
title: t("credentialsSaved"),
description: t("credentialsSavedDescription")
});
router.refresh();
};
const getCredentialType = () => {
if (site?.type === "wireguard") return "site-wireguard";
if (site?.type === "newt") return "site-newt";
return "site-newt";
};
const getCredentials = () => {
if (site?.type === "wireguard" && wgConfig) {
return { wgConfig };
}
if (site?.type === "newt" && siteDefaults) {
return {
Id: siteDefaults.newtId,
Secret: siteDefaults.newtSecret
};
}
return undefined;
};
return (
<SettingsContainer>
<SettingsSection>
<SettingsSectionHeader>
<SettingsSectionTitle>
{t("generatedcredentials")}
</SettingsSectionTitle>
<SettingsSectionDescription>
{t("regenerateCredentials")}
</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsSectionBody>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="inline-block">
<Button
onClick={() => setModalOpen(true)}
disabled={isSecurityFeatureDisabled()}
>
{t("regeneratecredentials")}
</Button>
</div>
</TooltipTrigger>
{isSecurityFeatureDisabled() && (
<TooltipContent side="top">
{t("featureDisabledTooltip")}
</TooltipContent>
)}
</Tooltip>
</TooltipProvider>
</SettingsSectionBody>
</SettingsSection>
<RegenerateCredentialsModal
open={modalOpen}
onOpenChange={setModalOpen}
type={getCredentialType()}
onConfirmRegenerate={handleConfirmRegenerate}
dashboardUrl={env.app.dashboardUrl}
credentials={getCredentials()}
/>
</SettingsContainer>
);
}

View File

@@ -15,7 +15,7 @@ import {
import { Input } from "@/components/ui/input";
import { useSiteContext } from "@app/hooks/useSiteContext";
import { useForm } from "react-hook-form";
import { toast } from "@app/hooks/useToast";
import { toast, useToast } from "@app/hooks/useToast";
import { useRouter } from "next/navigation";
import {
SettingsContainer,
@@ -37,6 +37,7 @@ import { Tag, TagInput } from "@app/components/tags/tag-input";
const GeneralFormSchema = z.object({
name: z.string().nonempty("Name is required"),
niceId: z.string().min(1).max(255).optional(),
dockerSocketEnabled: z.boolean().optional(),
remoteSubnets: z
.array(
@@ -55,19 +56,18 @@ export default function GeneralPage() {
const { env } = useEnvContext();
const api = createApiClient(useEnvContext());
const [loading, setLoading] = useState(false);
const [activeCidrTagIndex, setActiveCidrTagIndex] = useState<number | null>(
null
);
const router = useRouter();
const t = useTranslations();
const { toast } = useToast();
const [loading, setLoading] = useState(false);
const [activeCidrTagIndex, setActiveCidrTagIndex] = useState<number | null>(null);
const form = useForm({
resolver: zodResolver(GeneralFormSchema),
defaultValues: {
name: site?.name,
niceId: site?.niceId || "",
dockerSocketEnabled: site?.dockerSocketEnabled ?? false,
remoteSubnets: site?.remoteSubnets
? site.remoteSubnets.split(",").map((subnet, index) => ({
@@ -82,37 +82,40 @@ export default function GeneralPage() {
async function onSubmit(data: GeneralFormValues) {
setLoading(true);
await api
.post(`/site/${site?.siteId}`, {
try {
await api.post(`/site/${site?.siteId}`, {
name: data.name,
niceId: data.niceId,
dockerSocketEnabled: data.dockerSocketEnabled,
remoteSubnets:
data.remoteSubnets
?.map((subnet) => subnet.text)
.join(",") || ""
})
.catch((e) => {
toast({
variant: "destructive",
title: t("siteErrorUpdate"),
description: formatAxiosError(
e,
t("siteErrorUpdateDescription")
)
});
?.map((subnet) => subnet.text)
.join(",") || ""
});
updateSite({
name: data.name,
dockerSocketEnabled: data.dockerSocketEnabled,
remoteSubnets:
data.remoteSubnets?.map((subnet) => subnet.text).join(",") || ""
});
updateSite({
name: data.name,
niceId: data.niceId,
dockerSocketEnabled: data.dockerSocketEnabled,
remoteSubnets:
data.remoteSubnets?.map((subnet) => subnet.text).join(",") || ""
});
toast({
title: t("siteUpdated"),
description: t("siteUpdatedDescription")
});
if (data.niceId && data.niceId !== site?.niceId) {
router.replace(`/${site?.orgId}/settings/sites/${data.niceId}/general`);
}
toast({
title: t("siteUpdated"),
description: t("siteUpdatedDescription")
});
} catch (e) {
toast({
variant: "destructive",
title: t("siteErrorUpdate"),
description: formatAxiosError(e, t("siteErrorUpdateDescription"))
});
}
setLoading(false);
@@ -153,8 +156,25 @@ export default function GeneralPage() {
)}
/>
{env.flags.enableClients &&
site.type === "newt" ? (
<FormField
control={form.control}
name="niceId"
render={({ field }) => (
<FormItem>
<FormLabel>{t("identifier")}</FormLabel>
<FormControl>
<Input
{...field}
placeholder={t("enterIdentifier")}
className="flex-1"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{env.flags.enableClients && site.type === "newt" ? (
<FormField
control={form.control}
name="remoteSubnets"

View File

@@ -8,6 +8,7 @@ import { HorizontalTabs } from "@app/components/HorizontalTabs";
import SettingsSectionTitle from "@app/components/SettingsSectionTitle";
import SiteInfoCard from "../../../../../components/SiteInfoCard";
import { getTranslations } from "next-intl/server";
import { build } from "@server/build";
interface SettingsLayoutProps {
children: React.ReactNode;
@@ -35,14 +36,23 @@ export default async function SettingsLayout(props: SettingsLayoutProps) {
const navItems = [
{
title: t('general'),
href: "/{orgId}/settings/sites/{niceId}/general"
}
href: `/${params.orgId}/settings/sites/${params.niceId}/general`,
},
...(site.type !== 'local' && build === 'enterprise'
? [
{
title: t('credentials'),
href: `/${params.orgId}/settings/sites/${params.niceId}/credentials`,
},
]
: []),
];
return (
<>
<SettingsSectionTitle
title={t('siteSetting', {siteName: site?.name})}
title={t('siteSetting', { siteName: site?.name })}
description={t('siteSettingDescription')}
/>

View File

@@ -0,0 +1,68 @@
import { headers } from "next/headers";
import { priv } from "@app/lib/api";
import { GetMaintenanceInfoResponse } from "@server/routers/resource/types";
import { getTranslations } from "next-intl/server";
import {
Card,
CardContent,
CardHeader,
CardTitle
} from "@app/components/ui/card";
import { Alert, AlertTitle, AlertDescription } from "@app/components/ui/alert";
import { Clock } from "lucide-react";
export const dynamic = "force-dynamic";
export default async function MaintenanceScreen() {
const t = await getTranslations();
let title = t("maintenanceScreenTitle");
let message = t("maintenanceScreenMessage");
let estimatedTime: string | null = null;
try {
const headersList = await headers();
const host = headersList.get("host") || "";
const hostname = host.split(":")[0];
const res = await priv.get<GetMaintenanceInfoResponse>(
`/maintenance/info?fullDomain=${encodeURIComponent(hostname)}`
);
if (res && res.status === 200) {
const maintenanceInfo = res.data;
title = maintenanceInfo?.maintenanceTitle || title;
message = maintenanceInfo?.maintenanceMessage || message;
estimatedTime = maintenanceInfo?.maintenanceEstimatedTime || null;
}
} catch (err) {
console.error(
"Failed to fetch maintenance info",
err instanceof Error ? err.message : String(err)
);
}
return (
<div className="min-h-screen flex items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle>{title}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<p>{message}</p>
{estimatedTime && (
<Alert className="w-full" variant="neutral">
<Clock className="h-5 w-5" />
<AlertTitle>
{t("maintenanceScreenEstimatedCompletion")}
</AlertTitle>
<AlertDescription className="flex flex-col space-y-2">
{estimatedTime}
</AlertDescription>
</Alert>
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -1,7 +1,6 @@
"use client";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { InfoIcon } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { useClientContext } from "@app/hooks/useClientContext";
import {
InfoSection,
@@ -19,9 +18,7 @@ export default function SiteInfoCard({}: ClientInfoCardProps) {
return (
<Alert>
<InfoIcon className="h-4 w-4" />
<AlertTitle className="font-semibold">{t("clientInformation")}</AlertTitle>
<AlertDescription className="mt-4">
<AlertDescription>
<InfoSections cols={2}>
<>
<InfoSection>

View File

@@ -278,14 +278,14 @@ export default function ClientsTable({ clients, orgId }: ClientTableProps) {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{/* <Link */}
{/* className="block w-full" */}
{/* href={`/${clientRow.orgId}/settings/sites/${clientRow.nice}`} */}
{/* > */}
{/* <DropdownMenuItem> */}
{/* View settings */}
{/* </DropdownMenuItem> */}
{/* </Link> */}
<Link
className="block w-full"
href={`/${clientRow.orgId}/settings/clients/${clientRow.id}`}
>
<DropdownMenuItem>
View settings
</DropdownMenuItem>
</Link>
<DropdownMenuItem
onClick={() => {
setSelectedClient(clientRow);

View File

@@ -0,0 +1,52 @@
"use client";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { InfoIcon } from "lucide-react";
import {
InfoSection,
InfoSectionContent,
InfoSections,
InfoSectionTitle
} from "@app/components/InfoSection";
import { useTranslations } from "next-intl";
import { useRemoteExitNodeContext } from "@app/hooks/useRemoteExitNodeContext";
type ExitNodeInfoCardProps = {};
export default function ExitNodeInfoCard({}: ExitNodeInfoCardProps) {
const { remoteExitNode, updateRemoteExitNode } = useRemoteExitNodeContext();
const t = useTranslations();
return (
<Alert>
<AlertDescription className="mt-4">
<InfoSections cols={2}>
<>
<InfoSection>
<InfoSectionTitle>{t("status")}</InfoSectionTitle>
<InfoSectionContent>
{remoteExitNode.online ? (
<div className="text-green-500 flex items-center space-x-2">
<div className="w-2 h-2 bg-green-500 rounded-full"></div>
<span>{t("online")}</span>
</div>
) : (
<div className="text-neutral-500 flex items-center space-x-2">
<div className="w-2 h-2 bg-gray-500 rounded-full"></div>
<span>{t("offline")}</span>
</div>
)}
</InfoSectionContent>
</InfoSection>
</>
<InfoSection>
<InfoSectionTitle>{t("address")}</InfoSectionTitle>
<InfoSectionContent>
{remoteExitNode.address}
</InfoSectionContent>
</InfoSection>
</InfoSections>
</AlertDescription>
</Alert>
);
}

View File

@@ -0,0 +1,216 @@
"use client";
import { useState } from "react";
import {
Credenza,
CredenzaBody,
CredenzaClose,
CredenzaContent,
CredenzaDescription,
CredenzaFooter,
CredenzaHeader,
CredenzaTitle
} from "@app/components/Credenza";
import { Button } from "@app/components/ui/button";
import { Alert, AlertDescription, AlertTitle } from "@app/components/ui/alert";
import { InfoIcon, AlertTriangle } from "lucide-react";
import { useTranslations } from "next-intl";
import { InfoSection, InfoSectionContent, InfoSections, InfoSectionTitle } from "@app/components/InfoSection";
import CopyToClipboard from "@app/components/CopyToClipboard";
import CopyTextBox from "@app/components/CopyTextBox";
import { QRCodeCanvas } from "qrcode.react";
type CredentialType = "site-wireguard" | "site-newt" | "client-olm" | "remote-exit-node";
interface RegenerateCredentialsModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
type: CredentialType;
onConfirmRegenerate: () => Promise<void>;
dashboardUrl: string;
credentials?: {
// For WireGuard sites
wgConfig?: string;
Id?: string;
Secret?: string;
};
}
export default function RegenerateCredentialsModal({
open,
onOpenChange,
type,
onConfirmRegenerate,
dashboardUrl,
credentials
}: RegenerateCredentialsModalProps) {
const t = useTranslations();
const [stage, setStage] = useState<"confirm" | "show">("confirm");
const [loading, setLoading] = useState(false);
const handleConfirm = async () => {
try {
setLoading(true);
await onConfirmRegenerate();
setStage("show");
} catch (error) {
} finally {
setLoading(false);
}
};
const handleClose = () => {
setStage("confirm");
onOpenChange(false);
};
const getTitle = () => {
if (stage === "confirm") {
return t("regeneratecredentials");
}
switch (type) {
case "site-wireguard":
return t("WgConfiguration");
case "site-newt":
return t("siteNewtCredentials");
case "client-olm":
return t("clientOlmCredentials");
case "remote-exit-node":
return t("remoteExitNodeCreate.generate.title");
}
};
const getDescription = () => {
if (stage === "confirm") {
return t("regenerateCredentialsWarning");
}
switch (type) {
case "site-wireguard":
return t("WgConfigurationDescription");
case "site-newt":
return t("siteNewtCredentialsDescription");
case "client-olm":
return t("clientOlmCredentialsDescription");
case "remote-exit-node":
return t("remoteExitNodeCreate.generate.description");
}
};
return (
<Credenza open={open} onOpenChange={onOpenChange}>
<CredenzaContent className="max-h-[80vh] flex flex-col">
<CredenzaHeader>
<CredenzaTitle>{getTitle()}</CredenzaTitle>
<CredenzaDescription>{getDescription()}</CredenzaDescription>
</CredenzaHeader>
<CredenzaBody className="overflow-y-auto px-4">
{stage === "confirm" ? (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertTitle className="font-semibold">
{t("warning")}
</AlertTitle>
<AlertDescription>
{t("regenerateCredentialsConfirmation")}
</AlertDescription>
</Alert>
) : (
<>
{credentials?.wgConfig && (
<div className="space-y-4">
<div className="flex flex-col items-center gap-4">
<CopyTextBox text={credentials.wgConfig} />
<div className="relative w-fit border rounded-md">
<div className="bg-white p-6 rounded-md">
<QRCodeCanvas
value={credentials.wgConfig}
size={168}
className="mx-auto"
/>
</div>
</div>
</div>
<Alert variant="neutral">
<InfoIcon className="h-4 w-4" />
<AlertTitle className="font-semibold">
{t("copyandsavethesecredentials")}
</AlertTitle>
<AlertDescription>
{t("copyandsavethesecredentialsdescription")}
</AlertDescription>
</Alert>
</div>
)}
{credentials?.Id && credentials.Secret && (
<div className="space-y-4">
<InfoSections cols={1}>
<InfoSection>
<InfoSectionTitle>
{t("endpoint")}
</InfoSectionTitle>
<InfoSectionContent>
<CopyToClipboard text={dashboardUrl} />
</InfoSectionContent>
</InfoSection>
<InfoSection>
<InfoSectionTitle>
{t("Id")}
</InfoSectionTitle>
<InfoSectionContent>
<CopyToClipboard text={credentials?.Id} />
</InfoSectionContent>
</InfoSection>
<InfoSection>
<InfoSectionTitle>
{t("SecretKey")}
</InfoSectionTitle>
<InfoSectionContent>
<CopyToClipboard text={credentials?.Secret} />
</InfoSectionContent>
</InfoSection>
</InfoSections>
<Alert variant="neutral">
<InfoIcon className="h-4 w-4" />
<AlertTitle className="font-semibold">
{t("copyandsavethesecredentials")}
</AlertTitle>
<AlertDescription>
{t("copyandsavethesecredentialsdescription")}
</AlertDescription>
</Alert>
</div>
)}
</>
)}
</CredenzaBody>
<CredenzaFooter>
{stage === "confirm" ? (
<>
<CredenzaClose asChild>
<Button variant="outline">{t("cancel")}</Button>
</CredenzaClose>
<Button
onClick={handleConfirm}
loading={loading}
disabled={loading}
variant="destructive"
>
{t("confirm")}
</Button>
</>
) : (
<Button onClick={handleClose} className="w-full">
{t("close")}
</Button>
)}
</CredenzaFooter>
</CredenzaContent>
</Credenza>
);
}

View File

@@ -1,7 +1,7 @@
"use client";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { InfoIcon, ShieldCheck, ShieldOff } from "lucide-react";
import { ShieldCheck, ShieldOff } from "lucide-react";
import { useResourceContext } from "@app/hooks/useResourceContext";
import CopyToClipboard from "@app/components/CopyToClipboard";
import {
@@ -17,21 +17,30 @@ import { useEnvContext } from "@app/hooks/useEnvContext";
type ResourceInfoBoxType = {};
export default function ResourceInfoBox({}: ResourceInfoBoxType) {
const { resource, authInfo } = useResourceContext();
export default function ResourceInfoBox({ }: ResourceInfoBoxType) {
const { resource, authInfo, updateResource } = useResourceContext();
const { env } = useEnvContext();
const t = useTranslations();
const fullUrl = `${resource.ssl ? "https" : "http"}://${toUnicode(resource.fullDomain || "")}`;
return (
<Alert>
<AlertDescription>
{/* 4 cols because of the certs */}
<InfoSections
cols={resource.http && env.flags.usePangolinDns ? 4 : 3}
cols={resource.http && env.flags.usePangolinDns ? 5 : 4}
>
<InfoSection>
<InfoSectionTitle>
{t("identifier")}
</InfoSectionTitle>
<InfoSectionContent>
{resource.niceId}
</InfoSectionContent>
</InfoSection>
{resource.http ? (
<>
<InfoSection>
@@ -40,10 +49,10 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
</InfoSectionTitle>
<InfoSectionContent>
{authInfo.password ||
authInfo.pincode ||
authInfo.sso ||
authInfo.whitelist ||
authInfo.headerAuth ? (
authInfo.pincode ||
authInfo.sso ||
authInfo.whitelist ||
authInfo.headerAuth ? (
<div className="flex items-start space-x-2 text-green-500">
<ShieldCheck className="w-4 h-4 mt-0.5" />
<span>{t("protected")}</span>

View File

@@ -507,22 +507,6 @@ export default function ResourcesTable({
);
}
},
{
accessorKey: "nice",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() =>
column.toggleSorting(column.getIsSorted() === "asc")
}
>
{t("resource")}
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
}
},
{
accessorKey: "protocol",
header: t("protocol"),

View File

@@ -5,7 +5,7 @@ import { useTranslations } from "next-intl";
import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext";
import { useSubscriptionStatusContext } from "@app/hooks/useSubscriptionStatusContext";
export function SecurityFeaturesAlert() {
export function LicenseOrSubscriptionRequiredAlert() {
const t = useTranslations();
const { isUnlocked } = useLicenseStatusContext();
const subscriptionStatus = useSubscriptionStatusContext();

View File

@@ -1,7 +1,6 @@
"use client";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { InfoIcon } from "lucide-react";
import { useSiteContext } from "@app/hooks/useSiteContext";
import {
InfoSection,
@@ -12,9 +11,10 @@ import {
import { useTranslations } from "next-intl";
import { useEnvContext } from "@app/hooks/useEnvContext";
type SiteInfoCardProps = {};
export default function SiteInfoCard({}: SiteInfoCardProps) {
export default function SiteInfoCard({ }: SiteInfoCardProps) {
const { site, updateSite } = useSiteContext();
const t = useTranslations();
const { env } = useEnvContext();
@@ -31,10 +31,19 @@ export default function SiteInfoCard({}: SiteInfoCardProps) {
}
};
return (
<Alert>
<AlertDescription>
<InfoSections cols={env.flags.enableClients ? 3 : 2}>
<InfoSections cols={env.flags.enableClients ? 4 : 3}>
<InfoSection>
<InfoSectionTitle>
{t("identifier")}
</InfoSectionTitle>
<InfoSectionContent>
{site.niceId}
</InfoSectionContent>
</InfoSection>
{(site.type == "newt" || site.type == "wireguard") && (
<>
<InfoSection>

View File

@@ -164,30 +164,6 @@ export default function SitesTable({ sites, orgId }: SitesTableProps) {
}
}
},
{
accessorKey: "nice",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() =>
column.toggleSorting(column.getIsSorted() === "asc")
}
className="hidden md:flex whitespace-nowrap"
>
{t("site")}
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
cell: ({ row }) => {
return (
<div className="hidden md:block whitespace-nowrap">
{row.original.nice}
</div>
);
}
},
{
accessorKey: "mbIn",
header: ({ column }) => {

View File

@@ -2,11 +2,15 @@
import RemoteExitNodeContext from "@app/contexts/remoteExitNodeContext";
import { build } from "@server/build";
import { GetRemoteExitNodeResponse } from "@server/routers/remoteExitNode/types";
import { useContext } from "react";
export function useRemoteExitNodeContext() {
if (build == "oss") {
return null;
return {
remoteExitNode: {} as GetRemoteExitNodeResponse,
updateRemoteExitNode: () => {},
};
}
const context = useContext(RemoteExitNodeContext);
if (context === undefined) {