Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd3d0cd8ff | ||
|
|
7ebb1b1a01 | ||
|
|
ae54927210 |
@@ -2541,386 +2541,7 @@ const APP_TEMPLATES = {
|
||||
fix: "Check that uvicorn is binding 127.0.0.1:8765 (not 0.0.0.0). Use `ss -tlnp | grep 8765` to confirm."
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
"authelia": {
|
||||
name: "Authelia",
|
||||
description: "Single sign-on portal and authentication gateway for web apps",
|
||||
icon: "\u{1F6E1}\u{FE0F}",
|
||||
category: "Security",
|
||||
popularity: 82,
|
||||
difficulty: "Advanced",
|
||||
docker: {
|
||||
image: "authelia/authelia:latest",
|
||||
ports: ["{{PORT}}:9091"],
|
||||
volumes: ["/opt/authelia/config:/config"],
|
||||
environment: {
|
||||
"AUTHELIA_STORAGE": "local",
|
||||
"AUTHELIA_STORAGE_LOCAL_PATH": "/config/db.sqlite3"
|
||||
}
|
||||
},
|
||||
subdomain: "authelia",
|
||||
defaultPort: 9091,
|
||||
healthCheck: "/api/health",
|
||||
subpathSupport: 'native',
|
||||
setupInstructions: [
|
||||
"Edit /opt/authelia/config/configuration.yml with your domain and settings",
|
||||
"Configure users in /opt/authelia/config/users_database.yml",
|
||||
"Set up Caddy forward_auth to protect your services behind Authelia",
|
||||
"Configure 2FA (TOTP, WebAuthn) in the Authelia portal"
|
||||
],
|
||||
dashcaddyIntegration: {
|
||||
ssoCompatible: true,
|
||||
forwardAuth: true,
|
||||
caddySnippet: "forward_auth authelia.<domain>:9091 { uri /api/verify?rd=https://authelia.<domain> copy_headers Remote-User Remote-Groups Remote-Name Remote-Email }"
|
||||
}
|
||||
},
|
||||
|
||||
"keycloak": {
|
||||
name: "Keycloak",
|
||||
description: "Open source identity and access management with SSO, OIDC, and SAML",
|
||||
icon: "\u{1F511}",
|
||||
category: "Security",
|
||||
popularity: 85,
|
||||
difficulty: "Advanced",
|
||||
docker: {
|
||||
image: "quay.io/keycloak/keycloak:latest",
|
||||
ports: ["{{PORT}}:8080"],
|
||||
volumes: ["/opt/keycloak/data:/opt/keycloak/data"],
|
||||
environment: {
|
||||
"KEYCLOAK_ADMIN": "admin",
|
||||
"KEYCLOAK_ADMIN_PASSWORD": "{{GENERATED_SECRET}}",
|
||||
"KC_DB": "dev-file",
|
||||
"KC_HOSTNAME": "{{SUBDOMAIN}}.{{TLD}}"
|
||||
},
|
||||
command: ["start-dev"]
|
||||
},
|
||||
subdomain: "keycloak",
|
||||
defaultPort: 8090,
|
||||
healthCheck: "/health/ready",
|
||||
subpathSupport: 'none',
|
||||
setupInstructions: [
|
||||
"Log in with admin / generated password",
|
||||
"Create a realm for your applications",
|
||||
"Configure OIDC clients for each app you want to protect",
|
||||
"Set up identity providers (Google, GitHub, etc.) for social login"
|
||||
],
|
||||
secrets: [{
|
||||
envVar: "GENERATED_SECRET",
|
||||
label: "Keycloak Admin Password",
|
||||
description: "Initial admin password",
|
||||
type: "password",
|
||||
required: true,
|
||||
generate: "alphanumeric",
|
||||
length: 32
|
||||
}]
|
||||
},
|
||||
|
||||
"vikunja": {
|
||||
name: "Vikunja",
|
||||
description: "Self-hosted to-do app with lists, kanban boards, and teams",
|
||||
icon: "\u2705",
|
||||
category: "Productivity",
|
||||
popularity: 72,
|
||||
difficulty: "Easy",
|
||||
docker: {
|
||||
image: "vikunja/vikunja:latest",
|
||||
ports: ["{{PORT}}:3456"],
|
||||
volumes: ["/opt/vikunja/files:/app/vikunja/files", "/opt/vikunja/db:/app/vikunja/database"],
|
||||
environment: {
|
||||
"VIKUNJA_SERVICE_JWTSECRET": "{{GENERATED_SECRET}}",
|
||||
"VIKUNJA_SERVICE_FRONTENDURL": "https://{{SUBDOMAIN}}.{{TLD}}"
|
||||
}
|
||||
},
|
||||
subdomain: "vikunja",
|
||||
defaultPort: 3456,
|
||||
healthCheck: "/api/v1/info",
|
||||
subpathSupport: 'native',
|
||||
setupInstructions: ["Register the first user account", "Create projects and tasks", "Set up teams for shared task management"],
|
||||
secrets: [{
|
||||
envVar: "GENERATED_SECRET",
|
||||
label: "JWT Secret",
|
||||
description: "Secret for signing auth tokens",
|
||||
type: "password",
|
||||
required: true,
|
||||
generate: "alphanumeric",
|
||||
length: 48
|
||||
}]
|
||||
},
|
||||
|
||||
"openproject": {
|
||||
name: "OpenProject",
|
||||
description: "Project management with Gantt charts, time tracking, and Scrum boards",
|
||||
icon: "\u{1F4CB}",
|
||||
category: "Productivity",
|
||||
popularity: 75,
|
||||
difficulty: "Intermediate",
|
||||
docker: {
|
||||
image: "openproject/openproject:latest",
|
||||
ports: ["{{PORT}}:80"],
|
||||
volumes: ["/opt/openproject/pgdata:/var/openproject/pgdata", "/opt/openproject/assets:/var/openproject/assets"],
|
||||
environment: { "OPENPROJECT_HOST__NAME": "{{SUBDOMAIN}}.{{TLD}}", "OPENPROJECT_HTTPS": "true" }
|
||||
},
|
||||
subdomain: "projects",
|
||||
defaultPort: 8091,
|
||||
healthCheck: "/",
|
||||
subpathSupport: 'none',
|
||||
setupInstructions: ["Complete the initial setup wizard", "Create your first project", "Add team members and configure permissions"]
|
||||
},
|
||||
|
||||
"plane": {
|
||||
name: "Plane",
|
||||
description: "Open-source Jira alternative with issues, cycles, and modules",
|
||||
icon: "\u2708\uFE0F",
|
||||
category: "Productivity",
|
||||
popularity: 70,
|
||||
difficulty: "Intermediate",
|
||||
docker: {
|
||||
image: "makeplane/plane-frontend:latest",
|
||||
ports: ["{{PORT}}:3000"],
|
||||
volumes: ["/opt/plane/data:/app/data"],
|
||||
environment: { "NEXT_PUBLIC_API_BASE_URL": "https://{{SUBDOMAIN}}.{{TLD}}/api" }
|
||||
},
|
||||
subdomain: "plane",
|
||||
defaultPort: 8092,
|
||||
healthCheck: "/",
|
||||
subpathSupport: 'none',
|
||||
setupInstructions: ["Plane requires multiple containers - use the recipe for full stack deploy", "Create an organization and invite team members", "Set up cycles and modules for project tracking"]
|
||||
},
|
||||
|
||||
"hedgedoc": {
|
||||
name: "HedgeDoc",
|
||||
description: "Collaborative markdown editor with real-time editing",
|
||||
icon: "\u{1F4DD}",
|
||||
category: "Productivity",
|
||||
popularity: 68,
|
||||
difficulty: "Easy",
|
||||
docker: {
|
||||
image: "quay.io/hedgedoc/hedgedoc:latest",
|
||||
ports: ["{{PORT}}:3000"],
|
||||
volumes: ["/opt/hedgedoc/uploads:/hedgedoc/public/uploads"],
|
||||
environment: {
|
||||
"CMD_DOMAIN": "{{SUBDOMAIN}}.{{TLD}}",
|
||||
"CMD_URL_ADDPORT": "false",
|
||||
"CMD_PROTOCOL_USESSL": "true",
|
||||
"CMD_DB_URL": "sqlite:/hedgedoc/database.sqlite"
|
||||
}
|
||||
},
|
||||
subdomain: "notes",
|
||||
defaultPort: 8093,
|
||||
healthCheck: "/status",
|
||||
subpathSupport: 'native',
|
||||
setupInstructions: ["Register an account or use guest mode", "Create collaborative markdown documents", "Share links for real-time co-editing"]
|
||||
},
|
||||
|
||||
"yacht": {
|
||||
name: "Yacht",
|
||||
description: "Web-based Docker container manager with template support",
|
||||
icon: "\u26F5",
|
||||
category: "Management",
|
||||
popularity: 65,
|
||||
difficulty: "Easy",
|
||||
docker: {
|
||||
image: "selfhostedpro/yacht:latest",
|
||||
ports: ["{{PORT}}:8000"],
|
||||
volumes: ["/opt/yacht/config:/config", "/var/run/docker.sock:/var/run/docker.sock"],
|
||||
environment: { "PUID": "1000", "PGID": "1000" }
|
||||
},
|
||||
subdomain: "yacht",
|
||||
defaultPort: 8094,
|
||||
healthCheck: "/",
|
||||
subpathSupport: 'strip',
|
||||
setupInstructions: ["Set up admin account on first launch", "Add compose templates for one-click deployments", "Manage containers through the web interface"]
|
||||
},
|
||||
|
||||
"openvpn": {
|
||||
name: "OpenVPN",
|
||||
description: "Virtual private network server for secure remote access",
|
||||
icon: "\u{1F512}",
|
||||
category: "Security",
|
||||
popularity: 78,
|
||||
difficulty: "Intermediate",
|
||||
docker: {
|
||||
image: "kylemanna/openvpn:latest",
|
||||
ports: ["{{PORT}}:1194/udp"],
|
||||
volumes: ["/opt/openvpn:/etc/openvpn"],
|
||||
environment: {},
|
||||
cap_add: ["NET_ADMIN"]
|
||||
},
|
||||
subdomain: "openvpn",
|
||||
defaultPort: 1194,
|
||||
healthCheck: null,
|
||||
subpathSupport: 'none',
|
||||
setupInstructions: ["Initialize the PKI: docker exec openvpn ovpn_initpki", "Generate client certificates for each device", "Download client configs and import into OpenVPN client"]
|
||||
},
|
||||
|
||||
"forgejo": {
|
||||
name: "Forgejo",
|
||||
description: "Self-hosted Git service - soft fork of Gitea with enhanced features",
|
||||
icon: "\u{1F527}",
|
||||
category: "Development",
|
||||
popularity: 73,
|
||||
difficulty: "Easy",
|
||||
docker: {
|
||||
image: "codeberg.org/forgejo/forgejo:latest",
|
||||
ports: ["{{PORT}}:3000", "2222:22"],
|
||||
volumes: ["/opt/forgejo/data:/data", "/etc/localtime:/etc/localtime:ro"],
|
||||
environment: { "USER_UID": "1000", "USER_GID": "1000" }
|
||||
},
|
||||
subdomain: "forgejo",
|
||||
defaultPort: 8095,
|
||||
healthCheck: "/api/v1/version",
|
||||
subpathSupport: 'native',
|
||||
setupInstructions: ["Configure database on first run", "Create admin account and disable open registration", "Migrate repos from GitHub/GitLab via the built-in migration tool", "Set up Actions for CI/CD pipelines"]
|
||||
},
|
||||
|
||||
"gitlab": {
|
||||
name: "GitLab",
|
||||
description: "Complete DevOps platform with Git, CI/CD, and project management",
|
||||
icon: "\u{1F99A}",
|
||||
category: "Development",
|
||||
popularity: 88,
|
||||
difficulty: "Advanced",
|
||||
docker: {
|
||||
image: "gitlab/gitlab-ce:latest",
|
||||
ports: ["{{PORT}}:80", "8443:443", "2223:22"],
|
||||
volumes: ["/opt/gitlab/config:/etc/gitlab", "/opt/gitlab/logs:/var/log/gitlab", "/opt/gitlab/data:/var/opt/gitlab"],
|
||||
environment: { "GITLAB_OMNIBUS_CONFIG": "external_url https://{{SUBDOMAIN}}.{{TLD}}" },
|
||||
shm_size: "256m"
|
||||
},
|
||||
subdomain: "gitlab",
|
||||
defaultPort: 8096,
|
||||
healthCheck: "/-/health",
|
||||
subpathSupport: 'none',
|
||||
setupInstructions: ["Requires at least 4GB RAM and 2 CPU cores", "Wait 5-10 minutes for first boot", "Set root password on first login", "Configure runners for CI/CD pipelines"],
|
||||
resourceWarning: { minMemoryMB: 4096, minCpuCores: 2, message: "GitLab requires at least 4GB RAM. Deploying on a smaller server may cause instability." }
|
||||
},
|
||||
|
||||
"prometheus": {
|
||||
name: "Prometheus",
|
||||
description: "Monitoring system with time-series database and alerting",
|
||||
icon: "\u{1F525}",
|
||||
category: "Monitoring",
|
||||
popularity: 85,
|
||||
difficulty: "Intermediate",
|
||||
docker: {
|
||||
image: "prom/prometheus:latest",
|
||||
ports: ["{{PORT}}:9090"],
|
||||
volumes: ["/opt/prometheus/data:/prometheus", "/opt/prometheus/config:/etc/prometheus"],
|
||||
environment: {},
|
||||
command: ["--config.file=/etc/prometheus/prometheus.yml", "--storage.tsdb.path=/prometheus", "--web.enable-lifecycle"]
|
||||
},
|
||||
subdomain: "prometheus",
|
||||
defaultPort: 9090,
|
||||
healthCheck: "/-/healthy",
|
||||
subpathSupport: 'native',
|
||||
setupInstructions: ["Edit /opt/prometheus/config/prometheus.yml to add scrape targets", "Add DashCaddy /api/v1/metrics/prometheus as a scrape target", "Pair with Grafana for dashboards", "Configure alert rules"]
|
||||
},
|
||||
|
||||
"netdata": {
|
||||
name: "Netdata",
|
||||
description: "Real-time system metrics with zero configuration monitoring",
|
||||
icon: "\u{1F4C8}",
|
||||
category: "Monitoring",
|
||||
popularity: 82,
|
||||
difficulty: "Easy",
|
||||
docker: {
|
||||
image: "netdata/netdata:latest",
|
||||
ports: ["{{PORT}}:19999"],
|
||||
volumes: ["/opt/netdata/config:/etc/netdata", "/opt/netdata/lib:/var/lib/netdata", "/opt/netdata/cache:/var/cache/netdata", "/proc:/host/proc:ro", "/sys:/host/sys:ro", "/etc/os-release:/host/etc/os-release:ro"],
|
||||
environment: { "NETDATA_CLAIM_URL": "https://app.netdata.cloud" },
|
||||
cap_add: ["SYS_PTRACE"],
|
||||
security_opt: ["apparmor:unconfined"]
|
||||
},
|
||||
subdomain: "netdata",
|
||||
defaultPort: 19999,
|
||||
healthCheck: "/api/v1/info",
|
||||
subpathSupport: 'native',
|
||||
setupInstructions: ["Dashboard is immediately available with zero configuration", "Monitor CPU, RAM, disk, network, Docker in real-time", "Configure alarms for resource thresholds", "Optional: claim to Netdata Cloud for centralized monitoring"]
|
||||
},
|
||||
|
||||
"kibana": {
|
||||
name: "Kibana",
|
||||
description: "Visualization dashboard for Elasticsearch data analytics",
|
||||
icon: "\u{1F4C9}",
|
||||
category: "Monitoring",
|
||||
popularity: 70,
|
||||
difficulty: "Advanced",
|
||||
docker: {
|
||||
image: "kibana:8.12.0",
|
||||
ports: ["{{PORT}}:5601"],
|
||||
volumes: ["/opt/kibana/config:/usr/share/kibana/config"],
|
||||
environment: { "ELASTICSEARCH_HOSTS": "http://elasticsearch:9200" }
|
||||
},
|
||||
subdomain: "kibana",
|
||||
defaultPort: 5601,
|
||||
healthCheck: "/api/status",
|
||||
subpathSupport: 'native',
|
||||
setupInstructions: ["Requires an Elasticsearch instance running first", "Consider deploying via the ELK Stack recipe", "Create index patterns for your data", "Build dashboards and visualizations"]
|
||||
},
|
||||
|
||||
"openhab": {
|
||||
name: "OpenHAB",
|
||||
description: "Open source home automation platform with broad device support",
|
||||
icon: "\u2699\uFE0F",
|
||||
category: "Home Automation",
|
||||
popularity: 72,
|
||||
difficulty: "Intermediate",
|
||||
docker: {
|
||||
image: "openhab/openhab:latest",
|
||||
ports: ["{{PORT}}:8080", "8444:8443"],
|
||||
volumes: ["/opt/openhab/conf:/openhab/conf", "/opt/openhab/userdata:/openhab/userdata", "/opt/openhab/addons:/openhab/addons", "/etc/localtime:/etc/localtime:ro"],
|
||||
environment: { "OPENHAB_HTTP_PORT": "8080", "OPENHAB_HTTPS_PORT": "8443", "EXTRA_JAVA_OPTS": "-Duser.timezone={{TIMEZONE}}" }
|
||||
},
|
||||
subdomain: "openhab",
|
||||
defaultPort: 8097,
|
||||
healthCheck: "/start/index",
|
||||
subpathSupport: 'none',
|
||||
setupInstructions: ["Choose your preferred package (Standard, Demo, or Minimal)", "Install bindings for your smart home devices", "Create items, sitemaps, and rules", "Access the Paper UI for configuration"]
|
||||
},
|
||||
|
||||
"bitwarden": {
|
||||
name: "Bitwarden",
|
||||
description: "Official Bitwarden password manager server (unified self-hosted)",
|
||||
icon: "\u{1F510}",
|
||||
category: "Security",
|
||||
popularity: 80,
|
||||
difficulty: "Advanced",
|
||||
docker: {
|
||||
image: "bitwarden/self-host:latest",
|
||||
ports: ["{{PORT}}:8080"],
|
||||
volumes: ["/opt/bitwarden/data:/etc/bitwarden"],
|
||||
environment: { "BW_DOMAIN": "{{SUBDOMAIN}}.{{TLD}}" }
|
||||
},
|
||||
subdomain: "bitwarden",
|
||||
defaultPort: 8098,
|
||||
healthCheck: "/health",
|
||||
subpathSupport: 'none',
|
||||
setupInstructions: ["Complete the Bitwarden unified installation", "Generate installation ID and key at bitwarden.com/host", "Configure SMTP for email verification", "Note: Vaultwarden is recommended for smaller deployments"],
|
||||
resourceWarning: { minMemoryMB: 2048, message: "Official Bitwarden requires 2GB+ RAM. For lightweight deployments, use Vaultwarden instead." }
|
||||
},
|
||||
|
||||
"subsonic": {
|
||||
name: "Subsonic",
|
||||
description: "Web-based media streamer for music with wide client support",
|
||||
icon: "\u{1F3B5}",
|
||||
category: "Media",
|
||||
popularity: 60,
|
||||
difficulty: "Easy",
|
||||
docker: {
|
||||
image: "linuxserver/subsonic:latest",
|
||||
ports: ["{{PORT}}:4040"],
|
||||
volumes: ["/opt/subsonic/config:/config", "/opt/subsonic/music:/music", "/opt/subsonic/podcasts:/podcasts", "/opt/subsonic/playlists:/playlists"],
|
||||
environment: { "PUID": "1000", "PGID": "1000", "TZ": "{{TIMEZONE}}" }
|
||||
},
|
||||
subdomain: "subsonic",
|
||||
defaultPort: 4040,
|
||||
healthCheck: "/",
|
||||
subpathSupport: 'native',
|
||||
setupInstructions: ["Set admin password on first launch", "Add music folders in Settings", "Install Subsonic-compatible apps on your devices", "Note: Airsonic Advanced is also available as a fully open-source alternative"],
|
||||
mediaMount: { required: true, containerPath: "/music", label: "Music Library", description: "Folder containing your music files", defaultPath: "/media/music" }
|
||||
},
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
// Template categories for organization
|
||||
|
||||
@@ -504,45 +504,6 @@ module.exports = function configureMiddleware(app, {
|
||||
return errorResponse(res, 401, '[DC-110] Authentication required', { requiresTotp: true });
|
||||
};
|
||||
|
||||
|
||||
// ── Sensitive routes: block external access when TOTP is off ──
|
||||
// When TOTP is not enabled, all routes are open by design. But certain routes
|
||||
// expose infrastructure details (config, tailscale, license keys, service
|
||||
// manifests with container IDs, deployment manifests, port mappings) that
|
||||
// should not be accessible from the public internet. Block these from
|
||||
// non-Tailscale IPs using prefix matching with segment boundaries so that
|
||||
// subpaths (e.g. /api/v1/services/dc9201) are also protected.
|
||||
//
|
||||
// Each entry is matched as: path === prefix || path.startsWith(prefix + '/')
|
||||
const SENSITIVE_ROUTE_PREFIXES = [
|
||||
'/api/v1/config',
|
||||
'/api/v1/services',
|
||||
'/api/v1/tailscale',
|
||||
'/api/v1/updates',
|
||||
'/api/v1/license',
|
||||
'/api/v1/credentials',
|
||||
'/api/v1/health-checks',
|
||||
'/api/v1/disaster',
|
||||
'/api/v1/fleet',
|
||||
'/api/v1/disk',
|
||||
];
|
||||
|
||||
const sensitiveRouteMiddleware = (req, res, next) => {
|
||||
if (!totpConfig.enabled) {
|
||||
const isSensitive = SENSITIVE_ROUTE_PREFIXES.some(
|
||||
prefix => req.path === prefix || req.path.startsWith(prefix + '/')
|
||||
);
|
||||
if (isSensitive && !isTailscaleIP(getClientIP(req))) {
|
||||
return errorResponse(res, 403, '[DC-122] Access denied. This endpoint requires TOTP authentication or Tailscale access.', {
|
||||
requiresTotp: true
|
||||
});
|
||||
}
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
app.use(sensitiveRouteMiddleware);
|
||||
|
||||
app.use(totpAuthMiddleware);
|
||||
|
||||
// ── JWT/API Key authentication middleware ──
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
set -euo pipefail
|
||||
|
||||
# ---- Constants -------------------------------------------------------------
|
||||
readonly DASHCADDY_VERSION="1.15.0"
|
||||
readonly DASHCADDY_VERSION="1.14.6"
|
||||
readonly DASHCADDY_DOWNLOAD="https://get.dashcaddy.net/release/latest.tar.gz"
|
||||
readonly DASHCADDY_REPO="" # Set to a git URL to clone instead of downloading
|
||||
readonly INSTALL_DIR="/etc/dashcaddy"
|
||||
|
||||
@@ -7,6 +7,10 @@ const { DEFAULT_PORTS } = require('../shared/constants');
|
||||
*
|
||||
* Generates production-grade configs that match the patterns used by the
|
||||
* running DashCaddy deployment (CORS snippets, admin origins, PKI, etc.)
|
||||
*
|
||||
* DISK SAFETY: All generated configs include sensible defaults for storage
|
||||
* limits — health retention, stats caps, and memory limits — so a fresh
|
||||
* install will never silently fill a user's disk.
|
||||
*/
|
||||
class CaddyfileGenerator {
|
||||
/**
|
||||
@@ -279,19 +283,43 @@ class CaddyfileGenerator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate docker-compose.yml for running the API server
|
||||
* Generate docker-compose.yml for running the API server.
|
||||
*
|
||||
* DISK SAFETY: Includes env vars for health retention, stats caps, and
|
||||
* memory limits derived from the disk budget the user selected during
|
||||
* install. These prevent the disk-explosion bugs seen in early versions.
|
||||
*
|
||||
* @param {string} installPath - Installation directory
|
||||
* @param {Object} options - Configuration options
|
||||
* @param {number} options.apiPort - API server port
|
||||
* @param {string} options.lanIP - Host LAN IP address
|
||||
* @param {string} options.tailscaleIP - Host Tailscale IP address
|
||||
* @param {string} options.domainMode - Domain mode (local, public, custom-tld)
|
||||
* @param {Object} [options.disk] - Disk budget settings
|
||||
* @param {number} [options.disk.healthRetentionDays=14] - Health history retention
|
||||
* @param {number} [options.disk.healthMaxEntries=500] - Max health entries per service
|
||||
* @param {number} [options.disk.healthCheckInterval=30000] - Health check interval (ms)
|
||||
* @param {number} [options.disk.statsMaxEntries=2000] - Max container stats entries
|
||||
* @param {number} [options.disk.auditMaxEntries=1000] - Max audit log entries
|
||||
* @param {number} [options.disk.backupLimitGB=10] - Backup storage limit
|
||||
* @param {string} [options.dockerDataPath] - Docker data root override
|
||||
* @param {number} [options.memoryLimitMB=1024] - Container memory limit
|
||||
*/
|
||||
generateDockerCompose(installPath, options = {}) {
|
||||
const apiPort = options.apiPort || DEFAULT_PORTS.API;
|
||||
const adminPort = DEFAULT_PORTS.CADDY_ADMIN;
|
||||
const p = this._p.bind(this);
|
||||
|
||||
// Disk budget settings with safe defaults
|
||||
const disk = options.disk || {};
|
||||
const healthRetentionDays = disk.healthRetentionDays || 14;
|
||||
const healthMaxEntries = disk.healthMaxEntries || 500;
|
||||
const healthCheckInterval = disk.healthCheckInterval || 30000;
|
||||
const statsMaxEntries = disk.statsMaxEntries || 2000;
|
||||
const auditMaxEntries = disk.auditMaxEntries || 1000;
|
||||
const backupLimitGB = disk.backupLimitGB || 10;
|
||||
const memoryLimitMB = options.memoryLimitMB || 1024;
|
||||
|
||||
// Core volume mounts
|
||||
let volumes = ` - ${p(installPath)}/Caddyfile:/caddyfile:rw
|
||||
- ${p(installPath)}/services.json:/app/services.json:rw
|
||||
@@ -308,12 +336,19 @@ class CaddyfileGenerator {
|
||||
volumes += `\n - ${p(installPath)}/certs/pki/authorities/local:/app/pki:ro`;
|
||||
}
|
||||
|
||||
// Environment variables
|
||||
// Environment variables — disk safety baked in
|
||||
let envVars = ` - CADDYFILE_PATH=/caddyfile
|
||||
- CADDY_ADMIN_URL=http://host.docker.internal:${adminPort}
|
||||
- ASSETS_PATH=/app/assets
|
||||
- CREDENTIALS_FILE=/app/credentials.json
|
||||
- NODE_ENV=production`;
|
||||
- NODE_ENV=production
|
||||
# --- Disk Safety ---
|
||||
- HEALTH_HISTORY_RETENTION=${healthRetentionDays}
|
||||
- HEALTH_MAX_ENTRIES=${healthMaxEntries}
|
||||
- HEALTH_CHECK_INTERVAL=${healthCheckInterval}
|
||||
- CONTAINER_STATS_MAX_ENTRIES=${statsMaxEntries}
|
||||
- AUDIT_MAX_ENTRIES=${auditMaxEntries}
|
||||
- BACKUP_MAX_STORAGE_BYTES=${backupLimitGB * 1024 * 1024 * 1024}`;
|
||||
|
||||
if (options.domainMode === 'custom-tld') {
|
||||
envVars += `\n - CA_CERT_PATH=/app/pki/root.crt`;
|
||||
@@ -339,6 +374,9 @@ ${envVars}
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
restart: unless-stopped
|
||||
# Memory limit prevents OOM during startup when all managers init
|
||||
mem_limit: ${memoryLimitMB}m
|
||||
memswap_limit: ${(memoryLimitMB * 2)}m
|
||||
`;
|
||||
|
||||
return dockerCompose;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* VM Provisioner IPC Handler
|
||||
* Wires the Electron wizard to VMDiskProvisioner.
|
||||
* Add to src/main/index.js alongside the existing IPC handlers.
|
||||
*/
|
||||
|
||||
const { ipcMain } = require('electron');
|
||||
const { VMDiskProvisioner, DISK_PRESETS } = require('./vm-provisioner');
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
|
||||
function registerVMHandlers(mainWindow) {
|
||||
const provisioner = new VMDiskProvisioner();
|
||||
|
||||
// --- Get disk presets for wizard UI ---
|
||||
ipcMain.handle('vm:get-presets', async () => {
|
||||
return DISK_PRESETS;
|
||||
});
|
||||
|
||||
// --- Get current VM status ---
|
||||
ipcMain.handle('vm:get-status', async () => {
|
||||
try {
|
||||
const status = await provisioner.getStatus();
|
||||
// Also check for saved vmInfo from previous install
|
||||
try {
|
||||
const configPath = path.join(getInstallBase(), '.dashcaddy-config.json');
|
||||
const config = JSON.parse(await fs.readFile(configPath, 'utf8'));
|
||||
if (config.vmInfo) {
|
||||
status.vmInfo = config.vmInfo;
|
||||
status.diskSizeGB = config.vmInfo.diskSizeGB;
|
||||
}
|
||||
} catch {}
|
||||
return status;
|
||||
} catch (e) {
|
||||
return { platform: process.platform, running: false, error: e.message };
|
||||
}
|
||||
});
|
||||
|
||||
// --- Provision the VM sandbox ---
|
||||
ipcMain.handle('vm:provision', async (event, opts) => {
|
||||
try {
|
||||
const result = await provisioner.provision({
|
||||
...opts,
|
||||
onProgress: (msg, pct) => {
|
||||
mainWindow.webContents.send('vm:progress', { message: msg, percent: pct });
|
||||
},
|
||||
});
|
||||
|
||||
// Save vmInfo for uninstall
|
||||
if (result.vmInfo) {
|
||||
try {
|
||||
const configPath = path.join(opts.installPath || getInstallBase(), '.dashcaddy-config.json');
|
||||
let config = {};
|
||||
try { config = JSON.parse(await fs.readFile(configPath, 'utf8')); } catch {}
|
||||
config.vmInfo = result.vmInfo;
|
||||
config.diskBudgetGB = opts.diskSizeGB;
|
||||
await fs.writeFile(configPath, JSON.stringify(config, null, 2));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
mainWindow.webContents.send('vm:complete', result);
|
||||
return result;
|
||||
} catch (error) {
|
||||
mainWindow.webContents.send('vm:error', { error: error.message });
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
// --- Destroy the VM sandbox (uninstall) ---
|
||||
ipcMain.handle('vm:destroy', async (event, opts) => {
|
||||
try {
|
||||
// Load saved vmInfo
|
||||
let vmInfo = opts.vmInfo;
|
||||
if (!vmInfo) {
|
||||
try {
|
||||
const configPath = path.join(opts.installPath || getInstallBase(), '.dashcaddy-config.json');
|
||||
const config = JSON.parse(await fs.readFile(configPath, 'utf8'));
|
||||
vmInfo = config.vmInfo;
|
||||
} catch {}
|
||||
}
|
||||
|
||||
if (!vmInfo) {
|
||||
return { success: false, error: 'No VM info found. Already uninstalled?' };
|
||||
}
|
||||
|
||||
const result = await provisioner.destroy(vmInfo, {
|
||||
exportDataPath: opts.exportDataPath || null,
|
||||
});
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
});
|
||||
|
||||
// --- Export data from VM (before uninstall) ---
|
||||
ipcMain.handle('vm:export-data', async (event, opts) => {
|
||||
try {
|
||||
const result = await provisioner._exportData(opts.vmInfo, opts.exportPath);
|
||||
return result;
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function getInstallBase() {
|
||||
const { getPlatformInfo } = require('../shared/platform-utils');
|
||||
return getPlatformInfo().defaultInstallPath;
|
||||
}
|
||||
|
||||
module.exports = { registerVMHandlers };
|
||||
@@ -0,0 +1,511 @@
|
||||
/**
|
||||
* VM Disk Provisioner — creates a bounded virtual disk for DashCaddy.
|
||||
*
|
||||
* PLATFORM STRATEGY:
|
||||
* Windows: Dedicated WSL2 distro with a fixed-size VHDX.
|
||||
* Docker runs inside WSL2, all data lives in the VHDX.
|
||||
* Uninstall = wsl --unregister (deletes VHDX instantly).
|
||||
*
|
||||
* macOS: Lima VM with a fixed disk image.
|
||||
* Docker runs inside Lima, all data lives in the disk image.
|
||||
* Uninstall = limactl delete (removes VM + disk).
|
||||
*
|
||||
* Linux: Sparse ext4 loopback image mounted at /opt/dashcaddy-data.
|
||||
* Docker --data-root pointed at the mount.
|
||||
* Uninstall = unmount + rm image file.
|
||||
*
|
||||
* The user picks a disk size (default 20GB). DashCaddy is physically
|
||||
* unable to exceed it — the OS enforces the limit, not our code.
|
||||
*/
|
||||
|
||||
const { exec } = require('child_process');
|
||||
const { promisify } = require('util');
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
const platformUtils = require('../shared/platform-utils');
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
// Presets users pick from in the wizard
|
||||
const DISK_PRESETS = {
|
||||
minimal: { sizeGB: 10, label: 'Minimal (10GB)', desc: 'DashCaddy only, a few small apps' },
|
||||
balanced: { sizeGB: 30, label: 'Balanced (30GB)', desc: 'DashCaddy + media tools + containers' },
|
||||
power: { sizeGB: 100, label: 'Power (100GB)', desc: 'DashCaddy + heavy apps + lots of containers' },
|
||||
custom: { sizeGB: 0, label: 'Custom', desc: 'Pick your own size' },
|
||||
};
|
||||
|
||||
/**
|
||||
* Main provisioner class.
|
||||
*/
|
||||
class VMDiskProvisioner {
|
||||
constructor() {
|
||||
this.platform = platformUtils.detectOS();
|
||||
}
|
||||
|
||||
/**
|
||||
* Provision the full sandboxed environment.
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @param {number} opts.diskSizeGB — virtual disk size
|
||||
* @param {string} opts.installPath — where DashCaddy app files live (host)
|
||||
* @param {number} opts.apiPort
|
||||
* @param {Object} opts.domain — { mode, domain, tld, email }
|
||||
* @param {function} [opts.onProgress] — callback(statusMsg, pct)
|
||||
* @returns {Object} { success, dockerContext, dashboardUrl, vmInfo }
|
||||
*/
|
||||
async provision(opts) {
|
||||
const { diskSizeGB = 30, onProgress = () => {} } = opts;
|
||||
|
||||
onProgress('Checking prerequisites', 5);
|
||||
await this._checkPrerequisites();
|
||||
|
||||
onProgress('Creating virtual disk (' + diskSizeGB + 'GB)', 15);
|
||||
const diskInfo = await this._createDisk(opts);
|
||||
|
||||
onProgress('Starting sandbox environment', 40);
|
||||
const envInfo = await this._startEnvironment(diskInfo, opts);
|
||||
|
||||
onProgress('Installing Docker in sandbox', 60);
|
||||
await this._ensureDocker(envInfo);
|
||||
|
||||
onProgress('Deploying DashCaddy into sandbox', 75);
|
||||
const deployInfo = await this._deployDashCaddy(envInfo, opts);
|
||||
|
||||
onProgress('Configuring services', 90);
|
||||
await this._configureServices(envInfo, opts);
|
||||
|
||||
onProgress('Complete', 100);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
platform: this.platform,
|
||||
diskSizeGB,
|
||||
dockerContext: envInfo.dockerContext,
|
||||
dashboardUrl: deployInfo.dashboardUrl,
|
||||
vmInfo: {
|
||||
type: envInfo.type,
|
||||
name: envInfo.name,
|
||||
diskPath: diskInfo.path,
|
||||
diskSizeGB,
|
||||
dockerDataRoot: envInfo.dockerDataRoot,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the sandboxed environment completely.
|
||||
* @param {Object} vmInfo — from provision()
|
||||
* @param {Object} opts — { exportDataPath: null }
|
||||
*/
|
||||
async destroy(vmInfo, opts = {}) {
|
||||
// Export data first if requested
|
||||
if (opts.exportDataPath) {
|
||||
await this._exportData(vmInfo, opts.exportDataPath);
|
||||
}
|
||||
|
||||
switch (this.platform) {
|
||||
case 'windows': return this._destroyWSL2(vmInfo);
|
||||
case 'macos': return this._destroyLima(vmInfo);
|
||||
case 'linux': return this._destroyLoopback(vmInfo);
|
||||
default: throw new Error('Unsupported platform: ' + this.platform);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// PREREQUISITES
|
||||
// =========================================================================
|
||||
|
||||
async _checkPrerequisites() {
|
||||
const checks = [];
|
||||
|
||||
switch (this.platform) {
|
||||
case 'windows':
|
||||
checks.push(this._checkCommand('wsl', '--status', 'WSL2'));
|
||||
break;
|
||||
case 'macos':
|
||||
checks.push(this._checkCommand('limactl', 'version', 'Lima'));
|
||||
break;
|
||||
case 'linux':
|
||||
// Need root or sudo for loopback mount
|
||||
if (process.getuid && process.getuid() !== 0) {
|
||||
// Check if we can sudo
|
||||
try { await execAsync('sudo -n true', { timeout: 5000 }); }
|
||||
catch { throw new Error('Linux install needs root or passwordless sudo for loopback mount'); }
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
const results = await Promise.all(checks);
|
||||
const failed = results.filter(r => !r.ok);
|
||||
if (failed.length) {
|
||||
throw new Error('Missing: ' + failed.map(f => f.name).join(', ') +
|
||||
'. Install instructions: https://dashcaddy.net/docs/installation');
|
||||
}
|
||||
}
|
||||
|
||||
async _checkCommand(cmd, versionArg, friendlyName) {
|
||||
try {
|
||||
await execAsync(`${cmd} ${versionArg}`, { timeout: 10000 });
|
||||
return { ok: true, name: friendlyName };
|
||||
} catch {
|
||||
return { ok: false, name: friendlyName };
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// WINDOWS: WSL2 Dedicated Distro
|
||||
// =========================================================================
|
||||
|
||||
async _createDisk(opts) {
|
||||
if (this.platform === 'windows') return this._createWSL2Disk(opts);
|
||||
if (this.platform === 'macos') return this._createLimaDisk(opts);
|
||||
return this._createLoopbackDisk(opts);
|
||||
}
|
||||
|
||||
async _createWSL2Disk(opts) {
|
||||
const distroName = 'dashcaddy';
|
||||
const { diskSizeGB = 30 } = opts;
|
||||
const wslPath = opts.installPath || path.join(process.env.LOCALAPPDATA || 'C:\\DashCaddy', 'DashCaddy');
|
||||
const vhdxPath = path.join(wslPath, 'data.vhdx');
|
||||
|
||||
// Check if distro already exists
|
||||
try {
|
||||
const { stdout } = await execAsync('wsl -l -q', { timeout: 10000 });
|
||||
if (stdout.includes(distroName)) {
|
||||
return { type: 'wsl2', distroName, path: vhdxPath, diskSizeGB, existed: true };
|
||||
}
|
||||
} catch {}
|
||||
|
||||
// Download a minimal rootfs (Alpine for smallest footprint)
|
||||
await fs.mkdir(wslPath, { recursive: true });
|
||||
const rootfsUrl = 'https://dl-cdn.alpinelinux.org/alpine/v3.20/releases/x86_64/alpine-minirootfs-3.20.0-x86_64.tar.gz';
|
||||
const rootfsPath = path.join(wslPath, 'rootfs.tar.gz');
|
||||
|
||||
await execAsync(`curl -L -o "${rootfsPath}" "${rootfsUrl}"`, { timeout: 120000 });
|
||||
|
||||
// Import as a new WSL2 distro — the VHDX is created automatically
|
||||
// and capped by .wslconfig max disk size
|
||||
await execAsync(`wsl --import ${distroName} "${wslPath}" "${rootfsPath}" --version 2`, { timeout: 60000 });
|
||||
|
||||
// Set disk size limit via wsl config
|
||||
const wslconfigPath = path.join(wslPath, '.wslconfig');
|
||||
await fs.writeFile(wslconfigPath, [
|
||||
`[wsl2]`,
|
||||
`vmDiskSize=${diskSizeGB}GB`,
|
||||
`memory=2GB`,
|
||||
`processors=2`,
|
||||
].join('\n'));
|
||||
|
||||
// Clean up rootfs download
|
||||
await fs.unlink(rootfsPath).catch(() => {});
|
||||
|
||||
return { type: 'wsl2', distroName, path: vhdxPath, diskSizeGB, existed: false };
|
||||
}
|
||||
|
||||
async _startEnvironment(diskInfo, opts) {
|
||||
if (this.platform === 'windows') return this._startWSL2(diskInfo, opts);
|
||||
if (this.platform === 'macos') return this._startLima(diskInfo, opts);
|
||||
return this._startLoopback(diskInfo, opts);
|
||||
}
|
||||
|
||||
async _startWSL2(diskInfo, opts) {
|
||||
const { distroName } = diskInfo;
|
||||
|
||||
// Start the distro and install Docker inside
|
||||
const wslExec = (cmd) => execAsync(`wsl -d ${distroName} -- sh -c "${cmd}"`, { timeout: 60000 });
|
||||
|
||||
// Update apk and install Docker + dependencies
|
||||
await wslExec('apk update && apk add docker docker-cli-compose openrc ca-certificates curl');
|
||||
await wslExec('rc-update add docker default && service docker start');
|
||||
|
||||
// Create Docker data directory inside the VM
|
||||
await wslExec('mkdir -p /var/lib/docker /opt/dashcaddy');
|
||||
|
||||
return {
|
||||
type: 'wsl2',
|
||||
name: distroName,
|
||||
dockerContext: 'dashcaddy-wsl',
|
||||
dockerDataRoot: '/var/lib/docker',
|
||||
exec: wslExec,
|
||||
};
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// macOS: Lima VM
|
||||
// =========================================================================
|
||||
|
||||
async _createLimaDisk(opts) {
|
||||
const { diskSizeGB = 30 } = opts;
|
||||
const vmName = 'dashcaddy';
|
||||
const limaDir = path.join(process.env.HOME, '.lima', vmName);
|
||||
|
||||
// Check if VM already exists
|
||||
try {
|
||||
await execAsync(`limactl list ${vmName}`, { timeout: 10000 });
|
||||
return { type: 'lima', vmName, path: limaDir, diskSizeGB, existed: true };
|
||||
} catch {}
|
||||
|
||||
// Create Lima config with fixed disk
|
||||
const config = {
|
||||
vmType: 'qemu',
|
||||
arch: 'x86_64',
|
||||
images: [{
|
||||
location: 'https://cloud-images.ubuntu.com/jammy/current/jammy-server-cloudimg-amd64.img',
|
||||
arch: 'x86_64',
|
||||
}],
|
||||
cpus: 2,
|
||||
memory: '2GiB',
|
||||
disk: diskSizeGB + 'GiB',
|
||||
mounts: [],
|
||||
containerd: { system: false, user: false },
|
||||
provision: {
|
||||
mode: 'system',
|
||||
script: 'apt-get update && apt-get install -y docker.io docker-compose-plugin',
|
||||
},
|
||||
// Forward the API port
|
||||
portForwards: [{
|
||||
guestSocket: '/var/run/docker.sock',
|
||||
hostSocket: path.join(limaDir, 'sock', 'docker.sock'),
|
||||
}],
|
||||
};
|
||||
|
||||
const configPath = path.join(limaDir, 'lima.yaml');
|
||||
await fs.mkdir(path.dirname(configPath), { recursive: true });
|
||||
await fs.writeFile(configPath, require('yaml').stringify ? require('yaml').stringify(config) : JSON.stringify(config, null, 2));
|
||||
|
||||
await execAsync(`limactl start --name=${vmName} ${configPath}`, { timeout: 300000 });
|
||||
|
||||
return { type: 'lima', vmName, path: limaDir, diskSizeGB, existed: false };
|
||||
}
|
||||
|
||||
async _startLima(diskInfo, opts) {
|
||||
const { vmName } = diskInfo;
|
||||
|
||||
// Ensure VM is running
|
||||
try { await execAsync(`limactl start ${vmName}`, { timeout: 60000 }); } catch {}
|
||||
|
||||
const limaExec = (cmd) => execAsync(`limactl shell ${vmName} -- bash -c "${cmd}"`, { timeout: 60000 });
|
||||
|
||||
// Ensure Docker is running
|
||||
await limaExec('service docker start || true');
|
||||
|
||||
return {
|
||||
type: 'lima',
|
||||
name: vmName,
|
||||
dockerContext: 'dashcaddy-lima',
|
||||
dockerDataRoot: '/var/lib/docker',
|
||||
exec: limaExec,
|
||||
};
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// LINUX: Loopback ext4 image
|
||||
// =========================================================================
|
||||
|
||||
async _createLoopbackDisk(opts) {
|
||||
const { diskSizeGB = 30 } = opts;
|
||||
const imagePath = '/opt/dashcaddy-data.raw';
|
||||
const mountPoint = '/opt/dashcaddy-data';
|
||||
|
||||
// Check if already mounted
|
||||
try {
|
||||
const { stdout } = await execAsync('mountpoint -q /opt/dashcaddy-data && echo mounted', { timeout: 5000 });
|
||||
if (stdout.includes('mounted')) {
|
||||
return { type: 'loopback', imagePath, mountPoint, diskSizeGB, existed: true };
|
||||
}
|
||||
} catch {}
|
||||
|
||||
// Create sparse image (only uses space as data fills — starts at ~0 bytes)
|
||||
const sudo = process.getuid && process.getuid() === 0 ? '' : 'sudo';
|
||||
await execAsync(`truncate -s ${diskSizeGB}G "${imagePath}"`, { timeout: 30000 });
|
||||
|
||||
// Format as ext4
|
||||
await execAsync(`${sudo} mkfs.ext4 -F -L dashcaddy "${imagePath}"`, { timeout: 60000 });
|
||||
|
||||
// Mount
|
||||
await execAsync(`${sudo} mkdir -p "${mountPoint}"`, { timeout: 5000 });
|
||||
await execAsync(`${sudo} mount -o loop "${imagePath}" "${mountPoint}"`, { timeout: 10000 });
|
||||
|
||||
// Add to fstab for persistence across reboots
|
||||
const fstabEntry = `${imagePath} ${mountPoint} ext4 loop,defaults 0 0`;
|
||||
await execAsync(`grep -q '${imagePath}' /etc/fstab || echo '${fstabEntry}' | ${sudo} tee -a /etc/fstab`, { timeout: 5000 });
|
||||
|
||||
// Point Docker data-root at the mounted volume
|
||||
await this._configureDockerDataRoot(mountPoint + '/docker', sudo);
|
||||
|
||||
return { type: 'loopback', imagePath, mountPoint, diskSizeGB, existed: false };
|
||||
}
|
||||
|
||||
async _startLoopback(diskInfo, opts) {
|
||||
const { mountPoint } = diskInfo;
|
||||
const sudo = process.getuid && process.getuid() === 0 ? '' : 'sudo';
|
||||
|
||||
// Ensure mounted
|
||||
try {
|
||||
await execAsync(`mountpoint -q ${mountPoint} || ${sudo} mount -o loop ${diskInfo.imagePath} ${mountPoint}`, { timeout: 10000 });
|
||||
} catch {}
|
||||
|
||||
// Restart Docker to pick up new data-root
|
||||
await execAsync(`${sudo} systemctl restart docker`, { timeout: 30000 }).catch(() => {});
|
||||
|
||||
return {
|
||||
type: 'loopback',
|
||||
name: 'dashcaddy-loopback',
|
||||
dockerContext: 'default',
|
||||
dockerDataRoot: mountPoint + '/docker',
|
||||
exec: (cmd) => execAsync(cmd, { timeout: 60000 }),
|
||||
};
|
||||
}
|
||||
|
||||
async _configureDockerDataRoot(dataRoot, sudo) {
|
||||
const daemonJsonPath = '/etc/docker/daemon.json';
|
||||
let daemonJson = {};
|
||||
try {
|
||||
daemonJson = JSON.parse(await fs.readFile(daemonJsonPath, 'utf8'));
|
||||
} catch {}
|
||||
|
||||
daemonJson['data-root'] = dataRoot;
|
||||
|
||||
await execAsync(`${sudo} mkdir -p ${dataRoot}`, { timeout: 5000 });
|
||||
await execAsync(`${sudo} bash -c 'cat > ${daemonJsonPath} << EOF\n${JSON.stringify(daemonJson, null, 2)}\nEOF'`, { timeout: 5000 });
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// DEPLOY + CONFIGURE (shared across platforms)
|
||||
// =========================================================================
|
||||
|
||||
async _ensureDocker(envInfo) {
|
||||
// Docker was installed during VM creation per-platform.
|
||||
// Verify it's actually running.
|
||||
if (envInfo.exec) {
|
||||
try {
|
||||
await envInfo.exec('docker info > /dev/null 2>&1');
|
||||
return;
|
||||
} catch {
|
||||
// Try starting
|
||||
if (this.platform === 'windows') await envInfo.exec('service docker start || true');
|
||||
if (this.platform === 'macos') await envInfo.exec('service docker start || true');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async _deployDashCaddy(envInfo, opts) {
|
||||
const apiPort = opts.apiPort || 3001;
|
||||
const dashboardPort = opts.domain?.mode === 'public' ? null : (opts.dashboardPort || 8080);
|
||||
|
||||
// Inside the VM, download and run DashCaddy
|
||||
// The VM has Docker running — we deploy the same container image
|
||||
const deployScript = `
|
||||
mkdir -p /opt/dashcaddy && cd /opt/dashcaddy
|
||||
curl -fsSL https://get.dashcaddy.net/release/latest.tar.gz | tar xz
|
||||
cd dashcaddy-api && docker build -t dashcaddy-api .
|
||||
docker run -d --name dashcaddy-api --restart unless-stopped \\
|
||||
-p ${apiPort}:${apiPort} \\
|
||||
-v /opt/dashcaddy/data:/app/data \\
|
||||
-v /opt/dashcaddy/status:/app/status \\
|
||||
-v /var/run/docker.sock:/var/run/docker.sock \\
|
||||
-e NODE_ENV=production \\
|
||||
-e PORT=${apiPort} \\
|
||||
dashcaddy-api
|
||||
`;
|
||||
|
||||
if (envInfo.exec) {
|
||||
await envInfo.exec(deployScript.replace(/\n/g, ' && '));
|
||||
}
|
||||
|
||||
let url;
|
||||
if (opts.domain?.mode === 'public') {
|
||||
url = `https://${opts.domain.domain}`;
|
||||
} else if (opts.domain?.mode === 'custom-tld') {
|
||||
url = `https://dashcaddy${opts.domain.tld}`;
|
||||
} else {
|
||||
url = `http://localhost:${dashboardPort || 8080}`;
|
||||
}
|
||||
|
||||
return { success: true, dashboardUrl: url };
|
||||
}
|
||||
|
||||
async _configureServices(envInfo, opts) {
|
||||
// Port forwarding from host to VM
|
||||
if (this.platform === 'windows') {
|
||||
// WSL2 auto-forwards localhost ports to the host
|
||||
return;
|
||||
}
|
||||
if (this.platform === 'macos') {
|
||||
// Lima forwards are configured in the VM config
|
||||
return;
|
||||
}
|
||||
// Linux: container is directly accessible
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// DESTROY (uninstall)
|
||||
// =========================================================================
|
||||
|
||||
async _destroyWSL2(vmInfo) {
|
||||
await execAsync(`wsl --unregister ${vmInfo.name || 'dashcaddy'}`, { timeout: 30000 });
|
||||
// VHDX is deleted by WSL on unregister
|
||||
return { success: true, message: 'WSL2 distro deleted — all data removed' };
|
||||
}
|
||||
|
||||
async _destroyLima(vmInfo) {
|
||||
await execAsync(`limactl delete -f ${vmInfo.name || 'dashcaddy'}`, { timeout: 30000 });
|
||||
return { success: true, message: 'Lima VM deleted — all data removed' };
|
||||
}
|
||||
|
||||
async _destroyLoopback(vmInfo) {
|
||||
const sudo = process.getuid && process.getuid() === 0 ? '' : 'sudo';
|
||||
await execAsync(`${sudo} umount ${vmInfo.mountPoint || '/opt/dashcaddy-data'}`, { timeout: 10000 }).catch(() => {});
|
||||
await execAsync(`rm -f ${vmInfo.imagePath || '/opt/dashcaddy-data.raw'}`, { timeout: 5000 });
|
||||
// Remove from fstab
|
||||
await execAsync(`${sudo} sed -i '\\#${vmInfo.imagePath || '/opt/dashcaddy-data.raw'}#d' /etc/fstab`, { timeout: 5000 }).catch(() => {});
|
||||
return { success: true, message: 'Virtual disk unmounted and deleted — all data removed' };
|
||||
}
|
||||
|
||||
async _exportData(vmInfo, exportPath) {
|
||||
// Export DashCaddy config + service definitions before destroy
|
||||
if (vmInfo.type === 'wsl2') {
|
||||
await execAsync(`wsl -d ${vmInfo.name} -- tar czf /tmp/dc-export.tar.gz /opt/dashcaddy/data /opt/dashcaddy/status`, { timeout: 60000 });
|
||||
await execAsync(`wsl -d ${vmInfo.name} -- cat /tmp/dc-export.tar.gz > "${exportPath}"`, { timeout: 60000 });
|
||||
} else if (vmInfo.type === 'lima') {
|
||||
await execAsync(`limactl shell ${vmInfo.name} -- sudo tar czf /tmp/dc-export.tar.gz /opt/dashcaddy/data`, { timeout: 60000 });
|
||||
await execAsync(`limactl shell ${vmInfo.name} -- sudo cat /tmp/dc-export.tar.gz > "${exportPath}"`, { timeout: 60000 });
|
||||
} else if (vmInfo.type === 'loopback') {
|
||||
await execAsync(`tar czf "${exportPath}" -C ${vmInfo.mountPoint} data`, { timeout: 60000 });
|
||||
}
|
||||
return { success: true, exportPath };
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// STATUS
|
||||
// =========================================================================
|
||||
|
||||
async getStatus() {
|
||||
const info = { platform: this.platform, running: false };
|
||||
|
||||
try {
|
||||
switch (this.platform) {
|
||||
case 'windows': {
|
||||
const { stdout } = await execAsync('wsl -l -v', { timeout: 10000 });
|
||||
info.running = stdout.includes('dashcaddy') && stdout.includes('Running');
|
||||
break;
|
||||
}
|
||||
case 'macos': {
|
||||
const { stdout } = await execAsync('limactl list --json', { timeout: 10000 });
|
||||
const vms = JSON.parse(stdout);
|
||||
info.running = vms.some(v => v.name === 'dashcaddy' && v.status === 'Running');
|
||||
break;
|
||||
}
|
||||
case 'linux': {
|
||||
const { stdout } = await execAsync('mountpoint -q /opt/dashcaddy-data && echo yes', { timeout: 5000 });
|
||||
info.running = stdout.includes('yes');
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
return info;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { VMDiskProvisioner, DISK_PRESETS };
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* VM Disk Budget Step — rendered inside the Electron wizard.
|
||||
* Shows disk size presets, a custom slider, and real-time space check.
|
||||
* Add to wizard.js as a new render step between 'folder' and 'tier'.
|
||||
*
|
||||
* Exported function: renderDiskBudgetStep()
|
||||
* State updates: state.diskBudget.preset, state.diskBudget.customSizeGB
|
||||
*/
|
||||
|
||||
function renderDiskBudgetStep() {
|
||||
const presets = [
|
||||
{ id: 'minimal', icon: '💽', sizeGB: 10, label: 'Minimal', desc: 'DashCaddy only, a few small apps' },
|
||||
{ id: 'balanced', icon: '💿', sizeGB: 30, label: 'Balanced', desc: 'DashCaddy + media tools + containers' },
|
||||
{ id: 'power', icon: '🧊', sizeGB: 100, label: 'Power', desc: 'DashCaddy + heavy apps + lots of containers' },
|
||||
{ id: 'custom', icon: '⚙️', sizeGB: 0, label: 'Custom', desc: 'Pick your own size' },
|
||||
];
|
||||
|
||||
const selectedPreset = state.diskBudget?.preset || 'balanced';
|
||||
const selectedSize = state.diskBudget?.customSizeGB || presets.find(p => p.id === selectedPreset)?.sizeGB || 30;
|
||||
|
||||
return `
|
||||
<div>
|
||||
<h2>Storage Budget</h2>
|
||||
<p>DashCaddy creates a <strong>sandboxed virtual disk</strong> for all its data.
|
||||
It can never exceed this limit — your main drive stays safe.</p>
|
||||
<p class="hint" style="margin-bottom: 20px;">
|
||||
💡 The disk starts nearly empty and only grows as you add apps and data.
|
||||
Deleting DashCaddy removes the entire disk instantly.
|
||||
</p>
|
||||
|
||||
<div class="disk-presets" style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 20px;">
|
||||
${presets.map(p => `
|
||||
<div class="disk-preset-card ${selectedPreset === p.id ? 'selected' : ''}"
|
||||
onclick="selectDiskPreset('${p.id}', ${p.sizeGB})"
|
||||
style="padding: 16px; border: 2px solid ${selectedPreset === p.id ? '#6366f1' : 'var(--border, #333)'}; border-radius: 10px; cursor: pointer; transition: all 0.2s; ${selectedPreset === p.id ? 'background: rgba(99, 102, 241, 0.1);' : ''}">
|
||||
<div style="font-size: 2rem; margin-bottom: 8px;">${p.icon}</div>
|
||||
<div style="font-weight: 600; font-size: 1.05rem;">${p.label}</div>
|
||||
<div style="font-size: 0.85rem; color: var(--muted, #888); margin-top: 4px;">
|
||||
${p.sizeGB > 0 ? p.sizeGB + 'GB' : 'Custom'} — ${p.desc}
|
||||
</div>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
|
||||
${selectedPreset === 'custom' ? `
|
||||
<div class="folder-input" style="margin-bottom: 16px;">
|
||||
<label>Custom Disk Size</label>
|
||||
<div class="input-row" style="display: flex; align-items: center; gap: 12px;">
|
||||
<input type="range" id="disk-slider"
|
||||
min="5" max="500" step="5"
|
||||
value="${selectedSize}"
|
||||
oninput="updateDiskSize(this.value)"
|
||||
style="flex: 1;">
|
||||
<span id="disk-size-display" style="font-size: 1.3rem; font-weight: 700; min-width: 80px; text-align: right;">
|
||||
${selectedSize}GB
|
||||
</span>
|
||||
</div>
|
||||
<p class="hint">Min 5GB, Max 500GB. DashCaddy uses a sparse image — it only consumes real disk space as data fills.</p>
|
||||
</div>
|
||||
` : `
|
||||
<div style="padding: 12px 16px; background: rgba(99, 102, 241, 0.08); border-radius: 8px; border: 1px solid rgba(99, 102, 241, 0.2); margin-bottom: 16px;">
|
||||
<strong>${selectedSize}GB</strong> virtual disk will be created.
|
||||
The sandbox isolates Docker, all containers, and all DashCaddy data inside it.
|
||||
</div>
|
||||
`}
|
||||
|
||||
<div id="disk-space-check" style="margin-top: 12px;"></div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// State management helpers — call from wizard.js
|
||||
function selectDiskPreset(presetId, sizeGB) {
|
||||
if (!state.diskBudget) state.diskBudget = {};
|
||||
state.diskBudget.preset = presetId;
|
||||
if (presetId !== 'custom') {
|
||||
state.diskBudget.diskSizeGB = sizeGB;
|
||||
}
|
||||
checkDiskSpace(sizeGB);
|
||||
render(); // re-render the step
|
||||
}
|
||||
|
||||
function updateDiskSize(val) {
|
||||
const sizeGB = parseInt(val);
|
||||
if (!state.diskBudget) state.diskBudget = {};
|
||||
state.diskBudget.diskSizeGB = sizeGB;
|
||||
state.diskBudget.customSizeGB = sizeGB;
|
||||
document.getElementById('disk-size-display').textContent = sizeGB + 'GB';
|
||||
checkDiskSpace(sizeGB);
|
||||
}
|
||||
|
||||
async function checkDiskSpace(sizeGB) {
|
||||
const el = document.getElementById('disk-space-check');
|
||||
if (!el) return;
|
||||
|
||||
try {
|
||||
const info = await window.electronAPI.getDiskSpace(state.paths.install || '');
|
||||
const freeGB = Math.round(info.free / 1024 / 1024 / 1024);
|
||||
const neededGB = sizeGB + 2; // 2GB buffer for DashCaddy itself
|
||||
|
||||
if (freeGB < neededGB) {
|
||||
el.innerHTML = `<div style="padding: 10px 14px; background: rgba(239, 68, 68, 0.1); border-radius: 6px; border: 1px solid rgba(239, 68, 68, 0.3); color: #f87171; font-size: 0.85rem;">
|
||||
⚠️ Not enough free space. You have ${freeGB}GB free, but need ${neededGB}GB.
|
||||
</div>`;
|
||||
} else {
|
||||
el.innerHTML = `<div style="padding: 10px 14px; background: rgba(34, 197, 94, 0.1); border-radius: 6px; border: 1px solid rgba(34, 197, 94, 0.2); color: #4ade80; font-size: 0.85rem;">
|
||||
✓ You have ${freeGB}GB free — plenty of room for a ${sizeGB}GB disk.
|
||||
</div>`;
|
||||
}
|
||||
} catch {
|
||||
el.innerHTML = '';
|
||||
}
|
||||
}
|
||||
@@ -77,7 +77,6 @@ const bundles = {
|
||||
// window.wireModal + window.injectModal + window.escapeHtml helpers
|
||||
// defined in globals.js (already in core.js).
|
||||
JS('share-modal.js'),
|
||||
JS('i18n.js'),
|
||||
],
|
||||
'onboarding.js': [
|
||||
JS('driver.min.js'),
|
||||
|
||||
Vendored
-1
File diff suppressed because one or more lines are too long
Vendored
+251
-293
File diff suppressed because one or more lines are too long
Vendored
-1
File diff suppressed because one or more lines are too long
Vendored
-1
File diff suppressed because one or more lines are too long
@@ -653,23 +653,6 @@
|
||||
<!-- Will be filled dynamically -->
|
||||
</div>
|
||||
|
||||
<!-- Disk safety info: health checks accumulate data over time -->
|
||||
<div style="margin-top: 16px; padding: 14px 16px; background: color-mix(in srgb, var(--warn-fg, #f39c12) 10%, transparent); border-radius: 8px; border: 1px solid var(--warn-fg, #f39c12);">
|
||||
<div style="display: flex; gap: 10px; align-items: flex-start;">
|
||||
<span style="font-size: 1.2rem; line-height: 1;">💾</span>
|
||||
<div>
|
||||
<strong style="color: var(--warn-fg, #f39c12);">Disk Usage & Health-Check Data</strong>
|
||||
<div style="font-size: 0.85rem; margin-top: 4px; color: var(--muted); line-height: 1.45;">
|
||||
DashCaddy's health checks log response times, uptime history, and incidents for every monitored service.
|
||||
Over time this data accumulates and can consume significant disk space — especially on small VPS or
|
||||
SD-card installs. After setup, open <strong>Health → Configure → Global Settings</strong> to set a
|
||||
<strong>data retention period</strong> (default 30 days), adjust the <strong>polling interval</strong>,
|
||||
and configure a <strong>disk-usage warning threshold</strong> so you're alerted before storage runs low.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="margin-top: 24px; padding: 16px; background: color-mix(in srgb, var(--ok-fg) 10%, transparent); border-radius: 8px; border: 1px solid var(--ok-fg);">
|
||||
<strong style="color: var(--ok-fg);">✓ You can change these settings later</strong>
|
||||
<div style="font-size: 0.85rem; margin-top: 4px; color: var(--muted);">
|
||||
@@ -972,9 +955,6 @@
|
||||
<script src="/js/tailscale-devices.js" defer></script>
|
||||
|
||||
<!-- Bundled JS (built with: npm run build) -->
|
||||
<!-- i18n (language selector + translation system) -->
|
||||
<script src="/js/i18n.js" defer></script>
|
||||
|
||||
<script src="/dist/core.js" defer></script>
|
||||
<script src="/dist/features.js" defer></script>
|
||||
<script src="/dist/onboarding.js" defer></script>
|
||||
|
||||
@@ -34,34 +34,6 @@
|
||||
<div class="panel-empty"><span class="empty-icon">⚙️</span> Loading configuration...</div>
|
||||
</div>
|
||||
|
||||
<!-- Global Settings: retention, polling interval, disk-usage threshold -->
|
||||
<div id="health-global-settings" style="margin-top: 16px; padding: 16px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--card-base);">
|
||||
<h4 style="margin: 0 0 4px;">🌍 Global Settings</h4>
|
||||
<p class="text-muted-sm" style="margin: 0 0 12px;">Applies to all health checks. Settings are stored locally in this browser.</p>
|
||||
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px;">
|
||||
<div>
|
||||
<label class="text-muted-sm">Data Retention (days)</label>
|
||||
<input type="number" id="health-setting-retention" value="30" min="1" max="3650" class="form-input" />
|
||||
<div style="font-size: 0.72rem; color: var(--muted); margin-top: 2px;">Health history older than this is pruned.</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-muted-sm">Polling Interval (seconds)</label>
|
||||
<input type="number" id="health-setting-interval" value="30" min="5" max="3600" class="form-input" />
|
||||
<div style="font-size: 0.72rem; color: var(--muted); margin-top: 2px;">How often each service is checked.</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-muted-sm">Disk-Usage Warning (%)</label>
|
||||
<input type="number" id="health-setting-disk-threshold" value="80" min="50" max="99" class="form-input" />
|
||||
<div style="font-size: 0.72rem; color: var(--muted); margin-top: 2px;">Warn when disk usage exceeds this level.</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="margin-top: 12px; display: flex; gap: 8px; align-items: center;">
|
||||
<button id="health-global-save" class="btn-accent-solid">Save Global Settings</button>
|
||||
<button id="health-global-reset" class="btn-sm">Reset to Defaults</button>
|
||||
<span id="health-global-status" style="font-size: 0.8rem; color: var(--muted);"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Add/Edit Health Check Form -->
|
||||
<div id="health-config-form" style="display: none; margin-top: 16px; padding: 16px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--card-base);">
|
||||
<h4 id="health-form-title" style="margin: 0 0 12px;">Add Health Check</h4>
|
||||
@@ -131,71 +103,6 @@
|
||||
const formCancel = document.getElementById('health-form-cancel');
|
||||
const formSave = document.getElementById('health-form-save');
|
||||
|
||||
// ---- Global health settings (retention, polling interval, disk threshold) ----
|
||||
const HEALTH_SETTINGS_KEY = 'dashcaddy-health-settings';
|
||||
const HEALTH_DEFAULTS = { retentionDays: 30, pollingInterval: 30, diskUsageThreshold: 80 };
|
||||
const globalSaveBtn = document.getElementById('health-global-save');
|
||||
const globalResetBtn = document.getElementById('health-global-reset');
|
||||
const globalStatusSpan = document.getElementById('health-global-status');
|
||||
const retentionInput = document.getElementById('health-setting-retention');
|
||||
const intervalInput = document.getElementById('health-setting-interval');
|
||||
const diskThresholdInput = document.getElementById('health-setting-disk-threshold');
|
||||
|
||||
function loadHealthSettings() {
|
||||
try {
|
||||
const raw = safeGet(HEALTH_SETTINGS_KEY);
|
||||
const saved = raw ? JSON.parse(raw) : {};
|
||||
return Object.assign({}, HEALTH_DEFAULTS, saved);
|
||||
} catch (_) {
|
||||
return Object.assign({}, HEALTH_DEFAULTS);
|
||||
}
|
||||
}
|
||||
|
||||
function applyHealthSettingsToUI() {
|
||||
const s = loadHealthSettings();
|
||||
if (retentionInput) retentionInput.value = s.retentionDays;
|
||||
if (intervalInput) intervalInput.value = s.pollingInterval;
|
||||
if (diskThresholdInput) diskThresholdInput.value = s.diskUsageThreshold;
|
||||
}
|
||||
|
||||
function saveHealthSettings() {
|
||||
const settings = {
|
||||
retentionDays: Math.max(1, Math.min(3650, parseInt(retentionInput?.value) || HEALTH_DEFAULTS.retentionDays)),
|
||||
pollingInterval: Math.max(5, Math.min(3600, parseInt(intervalInput?.value) || HEALTH_DEFAULTS.pollingInterval)),
|
||||
diskUsageThreshold: Math.max(50, Math.min(99, parseInt(diskThresholdInput?.value) || HEALTH_DEFAULTS.diskUsageThreshold))
|
||||
};
|
||||
try {
|
||||
safeSet(HEALTH_SETTINGS_KEY, JSON.stringify(settings));
|
||||
applyHealthSettingsToUI();
|
||||
if (globalStatusSpan) {
|
||||
globalStatusSpan.textContent = 'Saved ✓';
|
||||
globalStatusSpan.style.color = 'var(--ok-fg)';
|
||||
setTimeout(() => { if (globalStatusSpan) globalStatusSpan.textContent = ''; }, 2500);
|
||||
}
|
||||
if (typeof showNotification === 'function') showNotification('Global health settings saved', 'success');
|
||||
} catch (e) {
|
||||
if (globalStatusSpan) { globalStatusSpan.textContent = 'Save failed'; globalStatusSpan.style.color = 'var(--bad-fg)'; }
|
||||
if (typeof showNotification === 'function') showNotification('Failed to save settings: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function resetHealthSettings() {
|
||||
try {
|
||||
safeSet(HEALTH_SETTINGS_KEY, JSON.stringify(HEALTH_DEFAULTS));
|
||||
} catch (_) { /* ignore */ }
|
||||
applyHealthSettingsToUI();
|
||||
if (globalStatusSpan) {
|
||||
globalStatusSpan.textContent = 'Reset to defaults ✓';
|
||||
globalStatusSpan.style.color = 'var(--ok-fg)';
|
||||
setTimeout(() => { if (globalStatusSpan) globalStatusSpan.textContent = ''; }, 2500);
|
||||
}
|
||||
}
|
||||
|
||||
applyHealthSettingsToUI();
|
||||
globalSaveBtn?.addEventListener('click', saveHealthSettings);
|
||||
globalResetBtn?.addEventListener('click', resetHealthSettings);
|
||||
// ---- End global health settings ----
|
||||
|
||||
let editingId = null;
|
||||
|
||||
function uptimeColor(pct) {
|
||||
|
||||
@@ -1,207 +0,0 @@
|
||||
/**
|
||||
* DC-077: i18n Frontend — Language selector and translation system
|
||||
*
|
||||
* Provides window.DCI18n.t(key) for the dashboard frontend.
|
||||
* Loads translations from /api/v1/i18n/translations/:lang
|
||||
* Language preference stored in localStorage.
|
||||
* Handles RTL for Arabic.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const STORAGE_KEY = 'dashcaddy-language';
|
||||
const DEFAULT_LANG = 'en';
|
||||
const SUPPORTED_LANGS = ['en', 'es', 'fr', 'de', 'ar'];
|
||||
const LANG_NAMES = {
|
||||
en: 'English', es: 'Español', fr: 'Français', de: 'Deutsch', ar: 'العربية',
|
||||
};
|
||||
|
||||
let currentLang = localStorage.getItem(STORAGE_KEY) || DEFAULT_LANG;
|
||||
let translations = {};
|
||||
let loaded = false;
|
||||
|
||||
async function loadTranslations(lang) {
|
||||
if (lang === DEFAULT_LANG) {
|
||||
translations = {}; // English is the default — no translation needed
|
||||
loaded = true;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch(`/api/v1/i18n/translations/${lang}`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
translations = data.translations || {};
|
||||
loaded = true;
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[i18n] Failed to load translations for', lang, e);
|
||||
}
|
||||
}
|
||||
|
||||
function t(key) {
|
||||
if (currentLang === DEFAULT_LANG) return key;
|
||||
return translations[key] || key;
|
||||
}
|
||||
|
||||
function setLanguage(lang) {
|
||||
if (!SUPPORTED_LANGS.includes(lang)) return;
|
||||
currentLang = lang;
|
||||
localStorage.setItem(STORAGE_KEY, lang);
|
||||
|
||||
// RTL handling
|
||||
const isRtl = lang === 'ar';
|
||||
document.documentElement.dir = isRtl ? 'rtl' : 'ltr';
|
||||
document.documentElement.lang = lang;
|
||||
|
||||
loadTranslations(lang).then(() => {
|
||||
applyTranslations();
|
||||
});
|
||||
}
|
||||
|
||||
function getLanguage() {
|
||||
return currentLang;
|
||||
}
|
||||
|
||||
function applyTranslations() {
|
||||
// Apply translations to elements with data-i18n attributes
|
||||
document.querySelectorAll('[data-i18n]').forEach(el => {
|
||||
const key = el.getAttribute('data-i18n');
|
||||
const translated = t(key);
|
||||
if (translated && translated !== key) {
|
||||
el.textContent = translated;
|
||||
}
|
||||
});
|
||||
// Apply to placeholders
|
||||
document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
|
||||
const key = el.getAttribute('data-i18n-placeholder');
|
||||
const translated = t(key);
|
||||
if (translated && translated !== key) {
|
||||
el.placeholder = translated;
|
||||
}
|
||||
});
|
||||
// Apply to titles
|
||||
document.querySelectorAll('[data-i18n-title]').forEach(el => {
|
||||
const key = el.getAttribute('data-i18n-title');
|
||||
const translated = t(key);
|
||||
if (translated && translated !== key) {
|
||||
el.title = translated;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function createLanguageSelector() {
|
||||
// Find the top bar area to insert the selector
|
||||
// Look for the auth-settings area or the header actions
|
||||
const targetContainer = document.querySelector('.header-actions') ||
|
||||
document.querySelector('#auth-settings-btn')?.parentElement ||
|
||||
document.querySelector('.top-bar-actions');
|
||||
|
||||
if (!targetContainer) {
|
||||
// If we can't find a target, try to add it near the settings button
|
||||
const settingsBtn = document.getElementById('auth-settings-btn');
|
||||
if (settingsBtn && settingsBtn.parentElement) {
|
||||
return createDropdown(settingsBtn.parentElement);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return createDropdown(targetContainer);
|
||||
}
|
||||
|
||||
function createDropdown(container) {
|
||||
// Check if selector already exists
|
||||
if (document.getElementById('dc-lang-selector')) return;
|
||||
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.id = 'dc-lang-selector';
|
||||
wrapper.style.cssText = 'display: inline-flex; align-items: center; gap: 4px; margin: 0 8px; position: relative;';
|
||||
|
||||
const btn = document.createElement('button');
|
||||
btn.id = 'dc-lang-btn';
|
||||
btn.className = 'lang-selector-btn';
|
||||
btn.style.cssText = 'background: var(--card-base, #2a2a3e); border: 1px solid var(--border, #3a3a4e); color: var(--text-primary, #e0e0e0); padding: 6px 10px; border-radius: 6px; cursor: pointer; font-size: 0.8rem; display: flex; align-items: center; gap: 4px;';
|
||||
btn.innerHTML = `🌐 <span class="lang-current">${currentLang.toUpperCase()}</span>`;
|
||||
btn.title = 'Language / Idioma / Langue / Sprache / اللغة';
|
||||
|
||||
const dropdown = document.createElement('div');
|
||||
dropdown.id = 'dc-lang-dropdown';
|
||||
dropdown.style.cssText = 'display: none; position: absolute; top: 100%; right: 0; margin-top: 4px; background: var(--card-base, #2a2a3e); border: 1px solid var(--border, #3a3a4e); border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); z-index: 9999; min-width: 140px; overflow: hidden;';
|
||||
|
||||
SUPPORTED_LANGS.forEach(lang => {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'lang-option';
|
||||
item.style.cssText = 'padding: 8px 14px; cursor: pointer; display: flex; align-items: center; gap: 8px; font-size: 0.85rem; color: var(--text-primary, #e0e0e0);';
|
||||
item.onmouseenter = () => item.style.background = 'var(--card-hover, rgba(255,255,255,0.05))';
|
||||
item.onmouseleave = () => item.style.background = 'transparent';
|
||||
|
||||
const flag = document.createElement('span');
|
||||
flag.textContent = lang === currentLang ? '✓' : '';
|
||||
flag.style.cssText = 'width: 16px; color: var(--ok-fg, #4ade80);';
|
||||
|
||||
const name = document.createElement('span');
|
||||
name.textContent = LANG_NAMES[lang];
|
||||
|
||||
item.appendChild(flag);
|
||||
item.appendChild(name);
|
||||
item.onclick = () => {
|
||||
setLanguage(lang);
|
||||
dropdown.style.display = 'none';
|
||||
// Update button text
|
||||
btn.querySelector('.lang-current').textContent = lang.toUpperCase();
|
||||
// Update checkmarks
|
||||
dropdown.querySelectorAll('.lang-option').forEach((opt, i) => {
|
||||
opt.querySelector('span').textContent = SUPPORTED_LANGS[i] === lang ? '✓' : '';
|
||||
});
|
||||
// Show notification
|
||||
if (window.showNotification) {
|
||||
window.showNotification(`Language: ${LANG_NAMES[lang]}`, 'info');
|
||||
}
|
||||
};
|
||||
dropdown.appendChild(item);
|
||||
});
|
||||
|
||||
btn.onclick = (e) => {
|
||||
e.stopPropagation();
|
||||
dropdown.style.display = dropdown.style.display === 'none' ? 'block' : 'none';
|
||||
};
|
||||
|
||||
// Close on outside click
|
||||
document.addEventListener('click', (e) => {
|
||||
if (!wrapper.contains(e.target)) {
|
||||
dropdown.style.display = 'none';
|
||||
}
|
||||
});
|
||||
|
||||
wrapper.appendChild(btn);
|
||||
wrapper.appendChild(dropdown);
|
||||
container.insertBefore(wrapper, container.firstChild);
|
||||
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
// Initialize on page load
|
||||
function init() {
|
||||
// Set initial RTL if needed
|
||||
if (currentLang === 'ar') {
|
||||
document.documentElement.dir = 'rtl';
|
||||
document.documentElement.lang = 'ar';
|
||||
}
|
||||
|
||||
// Create the language selector after DOM is ready
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
createLanguageSelector();
|
||||
if (currentLang !== DEFAULT_LANG) loadTranslations(currentLang).then(applyTranslations);
|
||||
});
|
||||
} else {
|
||||
createLanguageSelector();
|
||||
if (currentLang !== DEFAULT_LANG) loadTranslations(currentLang).then(applyTranslations);
|
||||
}
|
||||
}
|
||||
|
||||
// Expose globally
|
||||
window.DCI18n = { t, setLanguage, getLanguage, applyTranslations, loadTranslations };
|
||||
|
||||
// Auto-init
|
||||
init();
|
||||
})();
|
||||
@@ -135,22 +135,6 @@ window.populateTimezoneSelect = function(selectEl, selectedTz) {
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Disk-safety reminder (universal across all config types)
|
||||
html += `
|
||||
<div style="margin-top: 12px; padding: 12px 14px; border-radius: 8px; border: 1px solid var(--warn-fg, #f39c12); background: color-mix(in srgb, var(--warn-fg, #f39c12) 8%, transparent);">
|
||||
<div style="display: flex; gap: 8px; align-items: flex-start;">
|
||||
<span style="font-size: 1.1rem;">💾</span>
|
||||
<div style="font-size: 0.85rem; line-height: 1.45;">
|
||||
<strong style="color: var(--warn-fg, #f39c12);">Disk-space tip:</strong>
|
||||
Health-check monitoring records uptime, response-time, and incident data continuously.
|
||||
By default DashCaddy keeps <strong>30 days</strong> of history and warns at <strong>80% disk usage</strong>.
|
||||
You can tune the retention period, polling interval, and disk threshold later under
|
||||
<strong>Health → Configure → Global Settings</strong>.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
html += '</div>';
|
||||
summaryContent.innerHTML = html;
|
||||
showStep('setup-step-summary');
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
const CACHE = 'dashcaddy-shell-c775f8444e';
|
||||
const CACHE = 'dashcaddy-shell-c4c69c2c4c';
|
||||
const PRECACHE = [
|
||||
'/',
|
||||
'/index.html',
|
||||
|
||||
Reference in New Issue
Block a user