Commit Graph
28 Commits
Author SHA1 Message Date
Hermes 283121edba Merge krystie-improvements into main
Resolves 24 conflicts between Hermes (DC-008/009/010 + response-helper
envelope standardization) and Krystie (DC-005 src/ refactor path fixes,
DC-006 TOTP integration, DC-007 new test suites, cloud backup
destinations).

Conflict resolutions:
- src/utils/logging.js:    took ours (consumers depend on logError/
                            safeErrorMessage/createLogger exports)
- src/config/site.js:      merged (her factored validateAndLogConfig +
                            applyConfigFields helpers)
- src/context/dns.js:      took hers (admin/readonly role iteration for
                            write operations)
- src/utilities/backup-
  manager.js:              took hers (Dropbox/WebDAV/SFTP cloud feature)
- status/dist/*, status/
  sw.js:                   took hers (minified bundles + newer SW cache)

Additional fix (post-merge regression):
- src/monitoring/health-checker.js: fixed DC-005 path miss —
  'require(./platform-paths)' → 'require(../../platform-paths)'

Test status: 921/922 passing. One known failure in logging.test.js
(async file-handle timing) tracked as follow-up.
2026-06-25 16:43:10 -07:00
Krystie 4853f1feb8 fix(server): unbreak workflow engine init - import fetchT, new NotificationManager, hoist servicesStateManager
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Three cascading bugs in server.js's workflow engine init block:

1. fetchT was referenced but never imported from ./src/utils/http
2. notification-manager was called as factory function but the module
   now exports a class (NotificationManager) - need 'new'
3. servicesStateManager was referenced in workflowCtx but only created
   later inside an async IIFE (out of scope at workflow init time)

Result: every container start logged
  Workflow engine failed to initialize - fetchT is not defined
and the workflow engine never actually wired to resourceMonitor/
updateManager event sources. The 'app' context workflow engine
still ran but didn't get those connections.

Fix:
- Import fetchT at top of file
- Use 'new' for NotificationManager instantiation
- Hoist servicesStateManager creation before workflow init and
  remove the duplicate inside the health-checker async IIFE

Verified: container restart shows
  [server] Workflow engine initialized
  [ResourceMonitor] Workflow engine configured
  [UpdateManager] Workflow engine configured
in the log, no more errors at startup.

Also bumps VERSION to current SHA (bump from c64bbe2).
2026-06-18 20:15:23 -07:00
Hermes 7bc2a207f3 DC-005: Fix all 138 broken test paths after src/ refactor
After the DC-005 module reorganization (41 files moved into src/ subdirs),
138 test suites failed because the refactor script's path-rewrite logic
missed three categories:

1. Files inside src/ doing 'require("./src/...")' — should be 'require("../...")'
2. Files in src/X/Y/ doing 'require("../../../src/...")' — should be 'require("../../...")'
3. Test files in __tests__/ with leftover 'require("../../../src/...")' paths

Root cause: the original refactor script ran before all files were moved,
so it computed relative paths against stale filesystem state.

Result:
- 30/30 test suites pass
- 879/879 tests pass (was: 18/30 suites, 614/687 tests)

Also fixed:
- routes/apps/restore.js: wrong responses import path
- routes/*/*.js: '../../src/utilities/X' → '../src/utilities/X' (depth 2 routes)
2026-06-13 12:16:56 -07:00
Hermes 1fbe65f524 Standardize paths, add version endpoint, request timeouts, HOST env var, graceful shutdown
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Cross-platform hardening — removes all hardcoded /app/ paths from route files
and routes them through platform-paths.js so the app works the same way
regardless of Docker layout (single-file mount vs consolidated data dir).

Changes:
- platform-paths.js: add generatedCertsDir, pkiDir, containerUpdatesDir,
  containerFrontendDir, containerAssetsDir, resolveAssetsPath()
- self-updater.js: UPDATE_URL/MIRROR_URL/CHANNEL env var overrides
- routes/ca.js: use platformPaths for cert paths and generated certs dir
- routes/services.js: use platformPaths.pkiRootCert
- routes/themes.js: derive THEMES_DIR from platformPaths.servicesFile
- routes/config/assets.js + backup.js: use resolveAssetsPath() fallback
- routes/services.js + src/app.js: use platformPaths.pkiRootCert
- server.js: HOST env var support, parse PORT as int
- src/app.js: GET /api/v1/version (public, no auth), global request timeout,
  disable x-powered-by, trust proxy
- pylon/dashcaddy-pylon.js: PYLON_HOST env var, graceful shutdown on SIGTERM/SIGINT

A fresh user can now deploy with a custom Docker layout (e.g. /opt/dc/data/
as a single volume mount) and the app finds its files automatically, no env
var configuration required.
2026-06-10 19:36:05 -07:00
Hermes 1c0d765182 fix: app route path nesting (deploy/remove/templates), server.js fetchT import, lifetime license expiry, workflows path prefix
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
- routes/apps/index.js: mount sub-routers at '/' to avoid double-nesting (was /deploy/deploy, now /deploy)
- server.js: add fetchT import for workflow engine init
- license-manager.js: fix isExpired() for lifetime licenses (null expiresAt → always expired)
- src/app.js: add '/workflows' path prefix to prevent requirePremium gating all routes
- app-templates.js: fix 10 templates missing volumes/healthCheck
- routes/apps/index.js: add e.stack to error logging for better debugging
2026-06-10 16:20:51 -07:00
Hermes 11823a1466 feat: premium tier features — auto-backup scheduling, resource alerting, bundled workflows, one-click revert, notification manager 2026-05-27 23:39:46 -07:00
Hermes 17edb3bc90 Fix 5 critical security vulnerabilities
1. WebSocket exec auth bypass (exec.js): Require valid JWT or API key
   before accepting WebSocket upgrade. Reject unauthenticated requests
   with 401 before the upgrade completes.

2. Shell injection in router auto-login (session-handlers.js): Validate
   baseUrl against safe hostname pattern before embedding in wget shell
   command. Reject with null session if invalid.

3. Path traversal in credentials routes (services.js): Add explicit
   serviceId validation (alphanumeric + dash/underscore/dot, max 100
   chars) to all three credential endpoints. Removed redundant
   try/catch wrapper.

4. execSync injection in CA CSR generation (ca.js): Add sanitize step
   replacing any non-alphanumeric domain chars with underscore before
   interpolation into shell subj argument. Redundant with existing
   validation but provides defense-in-depth.

5. Auth bypass when TOTP disabled (middleware.js): Split the logic
   cleanly — disabled TOTP means no auth (initial setup state), enabled
   TOTP means all auth methods checked (session/JWT/API key). Removed
   the sessionDuration:never conflating shortcut.
2026-05-27 18:05:35 -07:00
Krystie 0c658a26a8 fix(routes): complete post-refactor dependency wiring cleanup 2026-05-04 16:44:18 -07:00
SamiandClaude Opus 4.6 bdf3f247b1 feat: add 7 new features — exec shell, SSE events, compose import, docker resources, resource limits, email notifications, auto-updates
- Container exec/shell via WebSocket + xterm.js (subtle >_ button on cards)
- Live dashboard updates via SSE (resource alerts, health changes, update notices)
- Docker Compose import with YAML parsing, preview, and dependency-ordered deploy
- Volume & network management modal with disk usage overview
- CPU/memory resource limits on deploy and live update
- Email SMTP notifications (nodemailer) alongside Discord/Telegram/ntfy
- Scheduled auto-update scheduler with maintenance windows (daily/weekly/monthly)

New deps: ws, js-yaml, nodemailer

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 16:15:14 -07:00
Krystie 5da1e572a1 refactor(server): Complete Phase 2.1 - Split monolithic server.js
MASSIVE REFACTOR:
- Created src/app.js (17KB) - Express setup, middleware, routes
- Slimmed server.js from 1997 lines → 230 lines (88% reduction!)
- Backed up original as server-old.js for reference

NEW STRUCTURE:
src/
├── app.js (Express application factory)
├── config/ (paths, site config, constants)
├── context/ (DI container, domain modules)
└── utils/ (http, logging, responses, async-handler)

STATS:
- Old server.js: 1997 lines (monolith)
- New server.js: 230 lines (entry point only)
- Modular code: 1729 lines across 14 files in src/
- Total reduction: 88% in main file

server.js now ONLY handles:
- App creation
- License loading
- HTTP server startup
- Feature module initialization
- Graceful shutdown

All business logic moved to src/ modules. Clean, testable, maintainable.

Phase 2.1 COMPLETE 
2026-03-29 19:46:41 -07:00
Krystie 64a0018d00 Unified error handling system
- Consolidated all error classes into single errors.js
- Removed duplicate error definitions (NotFoundError, etc.)
- Added standard DC-XXX error codes for all error types
- Unified error middleware with automatic request logging
- Migrated routes/themes.js to throw-based error pattern
- Updated routes/services.js to use ConflictError
- Cleaner server.js error handler registration
- 40% less error handling boilerplate in routes
- Consistent error response format across all endpoints
2026-03-29 18:46:02 -07:00
Krystie 51d6c37e4a refactor(routes): Phase 3.6-10 - standardize 5 utility routes
- credentials.js (2 deps: credentialManager, asyncHandler)
- backups.js (2 deps: backupManager, asyncHandler)
- license.js (2 deps: licenseManager, asyncHandler)
- errorlogs.js (3 deps: ERROR_LOG_FILE, auditLogger, asyncHandler)
- themes.js (0 deps! Standalone route)

Total: 9 routes refactored so far
2026-03-28 19:32:01 -07:00
Krystie f095ef24aa refactor(routes): Phase 3.5 - standardize monitoring.js (only 3 deps!) 2026-03-28 19:30:03 -07:00
Krystie 970e862533 refactor(routes): Phase 3.4 - standardize dns.js with explicit dependencies
- Replaced god object ctx with explicit dependency injection
- Added JSDoc documenting required dependencies (7 deps vs 50+)
- Updated response calls to use response-helpers (success/error)
- Dependencies: dns, siteConfig, asyncHandler, log, safeErrorMessage, fetchT, credentialManager
- DNS record management, Technitium proxy, credential storage all preserved
- 632 lines, now self-documenting and testable
2026-03-28 19:28:17 -07:00
Krystie eac4ede21e refactor(routes): Phase 3.3 - standardize health.js with explicit dependencies
- Replaced god object ctx with explicit dependency injection
- Added JSDoc documenting required dependencies (8 deps vs 50+)
- Updated response calls to use response-helpers (success/error)
- Self-documenting: you can see exactly what this route needs
- Health checks, pylon relay, CA cert validation all preserved
2026-03-28 19:25:06 -07:00
Krystie 4e2bec2ef0 refactor(routes): Phase 3.2 - standardize containers.js with explicit dependencies
- Replaced god object ctx with explicit dependency injection
- Added JSDoc documenting required dependencies (only 3!)
- Updated response calls to use response-helpers (success)
- Dependencies: docker, log, asyncHandler (vs 50+ ctx properties)
- Self-documenting and testable
2026-03-28 19:23:39 -07:00
Krystie 13d612df5d refactor(routes): Phase 3.1 - standardize services.js with explicit dependencies
- Replaced god object ctx with explicit dependency injection
- Added JSDoc documenting all required dependencies
- Updated response calls to use response-helpers (success/error)
- Maintained all existing functionality
- Self-documenting: you can see exactly what this route needs
- Easier testing: mock only what's actually used (14 deps vs 50+ ctx properties)
2026-03-28 19:22:42 -07:00
Sami cc8073256a refactor: Phase 2 - add error handling modules and response helpers 2026-03-28 19:01:24 -07:00
Sami 6c3848102b refactor: Phase 1 code cleanup - constants, logging, and repository organization 2026-03-28 18:54:39 -07:00
SamiandClaude Opus 4.6 fc6275a96b feat: add Pylon health relay for remote service health checks
DashCaddy Pylon is a lightweight probe agent that runs on remote
networks to relay health checks for services the main DashCaddy
instance can't reach directly (e.g., .sami domains, LAN IPs).

- Standalone zero-dependency Node.js script (pylon/dashcaddy-pylon.js)
- Optional API key auth, HEAD→GET fallback, batch probe support
- Health routes now try direct check first, fall back to pylon relay
- New endpoints: /health/probe (act as pylon), /health/pylon (status)
- Config: add "pylon": { "url": "...", "key": "..." } to config.json

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 15:52:43 -07:00
SamiandClaude Opus 4.6 2815233e86 Unify URL resolution, add health checker sync, and make modules optional
- Add url-resolver.js with single resolveServiceUrl() used by all 5 consumers
  (probes, health routes, health checker auto-config)
- Health checker now does full sync (add/update/remove) instead of add-only,
  and re-syncs automatically after every services.json mutation
- docker-maintenance and log-digest are now optional imports with try/catch,
  preventing container crashes when these files are absent
- Add null guards in routes/logs.js for graceful 503 responses

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 23:01:20 -07:00
SamiandClaude Opus 4.6 70b818c2bd Fix Tailscale route prefix mismatch and increase health check timeout
Mount Tailscale router at /tailscale prefix so all 10 routes resolve
to /api/tailscale/* as expected by middleware, audit logger, and
frontend. Previously 5 routes (status, config, check-connection,
devices, protect-service) resolved to /api/* instead, with config
colliding with the settings route. Strip redundant /tailscale/ prefix
from OAuth routes that were compensating for the missing mount prefix.

Increase default health check timeout from 10s to 20s to reduce false
positives on slower services.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 18:44:20 -07:00
SamiandClaude Opus 4.6 e615f24627 Add Docker hygiene, deployment manifests, and daily log digest
Prevents Docker disk bloat by adding log rotation (10MB max, 3 files)
to all container creation and update paths, auto-pruning dangling
images after deploy/remove/update, and a daily maintenance module
that cleans build cache and warns on disk thresholds.

Saves a deployment manifest in services.json at deploy time so users
can restore all their apps after a Docker purge. Adds restore-all
and restore-single endpoints that recreate containers, Caddy config,
and DNS records from the saved manifests.

Adds an hourly log collector and daily digest generator that
summarizes errors, warnings, and events across all services into
a single human-readable report with guidance on where to investigate.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 21:41:40 -07:00
SamiandClaude Opus 4.6 ffa6966fd3 Add auto-update system for DashCaddy instances
- self-updater.js: polls for new versions, downloads/verifies tarballs,
  triggers host-side rebuild via systemd path unit
- dashcaddy-update.sh + systemd units: host-side container rebuild with
  automatic rollback on health check failure
- 7 new /api/v1/system/* endpoints for version info, update check/apply,
  rollback, and update history
- Frontend: DashCaddy tab in Updates modal with version display,
  changelog, update button, rollback, and notification dot
- install.sh: updater service installation, volume mounts, env vars
- build-release.sh + webhook-handler.js: release server pipeline
  (Gitea webhook → build tarball → deploy to get.dashcaddy.net)
- Dockerfile: DASHCADDY_COMMIT build arg → VERSION file
- Version bump to 1.1.0

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 03:11:35 -08:00
SamiandClaude Opus 4.6 59b6d7d360 Fix 16 HIGH/MEDIUM security bugs across API
HIGH fixes:
- TOTP disable now requires valid code verification
- TOTP secret removed from plaintext file storage
- Container ID validated before update/check-update/logs operations
- DNS server parameter restricted to configured servers (SSRF prevention)
- Backup export no longer includes encryption key
- Backup restore of sensitive files requires TOTP re-authentication

MEDIUM fixes:
- Session cookie Secure flag added
- Caddy reload errors no longer leaked to client
- saveConfig uses atomic locked updates via configStateManager
- Log file path traversal prevented via symlink resolution
- Credential cache entries now expire after 5 minutes
- _httpFetch enforces 10MB response size limit
- External URL path injection into Caddyfile blocked
- Custom volume host paths validated against allowed roots
- Error logs endpoint no longer returns stack traces
- Logo delete path traversal prevented via path.basename()

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 00:15:28 -08:00
SamiandClaude Opus 4.6 3a6d2ce93d Fix input validation and error handling across API endpoints
- Deploy endpoint: validate appId, config, and subdomain before use (prevents 500 crash on empty body)
- Container ops: return 404 instead of 500 for non-existent containers
- Update-subdomain: require oldSubdomain/newSubdomain fields (prevents false 200 with undefined values)
- Global error handler: catch-all that never leaks stack traces or internal paths
- API 404 catch-all: return JSON instead of HTML for unmatched /api/* routes

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 20:21:21 -08:00
SamiandClaude Opus 4.6 77030931b7 Add subdirectory routing mode for public domain deployments
Apps can now be served at domain.com/appname/ instead of requiring
subdomain DNS records (appname.domain.com). Supports three subpath
modes per template: native (URL base env var), strip (handle_path),
and none (incompatible warning). Tested on Linux with deploy/removal
lifecycle verified.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 03:03:17 -08:00
Sami f61e85d9a7 Initial commit: DashCaddy v1.0
Full codebase including API server (32 modules + routes), dashboard frontend,
DashCA certificate distribution, installer script, and deployment skills.
2026-03-05 02:26:12 -08:00