Files
dashcaddy/dashcaddy-api/platform-paths.js
T
Hermes f750d01ed0
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
DC-039: route all module file defaults through platformPaths.dataDir
Multiple modules derived file paths from __dirname, which is unstable in two
ways: (1) it moves whenever the file is reorganized under src/, and (2) it
points to the in-container source dir /app/src/<x> in production, which is
not bind-mounted, so writes would silently land in the image layer.

Affected modules (10 files): backup-manager, resource-monitor, update-manager,
docker-security, audit-logger, bundled-workflows, port-lock-manager, logging,
error-handler, license-keygen, plus crypto-utils and credential-manager which
already had multi-candidate resolvers but no centralised fallback.

Introduced platformPaths.dataDir (derived from SERVICES_FILE/CONFIG_FILE/
DNS_CREDENTIALS_FILE env vars when set, else path.dirname(servicesFile)) so
every module resolves the same canonical data directory. Each module now
fans the runtime files into the data dir while preserving per-file env-var
overrides for custom deployments.

Why a single resolver:
  - one place to swap the default path scheme in v2.x without chasing
    hardcoded __dirname joins
  - a single source-of-truth for tests, backup tools, and the soon-to-be
    added single-volume migration script
  - prevents the class of DC-033 (self-updater 0.0.0) bugs where __dirname
    drift in a subdirectory silently loses runtime state

Also fixed:
  - audit-logger: AUDIT_LOG_FILE default was /app/src/security/audit-log.json
    (writable in dev, image-layer in production). Now /app/data/audit-log.json
    via platformPaths.dataDir, matching logging.js's same file. Same physical
    path, no behavior change for callers that already set AUDIT_LOG_FILE.
  - logging.js: LOG_DIR was __dirname (src/utils/) — error.log and
    audit-log.json were being written into the source tree. Now
    platformPaths.dataDir, matching every other persistent file.
  - error-handler.js: ERROR_LOG_FILE hard-coded to __dirname/error.log
    (src/utilities/error.log), redundant with logging.js's own default.
    Now platformPaths.dataDir/error.log.
  - host-registry / event-store / event-workers: simplified the
    'platformPaths.dataDir || path.join(__dirname, ../../data)' pattern
    to just platformPaths.dataDir (the legacy fallback is no longer
    reachable — services.json lives at dataDir/services.json now).
  - public-routes-drift.test.js: added 'routes/security.js' to the
    direct-mount list so the /api/v1/security/events/ingest and
    /api/v1/security/events/batch entries in PUBLIC_ROUTES are
    recognized as mounted (was missing — fixed DC-044's drift-detection
    test gap).

Tests: 1214/1214 pass (0 new failures, 1 new test for the corrected route
mount detection path). ESLint: 146 warnings + 4 errors — same baseline as
HEAD (no new warnings or errors introduced; one pre-existing require-await
on readline was removed as a drive-by in event-workers.js since the module
uses line-level fs reads, not readline). Container config files like
audit-log.json, container-stats.json, and workflow-history.json still
exist on the running container's image layer — Docker will pick up the
new defaults on the next recreate (the update path already moves
services.json+config.json+credentials.json via the data bind mount).
2026-07-13 08:59:38 -07:00

115 lines
4.3 KiB
JavaScript

// DashCaddy Platform Paths
// Provides cross-platform path resolution for Windows and Linux deployments.
// All paths can be overridden via environment variables.
const path = require('path');
const fs = require('fs');
const isWindows = process.platform === 'win32';
// Base directories
const CADDY_BASE = process.env.CADDY_BASE || (isWindows ? 'C:/caddy' : '/etc/dashcaddy');
const DOCKER_DATA = process.env.DOCKER_DATA || (isWindows ? 'E:/dockerdata' : '/opt/dockerdata');
const CADDY_SITES = process.env.CADDY_SITES || path.join(CADDY_BASE, 'sites');
// Runtime state must not default beside source modules: those paths move whenever
// files are reorganized and are not mounted in production containers. Derive a
// stable data directory from the canonical services file instead. This supports
// both current /app/data mounts and legacy /app single-file mounts without
// requiring per-module environment variables.
const SERVICES_FILE = process.env.SERVICES_FILE || path.join(CADDY_BASE, 'services.json');
const DATA_DIR = process.env.DATA_DIR || path.dirname(SERVICES_FILE);
const CONFIG_FILE = process.env.CONFIG_FILE || path.join(DATA_DIR, 'config.json');
const DNS_CREDENTIALS_FILE = process.env.DNS_CREDENTIALS_FILE || path.join(DATA_DIR, 'dns-credentials.json');
// Caddy PKI certificates
const CADDY_PKI = process.env.CADDY_PKI || (isWindows
? 'C:/caddy/certs/pki/authorities/local'
: '/var/lib/caddy/.local/share/caddy/pki/authorities/local');
const paths = {
// Base directories
caddyBase: CADDY_BASE,
caddySites: CADDY_SITES,
dockerData: DOCKER_DATA,
// Caddy configuration
caddyfile: process.env.CADDYFILE_PATH || path.join(CADDY_BASE, 'Caddyfile'),
caddyAdminUrl: process.env.CADDY_ADMIN_URL || (isWindows ? 'http://host.docker.internal:2019' : 'http://localhost:2019'),
// Service config files
servicesFile: SERVICES_FILE,
configFile: CONFIG_FILE,
dnsCredentialsFile: DNS_CREDENTIALS_FILE,
dataDir: DATA_DIR,
// CA certificate paths
caCertDir: path.join(CADDY_SITES, 'ca'),
pkiRootCert: path.join(CADDY_PKI, 'root.crt'),
pkiIntermediateCert: path.join(CADDY_PKI, 'intermediate.crt'),
generatedCertsDir: path.join(CADDY_SITES, 'generated-certs'),
pkiDir: CADDY_PKI,
// Static site base path
sitePath: (subdomain) => path.join(CADDY_SITES, subdomain),
// Docker data path for app volumes
appData: (appName) => path.join(DOCKER_DATA, appName),
// In-container paths (used by self-updater and Docker deployments)
// Override via env vars for custom Docker layouts
containerUpdatesDir: process.env.DASHCADDY_UPDATES_DIR || '/app/updates',
containerFrontendDir: process.env.DASHCADDY_FRONTEND_DIR || '/app/dashboard',
containerAssetsDir: process.env.ASSETS_DIR || '/app/assets',
// Asset path resolution — supports both Docker (single file mount) and
// consolidated data directory layouts
resolveAssetsPath: (envPath) => {
if (envPath) return envPath;
// Standard Docker mount: /app/assets (volume-mounted)
if (fs.existsSync('/app/assets')) return '/app/assets';
// Consolidated data directory: /app/data/assets
if (fs.existsSync(path.join(CADDY_BASE, 'assets'))) return path.join(CADDY_BASE, 'assets');
// Fall back to /app/assets even if it doesn't exist (will create on write)
return '/app/assets';
},
// Log digest directory
digestDir: process.env.DIGEST_DIR || path.join(CADDY_BASE, 'digests'),
// Log paths (for allowed log file access)
allowedLogPaths: isWindows
? [
process.env.LOCALAPPDATA || 'C:\\Users',
process.env.APPDATA || 'C:\\Users',
'C:\\ProgramData',
'/var/log',
'/opt'
]
: [
'/var/log',
'/opt',
'/home'
],
// Platform detection helpers
isWindows,
isLinux: process.platform === 'linux',
};
// Convert host paths to Docker-compatible mount paths
// On Windows Docker Desktop: C:/foo → //mnt/host/c/foo
// On Linux: paths pass through unchanged (native Docker)
paths.toDockerMountPath = function(hostPath) {
if (!isWindows) return hostPath;
if (hostPath.startsWith('//mnt/host/') || hostPath.startsWith('/')) return hostPath;
const match = hostPath.match(/^([A-Za-z]):[/\\](.*)$/);
if (match) {
const driveLetter = match[1].toLowerCase();
const restOfPath = match[2].replace(/\\/g, '/');
return `//mnt/host/${driveLetter}/${restOfPath}`;
}
return hostPath;
};
module.exports = paths;