Compare commits

...

16 Commits
1.0.0 ... 1.0.1

Author SHA1 Message Date
Milo Schwartz
e601816791 Merge pull request #319 from fosrl/dev
1.0.1
2025-03-10 11:09:38 -04:00
miloschwartz
7a46cf3da7 add border-2 to checkbox 2025-03-10 11:06:02 -04:00
miloschwartz
ad32e5e651 fix base domain overwritten on update closes #282 2025-03-09 22:05:13 -04:00
miloschwartz
8ec55eb70d append site name to resource in list add add site to info card closes #297 2025-03-08 22:11:27 -05:00
Owen
767fec19cd Remove old example config 2025-03-08 20:03:26 -05:00
miloschwartz
d215a12f5a disable auto backup on migration with env var 2025-03-08 18:23:36 -05:00
Owen
d22dcfb464 Optimize container size 2025-03-08 18:11:47 -05:00
miloschwartz
c93b36c757 remove environment variable support and config file autogeneration 2025-03-08 18:06:14 -05:00
Owen Schwartz
9253dd19ba Merge pull request #307 from fosrl/remove_json_group_array
Remove json_group_array from queries
2025-03-08 17:30:46 -05:00
miloschwartz
b9d83a2507 add es.md 2025-03-08 16:06:52 -05:00
Owen
581f96daa8 Remove json_group_array from queries
Also improve handling tcp/udp resources in newt function so it does not
loop twice
2025-03-08 11:58:48 -05:00
Owen
33ff2fbf3b Allow matching parts of words in path
Resolves #228
2025-03-08 11:43:47 -05:00
Owen
535b4e1fb1 Add clean up our few tests and add tests for #228 2025-03-08 11:43:22 -05:00
Owen
5871bea706 Reset port when entering targets
Resolves #270
2025-03-08 10:52:38 -05:00
Owen
07eb422491 Add back metrics port for scripting 2025-03-04 23:52:37 -05:00
Owen
654ed46a46 Return 401 instead of 400 on bad login
Resolves #276
2025-03-04 20:32:48 -05:00
33 changed files with 15661 additions and 511 deletions

View File

@@ -22,7 +22,6 @@ next-env.d.ts
*.log
.machinelogs*.json
*-audit.json
package-lock.json
install/
bruno/
LICENSE

1
.gitignore vendored
View File

@@ -23,7 +23,6 @@ next-env.d.ts
.machinelogs*.json
*-audit.json
migrations
package-lock.json
tsconfig.tsbuildinfo
config/config.yml
dist

View File

@@ -2,9 +2,8 @@ FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json ./
RUN npm install
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
@@ -14,21 +13,19 @@ RUN npm run build
FROM node:20-alpine AS runner
RUN apk add --no-cache curl
WORKDIR /app
COPY package.json ./
# Curl used for the health checks
RUN apk add --no-cache curl
RUN npm install --omit=dev
COPY package.json package-lock.json ./
RUN npm ci --only=production && npm cache clean --force
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/init ./dist/init
COPY config/config.example.yml ./dist/config.example.yml
COPY config/traefik/traefik_config.example.yml ./dist/traefik_config.example.yml
COPY config/traefik/dynamic_config.example.yml ./dist/dynamic_config.example.yml
COPY server/db/names.json ./dist/names.json
COPY public ./public

View File

@@ -1,53 +0,0 @@
http:
middlewares:
redirect-to-https:
redirectScheme:
scheme: https
routers:
# HTTP to HTTPS redirect router
main-app-router-redirect:
rule: "Host(`{{.DashboardDomain}}`)"
service: next-service
entryPoints:
- web
middlewares:
- redirect-to-https
# Next.js router (handles everything except API and WebSocket paths)
next-router:
rule: "Host(`{{.DashboardDomain}}`) && !PathPrefix(`/api/v1`)"
service: next-service
entryPoints:
- websecure
tls:
certResolver: letsencrypt
# API router (handles /api/v1 paths)
api-router:
rule: "Host(`{{.DashboardDomain}}`) && PathPrefix(`/api/v1`)"
service: api-service
entryPoints:
- websecure
tls:
certResolver: letsencrypt
# WebSocket router
ws-router:
rule: "Host(`{{.DashboardDomain}}`)"
service: api-service
entryPoints:
- websecure
tls:
certResolver: letsencrypt
services:
next-service:
loadBalancer:
servers:
- url: "http://pangolin:{{.NEXT_PORT}}" # Next.js server
api-service:
loadBalancer:
servers:
- url: "http://pangolin:{{.EXTERNAL_PORT}}" # API/WebSocket server

View File

@@ -1,44 +0,0 @@
api:
insecure: true
dashboard: true
providers:
http:
endpoint: "http://pangolin:{{.INTERNAL_PORT}}/api/v1/traefik-config"
pollInterval: "5s"
file:
filename: "/etc/traefik/dynamic_config.yml"
experimental:
plugins:
badger:
moduleName: "github.com/fosrl/badger"
version: "v1.0.0-beta.3"
log:
level: "INFO"
format: "common"
certificatesResolvers:
letsencrypt:
acme:
httpChallenge:
entryPoint: web
email: "{{.LetsEncryptEmail}}"
storage: "/letsencrypt/acme.json"
caServer: "https://acme-v02.api.letsencrypt.org/directory"
entryPoints:
web:
address: ":80"
websecure:
address: ":443"
transport:
respondingTimeouts:
readTimeout: "30m"
http:
tls:
certResolver: "letsencrypt"
serversTransport:
insecureSkipVerify: true

View File

@@ -22,5 +22,9 @@ services:
- ./config/crowdsec_logs/syslog:/var/log/syslog:ro # syslog
- ./config/crowdsec_logs:/var/log # crowdsec logs
- ./config/traefik/logs:/var/log/traefik # traefik logs
ports:
- 6060:6060 # metrics endpoint for prometheus
expose:
- 6060 # metrics endpoint for prometheus
restart: unless-stopped
command: -t # Add test config flag to verify configuration

291
internationalization/es.md Normal file
View File

@@ -0,0 +1,291 @@
## Authentication Site
| EN | ES | Notes |
| -------------------------------------------------------- | ------------------------------------------------------------ | ---------- |
| Powered by [Pangolin](https://github.com/fosrl/pangolin) | Desarrollado por [Pangolin](https://github.com/fosrl/pangolin) | |
| Authentication Required | Se requiere autenticación | |
| Choose your preferred method to access {resource} | Elije tu método requerido para acceder a {resource} | |
| PIN | PIN | |
| User | Usuario | |
| 6-digit PIN Code | Código PIN de 6 dígitos | pin login |
| Login in with PIN | Registrate con PIN | pin login |
| Email | Email | user login |
| Enter your email | Introduce tu email | user login |
| Password | Contraseña | user login |
| Enter your password | Introduce tu contraseña | user login |
| Forgot your password? | ¿Olvidaste tu contraseña? | user login |
| Log in | Iniciar sesión | user login |
## Login site
| EN | ES | Notes |
| --------------------- | ---------------------------------- | ----------- |
| Welcome to Pangolin | Binvenido a Pangolin | |
| Log in to get started | Registrate para comenzar | |
| Email | Email | |
| Enter your email | Introduce tu email | placeholder |
| Password | Contraseña | |
| Enter your password | Introduce tu contraseña | placeholder |
| Forgot your password? | ¿Olvidaste tu contraseña? | |
| Log in | Iniciar sesión | |
# Ogranization site after successful login
| EN | ES | Notes |
| ----------------------------------------- | -------------------------------------------- | ----- |
| Welcome to Pangolin | Binvenido a Pangolin | |
| You're a member of {number} organization. | Eres miembro de la organización {number}. | |
## Shared Header, Navbar and Footer
##### Header
| EN | ES | Notes |
| ------------------- | ------------------- | ----- |
| Documentation | Documentación | |
| Support | Soporte | |
| Organization {name} | Organización {name} | |
##### Organization selector
| EN | ES | Notes |
| ---------------- | ----------------- | ----- |
| Search… | Buscar… | |
| Create | Crear | |
| New Organization | Nueva Organización| |
| Organizations | Organizaciones | |
##### Navbar
| EN | ES | Notes |
| --------------- | -----------------------| ----- |
| Sites | Sitios | |
| Resources | Recursos | |
| User & Roles | Usuarios y roles | |
| Shareable Links | Enlaces para compartir | |
| General | General | |
##### Footer
| EN | ES | |
| ------------------------- | --------------------------- | -------|
| Page {number} of {number} | Página {number} de {number} | footer |
| Rows per page | Filas por página | footer |
| Pangolin | Pangolin | footer |
| Built by Fossorial | Construido por Fossorial | footer |
| Open Source | Código abierto | footer |
| Documentation | Documentación | footer |
| {version} | {version} | footer |
## Main “Sites”
##### “Hero” section
| EN | ES | Notes |
| ------------------------------------------------------------ | ------------------------------------------------------------ | ----- |
| Newt (Recommended) | Newt (Recomendado) | |
| For the best user experience, use Newt. It uses WireGuard under the hood and allows you to address your private resources by their LAN address on your private network from within the Pangolin dashboard. | Para obtener la mejor experiencia de usuario, utiliza Newt. Utiliza WireGuard internamente y te permite abordar tus recursos privados mediante tu dirección LAN en tu red privada desde el panel de Pangolin. | |
| Runs in Docker | Se ejecuta en Docker | |
| Runs in shell on macOS, Linux, and Windows | Se ejecuta en shell en macOS, Linux y Windows | |
| Install Newt | Instalar Newt | |
| Basic WireGuard<br> | WireGuard básico<br> | |
| Compatible with all WireGuard clients<br> | Compatible con todos los clientes WireGuard<br> | |
| Manual configuration required | Se requiere configuración manual | |
##### Content
| EN | ES | Notes |
| --------------------------------------------------------- | ------------------------------------------------------------ | -------------------------------- |
| Manage Sites | Administrar sitios | |
| Allow connectivity to your network through secure tunnels | Permitir la conectividad a tu red a través de túneles seguros| |
| Search sites | Buscar sitios | placeholder |
| Add Site | Agregar sitio | |
| Name | Nombre | table header |
| Online | Conectado | table header |
| Site | Sitio | table header |
| Data In | Datos en | table header |
| Data Out | Datos de salida | table header |
| Connection Type | Tipo de conexión | table header |
| Online | Conectado | site state |
| Offline | Desconectado | site state |
| Edit → | Editar → | |
| View settings | Ver configuración | Popup after clicking “…” on site |
| Delete | Borrar | Popup after clicking “…” on site |
##### Add Site Popup
| EN | ES | Notes |
| ------------------------------------------------------ | ----------------------------------------------------------- | ----------- |
| Create Site | Crear sitio | |
| Create a new site to start connection for this site | Crear un nuevo sitio para iniciar la conexión para este sitio | |
| Name | Nombre | |
| Site name | Nombre del sitio | placeholder |
| This is the name that will be displayed for this site. | Este es el nombre que se mostrará para este sitio. | desc |
| Method | Método | |
| Local | Local | |
| Newt | Newt | |
| WireGuard | WireGuard | |
| This is how you will expose connections. | Así es como expondrás las conexiones. | |
| You will only be able to see the configuration once. | Solo podrás ver la configuración una vez. | |
| Learn how to install Newt on your system | Aprende a instalar Newt en tu sistema | |
| I have copied the config | He copiado la configuración | |
| Create Site | Crear sitio | |
| Close | Cerrar | |
## Main “Resources”
##### “Hero” section
| EN | ES | Notes |
| ------------------------------------------------------------ | ------------------------------------------------------------ | ----- |
| Resources | Recursos | |
| Ressourcen sind Proxy-Server für Anwendungen, die in Ihrem privaten Netzwerk laufen. Erstellen Sie eine Ressource für jede HTTP- oder HTTPS-Anwendung in Ihrem privaten Netzwerk. Jede Ressource muss mit einer Website verbunden sein, um eine private und sichere Verbindung über den verschlüsselten WireGuard-Tunnel zu ermöglichen. |Los recursos son servidores proxy para aplicaciones que se ejecutan en su red privada. Cree un recurso para cada aplicación HTTP o HTTPS en su red privada. Cada recurso debe estar conectado a un sitio web para proporcionar una conexión privada y segura a través del túnel cifrado WireGuard. | |
| Secure connectivity with WireGuard encryption | Conectividad segura con encriptación WireGuard | |
| Configure multiple authentication methods | Configura múltiples métodos de autenticación | |
| User and role-based access control | Control de acceso basado en usuarios y roles | |
##### Content
| EN | ES | Notes |
| -------------------------------------------------- | ---------------------------------------------------------- | -------------------- |
| Manage Resources | Administrar recursos | |
| Create secure proxies to your private applications | Crea servidores proxy seguros para tus aplicaciones privadas | |
| Search resources | Buscar recursos | placeholder |
| Name | Nombre | |
| Site | Sitio | |
| Full URL | URL completa | |
| Authentication | Autenticación | |
| Not Protected | No protegido | authentication state |
| Protected | Protegido | authentication state |
| Edit → | Editar → | |
| Add Resource | Agregar recurso | |
##### Add Resource Popup
| EN | ES | Notes |
| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------- |
| Create Resource | Crear recurso | |
| Create a new resource to proxy request to your app | Crea un nuevo recurso para enviar solicitudes a tu aplicación | |
| Name | Nombre | |
| My Resource | Mi recurso | name placeholder |
| This is the name that will be displayed for this resource. | Este es el nombre que se mostrará para este recurso. | |
| Subdomain | Subdominio | |
| Enter subdomain | Ingresar subdominio | |
| This is the fully qualified domain name that will be used to access the resource. | Este es el nombre de dominio completo que se utilizará para acceder al recurso. | |
| Site | Sitio | |
| Search site… | Buscar sitio… | Site selector popup |
| This is the site that will be used in the dashboard. | Este es el sitio que se utilizará en el panel de control. | |
| Create Resource | Crear recurso | |
| Close | Cerrar | |
## Main “User & Roles”
##### Content
| EN | ES | Notes |
| ------------------------------------------------------------ | ------------------------------------------------------------ | ----------------------------- |
| Manage User & Roles | Administrar usuarios y roles | |
| Invite users and add them to roles to manage access to your organization | Invita a usuarios y agrégalos a roles para administrar el acceso a tu organización | |
| Users | Usuarios | sidebar item |
| Roles | Roles | sidebar item |
| **User tab** | **Pestaña de usuario** | |
| Search users | Buscar usuarios | placeholder |
| Invite User | Invitar usuario | addbutton |
| Email | Email | table header |
| Status | Estado | table header |
| Role | Role | table header |
| Confirmed | Confirmado | account status |
| Not confirmed (?) | No confirmado (?) | unknown for me account status |
| Owner | Dueño | role |
| Admin | Administrador | role |
| Member | Miembro | role |
| **Roles Tab** | **Pestaña Roles** | |
| Search roles | Buscar roles | placeholder |
| Add Role | Agregar rol | addbutton |
| Name | Nombre | table header |
| Description | Descripción | table header |
| Admin | Administrador | role |
| Member | Miembro | role |
| Admin role with the most permissions | Rol de administrador con más permisos | admin role desc |
| Members can only view resources | Los miembros sólo pueden ver los recursos | member role desc |
##### Invite User popup
| EN | ES | Notes |
| ----------------- | ------------------------------------------------------- | ----------- |
| Invite User | Invitar usuario | |
| Email | Email | |
| Enter an email | Introduzca un email | placeholder |
| Role | Rol | |
| Select role | Seleccionar rol | placeholder |
| Gültig für | Válido para | |
| 1 day | 1 día | |
| 2 days | 2 días | |
| 3 days | 3 días | |
| 4 days | 4 días | |
| 5 days | 5 días | |
| 6 days | 6 días | |
| 7 days | 7 días | |
| Create Invitation | Crear invitación | |
| Close | Cerrar | |
## Main “Shareable Links”
##### “Hero” section
| EN | ES | Notes |
| ------------------------------------------------------------ | ------------------------------------------------------------ | ----- |
| Shareable Links | Enlaces para compartir | |
| Create shareable links to your resources. Links provide temporary or unlimited access to your resource. You can configure the expiration duration of the link when you create one. | Crear enlaces que se puedan compartir a tus recursos. Los enlaces proporcionan acceso temporal o ilimitado a tu recurso. Puedes configurar la duración de caducidad del enlace cuando lo creas. | |
| Easy to create and share | Fácil de crear y compartir | |
| Configurable expiration duration | Duración de expiración configurable | |
| Secure and revocable | Seguro y revocable | |
##### Content
| EN | ES | Notes |
| ------------------------------------------------------------ | ------------------------------------------------------------ | ----------------- |
| Manage Shareable Links | Administrar enlaces compartibles | |
| Create shareable links to grant temporary or permanent access to your resources | Crear enlaces compartibles para otorgar acceso temporal o permanente a tus recursos | |
| Search links | Buscar enlaces | placeholder |
| Create Share Link | Crear enlace para compartir | addbutton |
| Resource | Recurso | table header |
| Title | Título | table header |
| Created | Creado | table header |
| Expires | Caduca | table header |
| No links. Create one to get started. | No hay enlaces. Crea uno para comenzar. | table placeholder |
##### Create Shareable Link popup
| EN | ES | Notes |
| ------------------------------------------------------------ | ------------------------------------------------------------ | ----------------------- |
| Create Shareable Link | Crear un enlace para compartir | |
| Anyone with this link can access the resource | Cualquier persona con este enlace puede acceder al recurso. | |
| Resource | Recurso | |
| Select resource | Seleccionar recurso | |
| Search resources… | Buscar recursos… | resource selector popup |
| Title (optional) | Título (opcional) | |
| Enter title | Introducir título | placeholder |
| Expire in | Caduca en | |
| Minutes | Minutos | |
| Hours | Horas | |
| Days | Días | |
| Months | Meses | |
| Years | Años | |
| Never expire | Nunca caduca | |
| Expiration time is how long the link will be usable and provide access to the resource. After this time, the link will no longer work, and users who used this link will lose access to the resource. | El tiempo de expiración es el tiempo durante el cual el enlace se podrá utilizar y brindará acceso al recurso. Después de este tiempo, el enlace dejará de funcionar y los usuarios que lo hayan utilizado perderán el acceso al recurso. | |
| Create Link | Crear enlace | |
| Close | Cerrar | |
## Main “General”
| EN | ES | Notes |
| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------ |
| General | General | |
| Configure your organizations general settings | Configura los ajustes generales de tu organización | |
| General | General | sidebar item |
| Organization Settings | Configuración de la organización | |
| Manage your organization details and configuration | Administra los detalles y la configuración de tu organización| |
| Name | Nombre | |
| This is the display name of the org | Este es el nombre para mostrar de la organización. | |
| Save Settings | Guardar configuración | |
| Danger Zone | Zona de peligro | |
| Once you delete this org, there is no going back. Please be certain. | Una vez que elimines esta organización, no habrá vuelta atrás. Asegúrate de hacerlo. | |
| Delete Organization Data | Eliminar datos de la organización | |

View File

@@ -2,7 +2,8 @@
const nextConfig = {
eslint: {
ignoreDuringBuilds: true,
}
},
output: "standalone"
};
export default nextConfig;

14861
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,9 @@
import fs from "fs";
import yaml from "js-yaml";
import path from "path";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import {
__DIRNAME,
APP_PATH,
APP_VERSION,
configFilePath1,
configFilePath2
@@ -14,12 +12,6 @@ import { passwordSchema } from "@server/auth/passwordSchema";
import stoi from "./stoi";
const portSchema = z.number().positive().gt(0).lte(65535);
// const hostnameSchema = z
// .string()
// .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]?)$|^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$/
// )
// .or(z.literal("localhost"));
const getEnvOrYaml = (envVar: string) => (valFromYaml: any) => {
return process.env[envVar] ?? valFromYaml;
@@ -31,7 +23,6 @@ const configSchema = z.object({
.string()
.url()
.optional()
.transform(getEnvOrYaml("APP_DASHBOARDURL"))
.pipe(z.string().url())
.transform((url) => url.toLowerCase()),
log_level: z.enum(["debug", "info", "warn", "error"]),
@@ -63,37 +54,11 @@ const configSchema = z.object({
{
message: "At least one domain must be defined"
}
)
.refine(
(domains) => {
const envBaseDomain = process.env.APP_BASE_DOMAIN;
if (envBaseDomain) {
return z.string().nonempty().safeParse(envBaseDomain).success;
}
return true;
},
{
message: "APP_BASE_DOMAIN must be a valid hostname"
}
),
server: z.object({
external_port: portSchema
.optional()
.transform(getEnvOrYaml("SERVER_EXTERNALPORT"))
.transform(stoi)
.pipe(portSchema),
internal_port: portSchema
.optional()
.transform(getEnvOrYaml("SERVER_INTERNALPORT"))
.transform(stoi)
.pipe(portSchema),
next_port: portSchema
.optional()
.transform(getEnvOrYaml("SERVER_NEXTPORT"))
.transform(stoi)
.pipe(portSchema),
external_port: portSchema.optional().transform(stoi).pipe(portSchema),
internal_port: portSchema.optional().transform(stoi).pipe(portSchema),
next_port: portSchema.optional().transform(stoi).pipe(portSchema),
internal_hostname: z.string().transform((url) => url.toLowerCase()),
session_cookie_name: z.string(),
resource_access_token_param: z.string(),
@@ -126,15 +91,10 @@ const configSchema = z.object({
additional_middlewares: z.array(z.string()).optional()
}),
gerbil: z.object({
start_port: portSchema
.optional()
.transform(getEnvOrYaml("GERBIL_STARTPORT"))
.transform(stoi)
.pipe(portSchema),
start_port: portSchema.optional().transform(stoi).pipe(portSchema),
base_endpoint: z
.string()
.optional()
.transform(getEnvOrYaml("GERBIL_BASEENDPOINT"))
.pipe(z.string())
.transform((url) => url.toLowerCase()),
use_subdomain: z.boolean(),
@@ -197,10 +157,6 @@ export class Config {
constructor() {
this.loadConfig();
if (process.env.GENERATE_TRAEFIK_CONFIG === "true") {
this.createTraefikConfig();
}
}
public loadConfig() {
@@ -225,45 +181,15 @@ export class Config {
} else if (fs.existsSync(configFilePath2)) {
environment = loadConfig(configFilePath2);
}
if (!environment) {
const exampleConfigPath = path.join(
__DIRNAME,
"config.example.yml"
);
if (fs.existsSync(exampleConfigPath)) {
try {
const exampleConfigContent = fs.readFileSync(
exampleConfigPath,
"utf8"
);
fs.writeFileSync(
configFilePath1,
exampleConfigContent,
"utf8"
);
environment = loadConfig(configFilePath1);
} catch (error) {
console.log(
"See the docs for information about what to include in the configuration file: https://docs.fossorial.io/Pangolin/Configuration/config"
);
if (error instanceof Error) {
throw new Error(
`Error creating configuration file from example: ${
error.message
}`
);
}
throw error;
}
} else {
throw new Error(
"No configuration file found and no example configuration available"
);
}
if (process.env.APP_BASE_DOMAIN) {
console.log("You're using deprecated environment variables. Transition to the configuration file. https://docs.fossorial.io/");
}
if (!environment) {
throw new Error("No configuration file found");
throw new Error(
"No configuration file found. Please create one. https://docs.fossorial.io/"
);
}
const parsedConfig = configSchema.safeParse(environment);
@@ -309,17 +235,6 @@ export class Config {
: "false";
process.env.DASHBOARD_URL = parsedConfig.data.app.dashboard_url;
if (process.env.APP_BASE_DOMAIN) {
console.log(
`DEPRECATED! APP_BASE_DOMAIN is deprecated and will be removed in a future release. Use the domains section in the configuration file instead. See https://docs.fossorial.io/Pangolin/Configuration/config for more information.`
);
parsedConfig.data.domains.domain1 = {
base_domain: process.env.APP_BASE_DOMAIN,
cert_resolver: "letsencrypt"
};
}
this.rawConfig = parsedConfig.data;
}
@@ -336,72 +251,6 @@ export class Config {
public getDomain(domainId: string) {
return this.rawConfig.domains[domainId];
}
private createTraefikConfig() {
try {
// check if traefik_config.yml and dynamic_config.yml exists in APP_PATH/traefik
const defaultTraefikConfigPath = path.join(
__DIRNAME,
"traefik_config.example.yml"
);
const defaultDynamicConfigPath = path.join(
__DIRNAME,
"dynamic_config.example.yml"
);
const traefikPath = path.join(APP_PATH, "traefik");
if (!fs.existsSync(traefikPath)) {
return;
}
// load default configs
let traefikConfig = fs.readFileSync(
defaultTraefikConfigPath,
"utf8"
);
let dynamicConfig = fs.readFileSync(
defaultDynamicConfigPath,
"utf8"
);
traefikConfig = traefikConfig
.split("{{.LetsEncryptEmail}}")
.join(this.rawConfig.users.server_admin.email);
traefikConfig = traefikConfig
.split("{{.INTERNAL_PORT}}")
.join(this.rawConfig.server.internal_port.toString());
dynamicConfig = dynamicConfig
.split("{{.DashboardDomain}}")
.join(new URL(this.rawConfig.app.dashboard_url).hostname);
dynamicConfig = dynamicConfig
.split("{{.NEXT_PORT}}")
.join(this.rawConfig.server.next_port.toString());
dynamicConfig = dynamicConfig
.split("{{.EXTERNAL_PORT}}")
.join(this.rawConfig.server.external_port.toString());
// write thiese to the traefik directory
const traefikConfigPath = path.join(
traefikPath,
"traefik_config.yml"
);
const dynamicConfigPath = path.join(
traefikPath,
"dynamic_config.yml"
);
fs.writeFileSync(traefikConfigPath, traefikConfig, "utf8");
fs.writeFileSync(dynamicConfigPath, dynamicConfig, "utf8");
console.log("Traefik configuration files created");
} catch (e) {
console.log(
"Failed to generate the Traefik configuration files. Please create them manually."
);
console.error(e);
}
}
}
export const config = new Config();

View File

@@ -1,61 +1,5 @@
import { cidrToRange, findNextAvailableCidr } from "./ip";
/**
* Compares two objects for deep equality
* @param actual The actual value to test
* @param expected The expected value to compare against
* @param message The message to display if assertion fails
* @throws Error if objects are not equal
*/
export function assertEqualsObj<T>(actual: T, expected: T, message: string): void {
const actualStr = JSON.stringify(actual);
const expectedStr = JSON.stringify(expected);
if (actualStr !== expectedStr) {
throw new Error(`${message}\nExpected: ${expectedStr}\nActual: ${actualStr}`);
}
}
/**
* Compares two primitive values for equality
* @param actual The actual value to test
* @param expected The expected value to compare against
* @param message The message to display if assertion fails
* @throws Error if values are not equal
*/
export function assertEquals<T>(actual: T, expected: T, message: string): void {
if (actual !== expected) {
throw new Error(`${message}\nExpected: ${expected}\nActual: ${actual}`);
}
}
/**
* Tests if a function throws an expected error
* @param fn The function to test
* @param expectedError The expected error message or part of it
* @param message The message to display if assertion fails
* @throws Error if function doesn't throw or throws unexpected error
*/
export function assertThrows(
fn: () => void,
expectedError: string,
message: string
): void {
try {
fn();
throw new Error(`${message}: Expected to throw "${expectedError}"`);
} catch (error) {
if (!(error instanceof Error)) {
throw new Error(`${message}\nUnexpected error type: ${typeof error}`);
}
if (!error.message.includes(expectedError)) {
throw new Error(
`${message}\nExpected error: ${expectedError}\nActual error: ${error.message}`
);
}
}
}
import { assertEquals } from "@test/assert";
// Test cases
function testFindNextAvailableCidr() {

View File

@@ -0,0 +1,71 @@
import { isValidUrlGlobPattern } from "./validators";
import { assertEquals } from "@test/assert";
function runTests() {
console.log('Running URL pattern validation tests...');
// Test valid patterns
assertEquals(isValidUrlGlobPattern('simple'), true, 'Simple path segment should be valid');
assertEquals(isValidUrlGlobPattern('simple/path'), true, 'Simple path with slash should be valid');
assertEquals(isValidUrlGlobPattern('/leading/slash'), true, 'Path with leading slash should be valid');
assertEquals(isValidUrlGlobPattern('path/'), true, 'Path with trailing slash should be valid');
assertEquals(isValidUrlGlobPattern('path/*'), true, 'Path with wildcard segment should be valid');
assertEquals(isValidUrlGlobPattern('*'), true, 'Single wildcard should be valid');
assertEquals(isValidUrlGlobPattern('*/subpath'), true, 'Wildcard with subpath should be valid');
assertEquals(isValidUrlGlobPattern('path/*/more'), true, 'Path with wildcard in the middle should be valid');
// Test with special characters
assertEquals(isValidUrlGlobPattern('path-with-dash'), true, 'Path with dash should be valid');
assertEquals(isValidUrlGlobPattern('path_with_underscore'), true, 'Path with underscore should be valid');
assertEquals(isValidUrlGlobPattern('path.with.dots'), true, 'Path with dots should be valid');
assertEquals(isValidUrlGlobPattern('path~with~tilde'), true, 'Path with tilde should be valid');
assertEquals(isValidUrlGlobPattern('path!with!exclamation'), true, 'Path with exclamation should be valid');
assertEquals(isValidUrlGlobPattern('path$with$dollar'), true, 'Path with dollar should be valid');
assertEquals(isValidUrlGlobPattern('path&with&ampersand'), true, 'Path with ampersand should be valid');
assertEquals(isValidUrlGlobPattern("path'with'quote"), true, "Path with quote should be valid");
assertEquals(isValidUrlGlobPattern('path(with)parentheses'), true, 'Path with parentheses should be valid');
assertEquals(isValidUrlGlobPattern('path+with+plus'), true, 'Path with plus should be valid');
assertEquals(isValidUrlGlobPattern('path,with,comma'), true, 'Path with comma should be valid');
assertEquals(isValidUrlGlobPattern('path;with;semicolon'), true, 'Path with semicolon should be valid');
assertEquals(isValidUrlGlobPattern('path=with=equals'), true, 'Path with equals should be valid');
assertEquals(isValidUrlGlobPattern('path:with:colon'), true, 'Path with colon should be valid');
assertEquals(isValidUrlGlobPattern('path@with@at'), true, 'Path with at should be valid');
// Test with percent encoding
assertEquals(isValidUrlGlobPattern('path%20with%20spaces'), true, 'Path with percent-encoded spaces should be valid');
assertEquals(isValidUrlGlobPattern('path%2Fwith%2Fencoded%2Fslashes'), true, 'Path with percent-encoded slashes should be valid');
// Test with wildcards in segments (the fixed functionality)
assertEquals(isValidUrlGlobPattern('padbootstrap*'), true, 'Path with wildcard at the end of segment should be valid');
assertEquals(isValidUrlGlobPattern('pad*bootstrap'), true, 'Path with wildcard in the middle of segment should be valid');
assertEquals(isValidUrlGlobPattern('*bootstrap'), true, 'Path with wildcard at the start of segment should be valid');
assertEquals(isValidUrlGlobPattern('multiple*wildcards*in*segment'), true, 'Path with multiple wildcards in segment should be valid');
assertEquals(isValidUrlGlobPattern('wild*/cards/in*/different/seg*ments'), true, 'Path with wildcards in different segments should be valid');
// Test invalid patterns
assertEquals(isValidUrlGlobPattern(''), false, 'Empty string should be invalid');
assertEquals(isValidUrlGlobPattern('//double/slash'), false, 'Path with double slash should be invalid');
assertEquals(isValidUrlGlobPattern('path//end'), false, 'Path with double slash in the middle should be invalid');
assertEquals(isValidUrlGlobPattern('invalid<char>'), false, 'Path with invalid characters should be invalid');
assertEquals(isValidUrlGlobPattern('invalid|char'), false, 'Path with invalid pipe character should be invalid');
assertEquals(isValidUrlGlobPattern('invalid"char'), false, 'Path with invalid quote character should be invalid');
assertEquals(isValidUrlGlobPattern('invalid`char'), false, 'Path with invalid backtick character should be invalid');
assertEquals(isValidUrlGlobPattern('invalid^char'), false, 'Path with invalid caret character should be invalid');
assertEquals(isValidUrlGlobPattern('invalid\\char'), false, 'Path with invalid backslash character should be invalid');
assertEquals(isValidUrlGlobPattern('invalid[char]'), false, 'Path with invalid square brackets should be invalid');
assertEquals(isValidUrlGlobPattern('invalid{char}'), false, 'Path with invalid curly braces should be invalid');
// Test invalid percent encoding
assertEquals(isValidUrlGlobPattern('invalid%2'), false, 'Path with incomplete percent encoding should be invalid');
assertEquals(isValidUrlGlobPattern('invalid%GZ'), false, 'Path with invalid hex in percent encoding should be invalid');
assertEquals(isValidUrlGlobPattern('invalid%'), false, 'Path with isolated percent sign should be invalid');
console.log('All tests passed!');
}
// Run all tests
try {
runTests();
} catch (error) {
console.error('Test failed:', error);
}

View File

@@ -29,11 +29,6 @@ export function isValidUrlGlobPattern(pattern: string): boolean {
return false;
}
// If segment contains *, it must be exactly *
if (segment.includes("*") && segment !== "*") {
return false;
}
// Check each character in the segment
for (let j = 0; j < segment.length; j++) {
const char = segment[j];

View File

@@ -5,7 +5,8 @@ import {
resources,
userResources,
roleResources,
resourceAccessToken
resourceAccessToken,
sites
} from "@server/db/schema";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
@@ -59,7 +60,8 @@ function queryAccessTokens(
title: resourceAccessToken.title,
description: resourceAccessToken.description,
createdAt: resourceAccessToken.createdAt,
resourceName: resources.name
resourceName: resources.name,
siteName: sites.name
};
if (orgId) {
@@ -70,6 +72,10 @@ function queryAccessTokens(
resources,
eq(resourceAccessToken.resourceId, resources.resourceId)
)
.leftJoin(
sites,
eq(resources.resourceId, sites.siteId)
)
.where(
and(
inArray(
@@ -91,6 +97,10 @@ function queryAccessTokens(
resources,
eq(resourceAccessToken.resourceId, resources.resourceId)
)
.leftJoin(
sites,
eq(resources.resourceId, sites.siteId)
)
.where(
and(
inArray(

View File

@@ -78,7 +78,7 @@ export async function login(
}
return next(
createHttpError(
HttpCode.BAD_REQUEST,
HttpCode.UNAUTHORIZED,
"Username or password is incorrect"
)
);
@@ -98,7 +98,7 @@ export async function login(
}
return next(
createHttpError(
HttpCode.BAD_REQUEST,
HttpCode.UNAUTHORIZED,
"Username or password is incorrect"
)
);
@@ -129,7 +129,7 @@ export async function login(
}
return next(
createHttpError(
HttpCode.BAD_REQUEST,
HttpCode.UNAUTHORIZED,
"The two-factor code you entered is incorrect"
)
);

View File

@@ -0,0 +1,67 @@
import { isPathAllowed } from './verifySession';
import { assertEquals } from '@test/assert';
function runTests() {
console.log('Running path matching tests...');
// Test exact matching
assertEquals(isPathAllowed('foo', 'foo'), true, 'Exact match should be allowed');
assertEquals(isPathAllowed('foo', 'bar'), false, 'Different segments should not match');
assertEquals(isPathAllowed('foo/bar', 'foo/bar'), true, 'Exact multi-segment match should be allowed');
assertEquals(isPathAllowed('foo/bar', 'foo/baz'), false, 'Partial multi-segment match should not be allowed');
// Test with leading and trailing slashes
assertEquals(isPathAllowed('/foo', 'foo'), true, 'Pattern with leading slash should match');
assertEquals(isPathAllowed('foo/', 'foo'), true, 'Pattern with trailing slash should match');
assertEquals(isPathAllowed('/foo/', 'foo'), true, 'Pattern with both leading and trailing slashes should match');
assertEquals(isPathAllowed('foo', '/foo/'), true, 'Path with leading and trailing slashes should match');
// Test simple wildcard matching
assertEquals(isPathAllowed('*', 'foo'), true, 'Single wildcard should match any single segment');
assertEquals(isPathAllowed('*', 'foo/bar'), true, 'Single wildcard should match multiple segments');
assertEquals(isPathAllowed('*/bar', 'foo/bar'), true, 'Wildcard prefix should match');
assertEquals(isPathAllowed('foo/*', 'foo/bar'), true, 'Wildcard suffix should match');
assertEquals(isPathAllowed('foo/*/baz', 'foo/bar/baz'), true, 'Wildcard in middle should match');
// Test multiple wildcards
assertEquals(isPathAllowed('*/*', 'foo/bar'), true, 'Multiple wildcards should match corresponding segments');
assertEquals(isPathAllowed('*/*/*', 'foo/bar/baz'), true, 'Three wildcards should match three segments');
assertEquals(isPathAllowed('foo/*/*', 'foo/bar/baz'), true, 'Specific prefix with wildcards should match');
assertEquals(isPathAllowed('*/*/baz', 'foo/bar/baz'), true, 'Wildcards with specific suffix should match');
// Test wildcard consumption behavior
assertEquals(isPathAllowed('*', ''), true, 'Wildcard should optionally consume segments');
assertEquals(isPathAllowed('foo/*', 'foo'), true, 'Trailing wildcard should be optional');
assertEquals(isPathAllowed('*/*', 'foo'), true, 'Multiple wildcards can match fewer segments');
assertEquals(isPathAllowed('*/*/*', 'foo/bar'), true, 'Extra wildcards can be skipped');
// Test complex nested paths
assertEquals(isPathAllowed('api/*/users', 'api/v1/users'), true, 'API versioning pattern should match');
assertEquals(isPathAllowed('api/*/users/*', 'api/v1/users/123'), true, 'API resource pattern should match');
assertEquals(isPathAllowed('api/*/users/*/profile', 'api/v1/users/123/profile'), true, 'Nested API pattern should match');
// Test for the requested padbootstrap* pattern
assertEquals(isPathAllowed('padbootstrap*', 'padbootstrap'), true, 'padbootstrap* should match padbootstrap');
assertEquals(isPathAllowed('padbootstrap*', 'padbootstrapv1'), true, 'padbootstrap* should match padbootstrapv1');
assertEquals(isPathAllowed('padbootstrap*', 'padbootstrap/files'), false, 'padbootstrap* should not match padbootstrap/files');
assertEquals(isPathAllowed('padbootstrap*/*', 'padbootstrap/files'), true, 'padbootstrap*/* should match padbootstrap/files');
assertEquals(isPathAllowed('padbootstrap*/files', 'padbootstrapv1/files'), true, 'padbootstrap*/files should not match padbootstrapv1/files (wildcard is segment-based, not partial)');
// Test wildcard edge cases
assertEquals(isPathAllowed('*/*/*/*/*/*', 'a/b'), true, 'Many wildcards can match few segments');
assertEquals(isPathAllowed('a/*/b/*/c', 'a/anything/b/something/c'), true, 'Multiple wildcards in pattern should match corresponding segments');
// Test patterns with partial segment matches
assertEquals(isPathAllowed('padbootstrap*', 'padbootstrap-123'), true, 'Wildcards in isPathAllowed should be segment-based, not character-based');
assertEquals(isPathAllowed('test*', 'testuser'), true, 'Asterisk as part of segment name is treated as a literal, not a wildcard');
assertEquals(isPathAllowed('my*app', 'myapp'), true, 'Asterisk in middle of segment name is treated as a literal, not a wildcard');
console.log('All tests passed!');
}
// Run all tests
try {
runTests();
} catch (error) {
console.error('Test failed:', error);
}

View File

@@ -534,7 +534,7 @@ async function checkRules(
return;
}
function isPathAllowed(pattern: string, path: string): boolean {
export function isPathAllowed(pattern: string, path: string): boolean {
logger.debug(`\nMatching path "${path}" against pattern "${pattern}"`);
// Normalize and split paths into segments
@@ -575,7 +575,7 @@ function isPathAllowed(pattern: string, path: string): boolean {
return result;
}
// For wildcards, try consuming different numbers of path segments
// For full segment wildcards, try consuming different numbers of path segments
if (currentPatternPart === "*") {
logger.debug(
`${indent}Found wildcard at pattern index ${patternIndex}`
@@ -607,6 +607,32 @@ function isPathAllowed(pattern: string, path: string): boolean {
return false;
}
// Check for in-segment wildcard (e.g., "prefix*" or "prefix*suffix")
if (currentPatternPart.includes("*")) {
logger.debug(
`${indent}Found in-segment wildcard in "${currentPatternPart}"`
);
// Convert the pattern segment to a regex pattern
const regexPattern = currentPatternPart
.replace(/\*/g, ".*") // Replace * with .* for regex wildcard
.replace(/\?/g, "."); // Replace ? with . for single character wildcard if needed
const regex = new RegExp(`^${regexPattern}$`);
if (regex.test(currentPathPart)) {
logger.debug(
`${indent}Segment with wildcard matches: "${currentPatternPart}" matches "${currentPathPart}"`
);
return matchSegments(patternIndex + 1, pathIndex + 1);
}
logger.debug(
`${indent}Segment with wildcard mismatch: "${currentPatternPart}" doesn't match "${currentPathPart}"`
);
return false;
}
// For regular segments, they must match exactly
if (currentPatternPart !== currentPathPart) {
logger.debug(
@@ -625,4 +651,4 @@ function isPathAllowed(pattern: string, path: string): boolean {
const result = matchSegments(0, 0);
logger.debug(`Final result: ${result}`);
return result;
}
}

View File

@@ -7,7 +7,7 @@ import {
Target,
targets
} from "@server/db/schema";
import { eq, and, sql } from "drizzle-orm";
import { eq, and, sql, inArray } from "drizzle-orm";
import { addPeer, deletePeer } from "../gerbil/peers";
import logger from "@server/logger";
@@ -75,68 +75,84 @@ export const handleRegisterMessage: MessageHandler = async (context) => {
allowedIps: [site.subnet]
});
const allResources = await db
.select({
// Resource fields
resourceId: resources.resourceId,
subdomain: resources.subdomain,
fullDomain: resources.fullDomain,
ssl: resources.ssl,
blockAccess: resources.blockAccess,
sso: resources.sso,
emailWhitelistEnabled: resources.emailWhitelistEnabled,
http: resources.http,
proxyPort: resources.proxyPort,
protocol: resources.protocol,
// Targets as a subquery
targets: sql<string>`json_group_array(json_object(
'targetId', ${targets.targetId},
'ip', ${targets.ip},
'method', ${targets.method},
'port', ${targets.port},
'internalPort', ${targets.internalPort},
'enabled', ${targets.enabled}
))`.as("targets")
})
.from(resources)
.leftJoin(
targets,
and(
eq(targets.resourceId, resources.resourceId),
eq(targets.enabled, true)
// Improved version
const allResources = await db.transaction(async (tx) => {
// First get all resources for the site
const resourcesList = await tx
.select({
resourceId: resources.resourceId,
subdomain: resources.subdomain,
fullDomain: resources.fullDomain,
ssl: resources.ssl,
blockAccess: resources.blockAccess,
sso: resources.sso,
emailWhitelistEnabled: resources.emailWhitelistEnabled,
http: resources.http,
proxyPort: resources.proxyPort,
protocol: resources.protocol
})
.from(resources)
.where(eq(resources.siteId, siteId));
// Get all enabled targets for these resources in a single query
const resourceIds = resourcesList.map((r) => r.resourceId);
const allTargets =
resourceIds.length > 0
? await tx
.select({
resourceId: targets.resourceId,
targetId: targets.targetId,
ip: targets.ip,
method: targets.method,
port: targets.port,
internalPort: targets.internalPort,
enabled: targets.enabled
})
.from(targets)
.where(
and(
inArray(targets.resourceId, resourceIds),
eq(targets.enabled, true)
)
)
: [];
// Combine the data in JS instead of using SQL for the JSON
return resourcesList.map((resource) => ({
...resource,
targets: allTargets.filter(
(target) => target.resourceId === resource.resourceId
)
)
.where(eq(resources.siteId, siteId))
.groupBy(resources.resourceId);
}));
});
let tcpTargets: string[] = [];
let udpTargets: string[] = [];
const { tcpTargets, udpTargets } = allResources.reduce(
(acc, resource) => {
// Skip resources with no targets
if (!resource.targets?.length) return acc;
for (const resource of allResources) {
const targets = JSON.parse(resource.targets);
if (!targets || targets.length === 0) {
continue;
}
if (resource.protocol === "tcp") {
tcpTargets = tcpTargets.concat(
targets.map(
// Format valid targets into strings
const formattedTargets = resource.targets
.filter(
(target: Target) =>
`${
target.internalPort ? target.internalPort + ":" : ""
}${target.ip}:${target.port}`
target?.internalPort && target?.ip && target?.port
)
);
} else {
udpTargets = tcpTargets.concat(
targets.map(
.map(
(target: Target) =>
`${
target.internalPort ? target.internalPort + ":" : ""
}${target.ip}:${target.port}`
)
);
}
}
`${target.internalPort}:${target.ip}:${target.port}`
);
// Add to the appropriate protocol array
if (resource.protocol === "tcp") {
acc.tcpTargets.push(...formattedTargets);
} else {
acc.udpTargets.push(...formattedTargets);
}
return acc;
},
{ tcpTargets: [] as string[], udpTargets: [] as string[] }
);
return {
message: {

View File

@@ -1,7 +1,7 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { Resource, resources } from "@server/db/schema";
import { Resource, resources, sites } from "@server/db/schema";
import { eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
@@ -18,7 +18,9 @@ const getResourceSchema = z
})
.strict();
export type GetResourceResponse = Resource;
export type GetResourceResponse = Resource & {
siteName: string;
};
export async function getResource(
req: Request,
@@ -38,13 +40,17 @@ export async function getResource(
const { resourceId } = parsedParams.data;
const resource = await db
const [resp] = await db
.select()
.from(resources)
.where(eq(resources.resourceId, resourceId))
.leftJoin(sites, eq(sites.siteId, resources.siteId))
.limit(1);
if (resource.length === 0) {
const resource = resp.resources;
const site = resp.sites;
if (!resource) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
@@ -54,7 +60,10 @@ export async function getResource(
}
return response(res, {
data: resource[0],
data: {
...resource,
siteName: site?.name
},
success: true,
error: false,
message: "Resource retrieved successfully",

View File

@@ -215,8 +215,13 @@ async function updateHttpResource(
.from(domains)
.where(eq(domains.domainId, domainId));
const isBaseDomain =
updateData.isBaseDomain !== undefined
? updateData.isBaseDomain
: resource.isBaseDomain;
let fullDomain: string | null = null;
if (updateData.isBaseDomain) {
if (isBaseDomain) {
fullDomain = domain.baseDomain;
} else if (subdomain && domain) {
fullDomain = `${subdomain}.${domain.baseDomain}`;

View File

@@ -1,6 +1,6 @@
import { Request, Response } from "express";
import db from "@server/db";
import { and, eq } from "drizzle-orm";
import { and, eq, inArray } from "drizzle-orm";
import logger from "@server/logger";
import HttpCode from "@server/types/HttpCode";
import config from "@server/lib/config";
@@ -12,52 +12,79 @@ export async function traefikConfigProvider(
res: Response
): Promise<any> {
try {
const allResources = await db
.select({
// Resource fields
resourceId: resources.resourceId,
subdomain: resources.subdomain,
fullDomain: resources.fullDomain,
ssl: resources.ssl,
blockAccess: resources.blockAccess,
sso: resources.sso,
emailWhitelistEnabled: resources.emailWhitelistEnabled,
http: resources.http,
proxyPort: resources.proxyPort,
protocol: resources.protocol,
isBaseDomain: resources.isBaseDomain,
domainId: resources.domainId,
// Site fields
site: {
siteId: sites.siteId,
type: sites.type,
subnet: sites.subnet
},
// Org fields
org: {
orgId: orgs.orgId
},
// Targets as a subquery
targets: sql<string>`json_group_array(json_object(
'targetId', ${targets.targetId},
'ip', ${targets.ip},
'method', ${targets.method},
'port', ${targets.port},
'internalPort', ${targets.internalPort},
'enabled', ${targets.enabled}
))`.as("targets")
})
.from(resources)
.innerJoin(sites, eq(sites.siteId, resources.siteId))
.innerJoin(orgs, eq(resources.orgId, orgs.orgId))
.leftJoin(
targets,
and(
eq(targets.resourceId, resources.resourceId),
eq(targets.enabled, true)
)
)
.groupBy(resources.resourceId);
// Get all resources with related data
const allResources = await db.transaction(async (tx) => {
// First query to get resources with site and org info
const resourcesWithRelations = await tx
.select({
// Resource fields
resourceId: resources.resourceId,
subdomain: resources.subdomain,
fullDomain: resources.fullDomain,
ssl: resources.ssl,
blockAccess: resources.blockAccess,
sso: resources.sso,
emailWhitelistEnabled: resources.emailWhitelistEnabled,
http: resources.http,
proxyPort: resources.proxyPort,
protocol: resources.protocol,
isBaseDomain: resources.isBaseDomain,
domainId: resources.domainId,
// Site fields
site: {
siteId: sites.siteId,
type: sites.type,
subnet: sites.subnet
},
// Org fields
org: {
orgId: orgs.orgId
}
})
.from(resources)
.innerJoin(sites, eq(sites.siteId, resources.siteId))
.innerJoin(orgs, eq(resources.orgId, orgs.orgId));
// Get all resource IDs from the first query
const resourceIds = resourcesWithRelations.map((r) => r.resourceId);
// Second query to get all enabled targets for these resources
const allTargets =
resourceIds.length > 0
? await tx
.select({
resourceId: targets.resourceId,
targetId: targets.targetId,
ip: targets.ip,
method: targets.method,
port: targets.port,
internalPort: targets.internalPort,
enabled: targets.enabled
})
.from(targets)
.where(
and(
inArray(targets.resourceId, resourceIds),
eq(targets.enabled, true)
)
)
: [];
// Create a map for fast target lookup by resourceId
const targetsMap = allTargets.reduce((map, target) => {
if (!map.has(target.resourceId)) {
map.set(target.resourceId, []);
}
map.get(target.resourceId).push(target);
return map;
}, new Map());
// Combine the data
return resourcesWithRelations.map((resource) => ({
...resource,
targets: targetsMap.get(resource.resourceId) || []
}));
});
if (!allResources.length) {
return res.status(HttpCode.OK).json({});
@@ -101,7 +128,7 @@ export async function traefikConfigProvider(
};
for (const resource of allResources) {
const targets = JSON.parse(resource.targets);
const targets = resource.targets as Target[];
const site = resource.site;
const org = resource.org;

View File

@@ -18,7 +18,7 @@ export async function clearStaleData() {
.delete(sessions)
.where(lt(sessions.expiresAt, new Date().getTime()));
} catch (e) {
logger.error("Error clearing expired sessions:", e);
logger.warn("Error clearing expired sessions:", e);
}
try {
@@ -26,7 +26,7 @@ export async function clearStaleData() {
.delete(newtSessions)
.where(lt(newtSessions.expiresAt, new Date().getTime()));
} catch (e) {
logger.error("Error clearing expired newtSessions:", e);
logger.warn("Error clearing expired newtSessions:", e);
}
try {
@@ -34,7 +34,7 @@ export async function clearStaleData() {
.delete(emailVerificationCodes)
.where(lt(emailVerificationCodes.expiresAt, new Date().getTime()));
} catch (e) {
logger.error("Error clearing expired emailVerificationCodes:", e);
logger.warn("Error clearing expired emailVerificationCodes:", e);
}
try {
@@ -42,7 +42,7 @@ export async function clearStaleData() {
.delete(passwordResetTokens)
.where(lt(passwordResetTokens.expiresAt, new Date().getTime()));
} catch (e) {
logger.error("Error clearing expired passwordResetTokens:", e);
logger.warn("Error clearing expired passwordResetTokens:", e);
}
try {
@@ -50,7 +50,7 @@ export async function clearStaleData() {
.delete(userInvites)
.where(lt(userInvites.expiresAt, new Date().getTime()));
} catch (e) {
logger.error("Error clearing expired userInvites:", e);
logger.warn("Error clearing expired userInvites:", e);
}
try {
@@ -58,7 +58,7 @@ export async function clearStaleData() {
.delete(resourceAccessToken)
.where(lt(resourceAccessToken.expiresAt, new Date().getTime()));
} catch (e) {
logger.error("Error clearing expired resourceAccessToken:", e);
logger.warn("Error clearing expired resourceAccessToken:", e);
}
try {
@@ -66,7 +66,7 @@ export async function clearStaleData() {
.delete(resourceSessions)
.where(lt(resourceSessions.expiresAt, new Date().getTime()));
} catch (e) {
logger.error("Error clearing expired resourceSessions:", e);
logger.warn("Error clearing expired resourceSessions:", e);
}
try {
@@ -74,6 +74,6 @@ export async function clearStaleData() {
.delete(resourceOtp)
.where(lt(resourceOtp.expiresAt, new Date().getTime()));
} catch (e) {
logger.error("Error clearing expired resourceOtp:", e);
logger.warn("Error clearing expired resourceOtp:", e);
}
}

View File

@@ -40,9 +40,6 @@ const migrations = [
await run();
async function run() {
// backup the database
backupDb();
// run the migrations
await runMigrations();
}
@@ -127,6 +124,11 @@ async function executeScripts() {
console.log(`Running migration ${migration.version}`);
try {
if (!process.env.DISABLE_BACKUP_ON_MIGRATION) {
// Backup the database before running the migration
backupDb();
}
await migration.run();
// Update version in database

View File

@@ -1,7 +1,7 @@
"use client";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { InfoIcon, ShieldCheck, ShieldOff } from "lucide-react";
import { ArrowRight, InfoIcon, ShieldCheck, ShieldOff } from "lucide-react";
import { useResourceContext } from "@app/hooks/useResourceContext";
import { Separator } from "@app/components/ui/separator";
import CopyToClipboard from "@app/components/CopyToClipboard";
@@ -11,6 +11,7 @@ import {
InfoSections,
InfoSectionTitle
} from "@app/components/InfoSection";
import Link from "next/link";
type ResourceInfoBoxType = {};
@@ -26,7 +27,7 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
Resource Information
</AlertTitle>
<AlertDescription className="mt-4">
<InfoSections>
<InfoSections cols={3}>
{resource.http ? (
<>
<InfoSection>
@@ -40,22 +41,16 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
authInfo.whitelist ? (
<div className="flex items-start space-x-2 text-green-500">
<ShieldCheck className="w-4 h-4 mt-0.5" />
<span>
This resource is protected with
at least one authentication method.
</span>
<span>Protected</span>
</div>
) : (
<div className="flex items-center space-x-2 text-yellow-500">
<ShieldOff className="w-4 h-4" />
<span>
Anyone can access this resource.
</span>
<span>Not Protected</span>
</div>
)}
</InfoSectionContent>
</InfoSection>
<Separator orientation="vertical" />
<InfoSection>
<InfoSectionTitle>URL</InfoSectionTitle>
<InfoSectionContent>
@@ -65,6 +60,12 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
/>
</InfoSectionContent>
</InfoSection>
<InfoSection>
<InfoSectionTitle>Site</InfoSectionTitle>
<InfoSectionContent>
{resource.siteName}
</InfoSectionContent>
</InfoSection>
</>
) : (
<>
@@ -76,7 +77,6 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
</span>
</InfoSectionContent>
</InfoSection>
<Separator orientation="vertical" />
<InfoSection>
<InfoSectionTitle>Port</InfoSectionTitle>
<InfoSectionContent>

View File

@@ -104,8 +104,8 @@ export default function ReverseProxyTargets(props: {
resolver: zodResolver(addTargetSchema),
defaultValues: {
ip: "",
method: resource.http ? "http" : null
// protocol: "TCP",
method: resource.http ? "http" : null,
port: "" as any as number
} as z.infer<typeof addTargetSchema>
});
@@ -200,7 +200,11 @@ export default function ReverseProxyTargets(props: {
};
setTargets([...targets, newTarget]);
addTargetForm.reset();
addTargetForm.reset({
ip: "",
method: resource.http ? "http" : null,
port: "" as any as number
});
}
const removeTarget = (targetId: number) => {

View File

@@ -265,6 +265,12 @@ export default function GeneralForm() {
description: "The resource has been transferred successfully"
});
router.refresh();
updateResource({
siteName:
sites.find((site) => site.siteId === data.siteId)?.name ||
""
});
}
setTransferLoading(false);
}
@@ -606,9 +612,7 @@ export default function GeneralForm() {
</PopoverTrigger>
<PopoverContent className="w-full p-0">
<Command>
<CommandInput
placeholder="Search sites"
/>
<CommandInput placeholder="Search sites" />
<CommandEmpty>
No sites found.
</CommandEmpty>

View File

@@ -107,7 +107,12 @@ export default function CreateShareLinkForm({
const [isOpen, setIsOpen] = useState(false);
const [resources, setResources] = useState<
{ resourceId: number; name: string; resourceUrl: string }[]
{
resourceId: number;
name: string;
resourceUrl: string;
siteName: string | null;
}[]
>([]);
const timeUnits = [
@@ -159,7 +164,8 @@ export default function CreateShareLinkForm({
.map((r) => ({
resourceId: r.resourceId,
name: r.name,
resourceUrl: `${r.ssl ? "https://" : "http://"}${r.fullDomain}/`
resourceUrl: `${r.ssl ? "https://" : "http://"}${r.fullDomain}/`,
siteName: r.siteName
}))
);
}
@@ -231,19 +237,28 @@ export default function CreateShareLinkForm({
token.accessToken
);
setDirectLink(directLink);
const resource = resources.find((r) => r.resourceId === values.resourceId);
onCreated?.({
accessTokenId: token.accessTokenId,
resourceId: token.resourceId,
resourceName: values.resourceName,
title: token.title,
createdAt: token.createdAt,
expiresAt: token.expiresAt
expiresAt: token.expiresAt,
siteName: resource?.siteName || null,
});
}
setLoading(false);
}
function getSelectedResourceName(id: number) {
const resource = resources.find((r) => r.resourceId === id);
return `${resource?.name} ${resource?.siteName ? `(${resource.siteName})` : ""}`;
}
return (
<>
<Credenza
@@ -292,14 +307,9 @@ export default function CreateShareLinkForm({
)}
>
{field.value
? resources.find(
(
r
) =>
r.resourceId ===
field.value
? getSelectedResourceName(
field.value
)
?.name
: "Select resource"}
<CaretSortIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
@@ -348,9 +358,7 @@ export default function CreateShareLinkForm({
: "opacity-0"
)}
/>
{
r.name
}
{`${r.name} ${r.siteName ? `(${r.siteName})` : ""}`}
</CommandItem>
)
)}

View File

@@ -41,6 +41,7 @@ export type ShareLinkRow = {
title: string | null;
createdAt: number;
expiresAt: number | null;
siteName: string | null;
};
type ShareLinksTableProps = {
@@ -145,7 +146,8 @@ export default function ShareLinksTable({
return (
<Link href={`/${orgId}/settings/resources/${r.resourceId}`}>
<Button variant="outline">
{r.resourceName}
{r.resourceName}{" "}
{r.siteName ? `(${r.siteName})` : ""}
<ArrowUpRight className="ml-2 h-4 w-4" />
</Button>
</Link>
@@ -274,20 +276,21 @@ export default function ShareLinksTable({
return "Never";
}
},
{
{
id: "delete",
cell: ({ row }) => (
<div className="flex items-center justify-end space-x-2">
<Button
variant="outlinePrimary"
onClick={() => deleteSharelink(row.original.accessTokenId)}
onClick={() =>
deleteSharelink(row.original.accessTokenId)
}
>
Delete
</Button>
</div>
)
}
];
return (

View File

@@ -3,7 +3,6 @@
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { InfoIcon } from "lucide-react";
import { useSiteContext } from "@app/hooks/useSiteContext";
import { Separator } from "@app/components/ui/separator";
import {
InfoSection,
InfoSectionContent,
@@ -33,7 +32,7 @@ export default function SiteInfoCard({}: SiteInfoCardProps) {
<InfoIcon className="h-4 w-4" />
<AlertTitle className="font-semibold">Site Information</AlertTitle>
<AlertDescription className="mt-4">
<InfoSections>
<InfoSections cols={2}>
{(site.type == "newt" || site.type == "wireguard") && (
<>
<InfoSection>
@@ -52,8 +51,6 @@ export default function SiteInfoCard({}: SiteInfoCardProps) {
)}
</InfoSectionContent>
</InfoSection>
<Separator orientation="vertical" />
</>
)}
<InfoSection>

View File

@@ -1,8 +1,16 @@
"use client";
export function InfoSections({ children }: { children: React.ReactNode }) {
export function InfoSections({
children,
cols
}: {
children: React.ReactNode;
cols?: number;
}) {
return (
<div className="grid grid-cols-1 md:gap-4 gap-2 md:grid-cols-[1fr_auto_1fr] md:items-start">
<div
className={`grid md:grid-cols-${cols || 1} md:gap-4 gap-2 md:items-start grid-cols-1`}
>
{children}
</div>
);
@@ -23,9 +31,3 @@ export function InfoSectionContent({
}) {
return <div className="break-words">{children}</div>;
}
export function Divider() {
return (
<div className="hidden md:block border-l border-gray-300 h-auto mx-4"></div>
);
}

View File

@@ -13,7 +13,7 @@ const Checkbox = React.forwardRef<
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
"peer h-4 w-4 shrink-0 rounded-sm border-2 border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}

55
test/assert.ts Normal file
View File

@@ -0,0 +1,55 @@
/**
* Compares two objects for deep equality
* @param actual The actual value to test
* @param expected The expected value to compare against
* @param message The message to display if assertion fails
* @throws Error if objects are not equal
*/
export function assertEqualsObj<T>(actual: T, expected: T, message: string): void {
const actualStr = JSON.stringify(actual);
const expectedStr = JSON.stringify(expected);
if (actualStr !== expectedStr) {
throw new Error(`${message}\nExpected: ${expectedStr}\nActual: ${actualStr}`);
}
}
/**
* Compares two primitive values for equality
* @param actual The actual value to test
* @param expected The expected value to compare against
* @param message The message to display if assertion fails
* @throws Error if values are not equal
*/
export function assertEquals<T>(actual: T, expected: T, message: string): void {
if (actual !== expected) {
throw new Error(`${message}\nExpected: ${expected}\nActual: ${actual}`);
}
}
/**
* Tests if a function throws an expected error
* @param fn The function to test
* @param expectedError The expected error message or part of it
* @param message The message to display if assertion fails
* @throws Error if function doesn't throw or throws unexpected error
*/
export function assertThrows(
fn: () => void,
expectedError: string,
message: string
): void {
try {
fn();
throw new Error(`${message}: Expected to throw "${expectedError}"`);
} catch (error) {
if (!(error instanceof Error)) {
throw new Error(`${message}\nUnexpected error type: ${typeof error}`);
}
if (!error.message.includes(expectedError)) {
throw new Error(
`${message}\nExpected error: ${expectedError}\nActual error: ${error.message}`
);
}
}
}

View File

@@ -15,6 +15,7 @@
"baseUrl": "src",
"paths": {
"@server/*": ["../server/*"],
"@test/*": ["../test/*"],
"@app/*": ["*"],
"@/*": ["./*"]
},