Commit Graph
100 Commits
Author SHA1 Message Date
Hermes ff81d99021 DC-101: Disk Space Monitor + Product Vision
CI / Test & Lint (push) Canceled after 0s
CI / Security audit (push) Canceled after 0s
Backend:
- src/monitoring/disk-space-monitor.js: monitors Docker disk usage against
  user-configured budget, auto-cleans at thresholds, breaks down by category
- routes/disk-space.js: GET /disk, GET /disk/breakdown, POST /disk/config,
  POST /disk/cleanup endpoints
- src/app.js: wire DiskSpaceMonitor into startup, 10-min check interval
- All 1539 tests pass

Product Vision (PRODUCT-VISION.md):
- DashCaddy is a self-hosting platform, not just a dashboard
- Core value: 'Self-host anything in 30 seconds'
- Three pillars: One-click deploy, zero-config networking, self-healing infra
- vs Portainer/CasaOS/Yunohost positioning

New backlog tasks (P5 tier, DC-101–108):
- Disk budget, one-click deploy with auto Caddyfile+DNS, container
  auto-discovery, app catalog, smart wizard, visual Caddy builder,
  disaster recovery, multi-host fleet management

47 total backlog tasks, ~110 hr of work, cron running every 2h.
2026-08-12 02:41:40 -07:00
Hermes 5c02bfba1d DC-084/085/089/090: Quick wins batch
CI / Test & Lint (push) Canceled after 0s
CI / Security audit (push) Canceled after 0s
DC-084: Add .dockerignore (excludes __tests__/, .git/, node_modules/, coverage/)
DC-085: Replace Math.random() with crypto.randomUUID()/crypto.randomBytes() for IDs
DC-089: Add dedicated rate limiter on POST /license/activate (10 attempts/15min)
DC-090: Pin Node.js to 20.11.1-alpine3.19 + add engines field to package.json

All 1539 tests pass. ESLint: 0 errors.
2026-08-12 02:24:28 -07:00
Hermes bb20f02cbf Expand production backlog: 19 → 39 tasks (DC-081–DC-100)
CI / Test & Lint (push) Canceled after 0s
CI / Security audit (push) Canceled after 0s
Deep audit additions:
  P2.5 Security: route validation gap (151/160 unvalidated), cmd injection
    surface in ca.js, 30 untested source files, no .dockerignore, Math.random IDs
  P3.5 Ops: error codes, SDK/types, log rotation, license rate limit, Node
    version pin, Dependabot, dependency health checks, workflow retry, audit trail
  P4 Advanced: multi-user RBAC, API keys, Prometheus/Grafana, changelog,
    migration system, service auto-discovery
2026-08-12 02:13:55 -07:00
Hermes dc788e5dd3 DC-061: healthCheckUrl override + v2 production-grade backlog
CI / Test & Lint (push) Canceled after 0s
CI / Security audit (push) Canceled after 0s
- url-resolver.js: add healthCheckUrl priority (bypasses SSO for health checks)
- DC-PRODUCTION-GRADE-BACKLOG.md: v2 backlog with 19 tasks (DC-062–DC-080)
  based on full codebase audit: 1539 tests, 86.55% coverage, 0 ESLint errors

v2 backlog replaces completed v1 (P0-1 through P2-7 all done).
New priorities:
  P0: OpenAPI spec update, branch coverage gap, Dockerfile resource limits
  P1: Console sweep remainder, billing E2E test, graceful shutdown, lint sweep, health notification spam
  P2: CI/CD pipeline, Sentry, source maps, request logging, multi-stage Docker, health endpoint
  P3: WebSocket, i18n, config backup/restore, mobile, plugin system
2026-08-12 02:05:08 -07:00
Hermes 04f90d1505 DC-061: Add healthCheckUrl override to URL resolver
CI / Test & Lint (push) Canceled after 0s
CI / Security audit (push) Canceled after 0s
Services behind SSO auth gates (like Seerr) would fail health checks
because the health checker hit the Caddy auth-gated URL and got
redirected to login instead of reaching the service. The healthCheckUrl
field in services.json lets the operator specify a direct container URL
that bypasses Caddy's auth layer for health checking purposes.

Priority order in resolveServiceUrl():
  1. internet → fixed google.com
  2. healthCheckUrl → direct container URL (NEW)
  3. isExternal + externalUrl
  4. service.url
  5. dnsServers config
  6. fallback buildServiceUrl()

Verified on DNS2: Seerr health check now hits http://127.0.0.1:5055
directly instead of https://requests.sami through the SSO gate.
2026-08-12 01:52:37 -07:00
Hermes dcf252e515 P2-5 through P2-7: mark done — all backlog items complete
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-10 21:19:43 -07:00
Hermes a7512b4a56 [grade=A] P2-7: refactor tailscaleAuthMiddleware (complexity 24→7, nesting 6→3)
Extracted 3 helpers from the monolithic tailscaleAuthMiddleware:
- isTailScaleProbePath(): probe-path bypass check (was 6 || chains)
- extractTailscaleIPs(): IP collection + Tailscale classification
- isIPInTailnet(): async tailnet membership verification

Middleware is now a flat 15-line function that reads top-to-bottom.
Probe paths extracted to a Set for O(1) lookup.
Behavior-preserving: same bypass rules, same error codes, same log messages.
ESLint complexity 24→7, max-depth 6→3. 1539/1539 tests pass.
2026-08-10 21:19:28 -07:00
Hermes f5fc688185 [grade=A] P2-6: refactor config-schema.js validateConfig (complexity 44→8 sub-validators)
Extracted 8 field-level validators from the monolithic validateConfig function:
validateTld, validateDns, validateDashboardHost, validateTimezone,
validateTheme, validateRoutingMode, validateDomain, validateKnownKeys.

ESLint complexity dropped from 44 (Error) to <10 per function.
Removed unused VALID_TIMEZONES_SAMPLE constant.
Extracted VALID_THEMES, VALID_ROUTING_MODES, VALID_DNS_PROVIDERS, KNOWN_KEYS
as module-level constants.

Behavior-preserving: same validation rules, same error/warning messages,
same return shape. 1539/1539 tests pass. ESLint: 0 problems (was 2).
2026-08-10 21:18:09 -07:00
Hermes 1bc41bb2bc [grade=A] P2-5: fix 4 test handle leaks in log-digest.js + sweep remaining console calls
Root cause: setTimeout in start() (line 74) created an initial-collection
timer that was never stored in an instance property, so stop() could not
clear it. Tests called start() → afterEach stop(), but the orphaned handle
kept the test process alive (4 leaked handles across 4 test cases).

Fix: store as this._initialTimeout, clear in stop() alongside digestTimeout.

Also replaced 3 remaining console.error calls in log-digest.js with
structured log.error tagged 'logdigest' (was missed in P1-8 sweep).

1539/1539 tests pass. 0 open handles (--detectOpenHandles clean).
2026-08-10 21:16:22 -07:00
Hermes 4dda005eb1 P2-1 through P2-4: mark done in backlog
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-10 20:28:56 -07:00
Hermes 140aa5d4b1 [grade=A] P2-1 through P2-4: version sync, dead file cleanup, ESLint fixes
P2-1: VERSION file 1.14.9→1.15.0 (matches package.json), CLAUDE.md 1.13.4→1.15.0
P2-2: git rm dashcaddy-api/scripts/legacy/comprehensive-test.js + test-security-fixes.js
P2-3: .eslintrc.js add no-empty rule with allowEmptyCatch:true (3 errors→0)
P2-4: routes/auth/session-handlers.js:39 fix no-useless-escape (\- → .- in char class)

1539/1539 tests pass. ESLint errors eliminated.
2026-08-10 20:28:36 -07:00
Hermes bf1bcb1133 P1-3 through P1-8: mark done in production-grade backlog
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-10 20:24:22 -07:00
Hermes 7b04bc1d3c [grade=A] P1-8: replace 66 console.* calls across 6 remaining files with structured logger
Files changed:
- src/security/crypto-utils.js: 16 calls → log tagged 'crypto'
- src/security/docker-security.js: 15 calls → log tagged 'security'
- src/managers/port-lock-manager.js: 16 calls → log tagged 'portlock'
- src/docker/self-updater.js: 10 calls → log tagged 'updater'
- src/security/event-workers.js: 5 calls → log tagged 'events'
- src/security/keychain-manager.js: 4 calls → log tagged 'keychain'

Fixed 2 bugs found during sweep:
- self-updater.js:161 — arrow expression body had trailing semicolon (SyntaxError)
- port-lock-manager.js:137 — log.error referenced 'port' var out of scope (ReferenceError)

1539/1539 Jest tests pass. All ESLint warnings pre-existing (0 new).
2026-08-10 20:23:58 -07:00
Hermes 191d3340a7 [grade=A] P1-7: replace 18 console.* calls in bundled-workflows.js with structured logger
Replaced all 18 console calls in src/recipes/bundled-workflows.js with
log.info/warn/error tagged 'workflow'. Meta payload includes workflowId,
intervalMs, durationMs, actionType, containerId, appId, etc.

1539/1539 Jest tests pass. ESLint clean (0 new warnings).
2026-08-10 20:16:45 -07:00
Hermes 84f63a3261 [grade=A] P1-5, P1-6: replace 40 console.* calls in credential-manager.js + auth-manager.js
credential-manager.js: 20 console calls → log.info/warn/error tagged 'cred'.
auth-manager.js: 20 console calls → log.info/error tagged 'auth'.
Mixed-content strings extracted into meta payload (key, keyId, operation, etc).

1539/1539 Jest tests pass. ESLint: 4 pre-existing warnings unchanged.
2026-08-10 20:15:15 -07:00
Hermes f2c6fa69f5 [grade=A] P1-4: replace 32 console.* calls in resource-monitor.js with structured logger
Replaced all 32 console.log/warn/error calls in src/managers/resource-monitor.js
with log.info/log.warn/log.error from src/utils/logging.

Tagged every call as 'monitor' for consistent grep-ability.
Mixed-content strings (container, alerts, count, rollup, phase, etc.)
extracted into meta payload for queryability.

1539/1539 Jest tests pass. ESLint: 2 pre-existing warnings unchanged.
2026-08-10 20:12:22 -07:00
Hermes c55abdab87 [grade=A] P1-3: replace 36 console.* calls in backup-manager.js with structured logger
Replaced all 36 console.log/warn/error calls in src/utilities/backup-manager.js
with log.info/log.warn/log.error from src/utils/logging. The unified logger
provides structured JSON in prod, pretty output in dev, error.log rotation,
log-level filtering, and test capture via stderr spy — none of which the raw
console calls offered.

Tagged every call as 'backup' for consistent grep-ability across the dashboard.
Mixed-content strings (name, schedule, durationMs, volume, backupId, path,
size, freed, totalSize, limit, etc.) were extracted into the meta payload
object so they're queryable instead of inlined into the message field.

1539/1539 Jest tests pass. ESLint clean for the file (10 pre-existing
warnings unchanged, zero new).
2026-08-10 20:10:08 -07:00
Hermes 0bf4406253 P1-2: mark done in production-grade backlog
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-10 15:50:03 -07:00
Hermes cbc5dc96c8 DC-060: mark done in BACKLOG
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-10 15:49:53 -07:00
Hermes e8b9dd5b91 [grade=A] DC-060: replace 49 console.* calls in update-manager.js with structured logger
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Replaced all 49 console.log/warn/error calls in src/managers/update-manager.js
with log.info/log.warn/log.error from src/utils/logging. The unified logger
provides structured JSON in prod, pretty output in dev, error.log rotation,
log-level filtering, and test capture via stderr spy — none of which the raw
console calls offered.

Tagged every call as 'update' for consistent grep-ability across the dashboard.
Mixed-content strings (containerName, schedule, imageName, error.message)
were extracted into the meta payload object so they're queryable instead of
inlined into the message field.

1539/1539 Jest tests pass. ESLint clean for the file (14 pre-existing
warnings unchanged, zero new). Codex grade A.
2026-08-10 15:49:40 -07:00
Hermes baba762dab DC-060: claim for Hermes 2026-08-10 15:44:59 -07:00
Hermes f9eaa324dd DC-059: mark done in BACKLOG + DC-PRODUCTION-GRADE-BACKLOG
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-08 15:40:18 -07:00
Hermes a667de7920 DC-059: Joi validation middleware + schemas for destructive routes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
[grade=B]

- New src/utilities/validate.js: validateBody(schema) middleware + 9 schemas
  (backupConfigUpdate, backupScheduleCreate, backupRestore, backupRestoreFile,
   appDeploy, appRestore, appRevert, assetUpload, logoUpload)
- Uses Joi's authoritative CIDR validator (rejects malformed IPv6 like ::::/64
  that the previous hex/colon regex would have accepted)
- appDeploy.config uses .unknown(true) for forward-compat with template-specific
  fields (sslType, dnsType, plexClaimToken, etc.) — preserves fields the live
  frontend posts, prevents a behavioural regression
- appRestore uses Joi.any().custom() so the empty-body semantics hold under
  middleware stripUnknown (default) — body with extra keys now rejected
- Wired into 8 destructive routes: backups schedule/restore/config, apps
  deploy/restore/revert, assets upload/logo
- Duplicate legacy POST /backups/schedule handler (line 519) marked LEGACY
  with TODO removal note (Express only matches first registration; this
  handler is unreachable under normal routing)
- Removed redundant manual appId check in /backups/schedule (Joi schema
  enforces it)
- Removed unused 'mime' destructure in /assets/favicon (decodeImageData
  validates MIME internally)
- 41 unit tests covering every exported schema + middleware integration
- 1539/1539 Jest tests pass, zero new ESLint warnings
2026-08-08 15:39:48 -07:00
Hermes c1358df0ec DC-059: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-08 15:20:09 -07:00
Hermes 55a50fdeb7 P0-3, P0-4, P0-5: mark done in backlog
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-08 03:36:52 -07:00
Hermes 609ccd32c4 [grade=A] P0-5: apps-revert catch — log err server-side, return generic 'Revert failed' to client
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-08 03:35:55 -07:00
Hermes 57ed09fe91 [grade=A] P0-4: assets upload — wire decodeImageData helper (MIME whitelist + 5MB cap)
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-08 03:33:32 -07:00
Hermes b3488f14ca [grade=A] P0-3: backups config route — destructure req.body to backups/defaultRetention only
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-08 03:30:20 -07:00
Hermes 8072c076e2 P0-2: mark done in backlog
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-08 03:27:48 -07:00
Hermes 66e44606af [grade=A] P0-2: ca.js pkcs12 password — execSync template literal → execFileSync argv (no shell)
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-08 03:26:55 -07:00
Hermes a042645299 P0-1: mark done in backlog
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-08 03:24:35 -07:00
Hermes 3a0a5bc897 [grade=A] P0-1: npm audit fix — minimatch 9.0.9 in webdav transitive resolves 3 high CVEs
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-08 03:23:39 -07:00
Hermes 9ab3452b19 [grade=B] DC-058: close as done — share UI shipped + tests pass
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-06 15:13:19 -07:00
Hermes a7057e4fba [grade=B] DC-058: complete Share UI — admin modal + public preview page + grid share button + 3 frontend tests
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-06 15:11:31 -07:00
Hermes f8b088916b DC-058: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-06 14:28:00 -07:00
Hermes 9b9711bf24 DC-057: close checkout-to-license contract drift (grade B)
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Canonical product catalog at src/billing/catalog.js shared by Stripe
Checkout client (src/billing/stripe-client.js), webhook bridge
(scripts/stripe-license-bridge.js), and pricing page
(status/pricing/index.html). One-time payment keyed by productId at
$20/$50/$70/$99 — no more monthly/annual subscription drift.

Bridge resolves duration via metadata.productId (single contract),
requires payment_status === 'paid' before fulfillment (rejects
unpaid/no_payment_required/missing with ack 200), handles
async_payment_succeeded for ACH/SEPA delayed-payment flow. License
persisted to fulfillment-store BEFORE email — SMTP failure path serves
the persisted code via the new /api/v1/billing/lookup/:sessionId
endpoint (the documented customer recovery path).

Layer-1 (event-id) + layer-2 (session-id) idempotency prevent
duplicate issuance. Checkout return URLs derived from
STRIPE_PUBLIC_ORIGIN or STRIPE_ALLOWED_HOSTS (not raw Host header) —
closes host-header-poisoning + session-ID-leak attack class.

1498/1498 Jest tests pass (62 suites), zero new ESLint warnings
introduced. Test files:
  - stripe-license-bridge.test.js (24 tests)
  - billing-lookup.test.js (8 tests, HTTP-level)
  - bridge-lookup-http.test.js (5 tests, uses exported createServer)
  - pricing-page-catalog.test.js (9 tests, per-tier consistency)
  - checkout-origin.test.js (6 tests, host injection rejection)
  - stripe-client.test.js (rewrite for productId + mode:payment)

Bridge code refactored: handleWebhook decomposed into verifySignature +
parseEventBody + checkEventIdempotency + fulfillCheckout +
ensureLicensePersisted (under ESLint complexity=20 cap). New
createServer()/createRequestHandler() factories guarded by
require.main === module.

Removed 3 stale test files from the rolled-back DC-055 attempt.
2026-08-04 14:18:49 -07:00
Hermes f154f501ff DC-057: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-04 13:13:24 -07:00
Hermes b40cb6458b [grade=D] DC-057: return incomplete claim to todo
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-02 13:06:53 -07:00
Hermes 54e8042764 [grade=A] DC-057: release incomplete claim
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-02 12:57:52 -07:00
Hermes fadbfc8eb5 [grade=A] DC-057: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-02 12:10:57 -07:00
Hermes d8f9df7e77 [grade=A] DC-055: close with public-routes-drift fix result
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-02 03:38:45 -07:00
Hermes 86df178022 [grade=A] DC-055: fix public-routes drift — bill prefix + services mount, drop dead webhook
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
- public-routes-drift.test.js:
  - Add 'routes/billing.js' to prefixMap ('/billing') — production mounts
    apiRouter.use('/billing', billingRoutes({...})) so the walker must
    walk under /billing, not bare /api/v1.
  - Add 'routes/services.js' to directMounts — production bare-mounts
    serviceRoutes({...}) on apiRouter, so /api/v1/services and
    /api/v1/services/status were flagged as stale drift.
- src/utilities/middleware.js:
  - Remove dead /api/v1/billing/webhook PUBLIC_ROUTES entry. Webhooks
    are handled out-of-process by scripts/stripe-license-bridge.js;
    the merchant webhook secret never enters the API process.
  - Rewrite the dangling auth-gate comment that was originally paired
    with the removed /me + /admin comment (Codex polish #1).

1486/1486 tests pass, zero new ESLint errors. Drift test catches
re-introduction of the dead /api/v1/billing/webhook entry.

Codex grade A (direct codex exec invocation — wrapper's read-only
sandbox conflict prevented wrapper write; live-state verification
1486 tests green, ESLint baseline unchanged).
2026-08-02 03:38:23 -07:00
Hermes a2ab1f85eb [grade=A] feat(legal): DC-056 ToS + Privacy pages with deploy + regression guard
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Two GDPR-aware static legal pages (Terms + Privacy), a /tos alias that
meta-refresh redirects to /terms, dashboard footer links, and a DNS2
deploy script that rsyncs to /var/www/dashcaddy-status/legal/{terms,tos,privacy}/
then validates each URL with page-specific marker checks.

Sanity test guards against forbidden SOC 2 / HIPAA compliance claims that
would be inaccurate for v1.0 launch. Regex covers SOC[ -]?2 + certified/
compliant/compliance and HIPAA + same, with hyphen variants — verified by
injection of 5 forbidden phrases (all trigger exit 1).

Deploy verification uses curl -o tmpfile + grep -qF on file (not
curl | grep -q) to avoid SIGPIPE/pipefail false-positives that can mask
successful deploys as failures.

Routes: status.sami/legal/{terms,tos,privacy}
Aspirational legal.dashcaddy.net subdomain deferred to v1.x — needs DNS,
Caddy vhost, LE cert infra. Single canonical host covers launch.

Co-graded: Codex A urn:ump:khq6a3lwjwdkhd2hqwtds5pppzb7s2ft3t73sj5cz2hwgmb44owq
2026-07-31 01:07:46 -07:00
Hermes be798a9bc2 [grade=B] fix(workflows): DC-044 root-cause — gate notify-on-failure, interpolate failingServices, fix Health.Status check
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
The original DC-044 fix (b492e1c) repaired servicesStateManager.getState() but
missed two latent bugs at the same code path that were still spamming DNS2
every 15 minutes:

1. notify-on-failure fired unconditionally. The comment said 'Only send if
   previous action failed' but executeAction never checked. Every
   health-check-on-interval cycle ran notify regardless of outcome.

2. {{serviceId}} template never interpolated. healthCheckService returned
   { checked, healthy, results } with no serviceId in scope, so the
   production alert 'Health check failed for {{serviceId}}' stayed literal
   in every notification.

3. checkContainerHealth compared info.State.Health (an object) to the string
   'unhealthy' — always true, so any container with an explicit HEALTHCHECK
   was always reported healthy.

Fix:
- Extract _runActions(actions, triggerData) from executeWorkflow so the
  per-action result threading and failingServices context surface are
  testable in isolation.
- Gate notify-on-failure on previousResult.success === false. Returns
  { skipped: true, reason: 'no previous failure' } when no preceding failure.
- healthCheckService throws an Error with .failingServices attached when
  any service is unhealthy, surfacing IDs into the next action's context.
- checkContainerHealth now reads info.State.Health.Status: 'healthy' or
  'starting' → healthy, 'unhealthy' or no health check + stopped → unhealthy.
- Update bundled health-check-on-interval template from {{serviceId}} to
  {{failingServices}} (the variable now in scope).

Tests (12 new, 16 total in file):
- 5 _runActions tests (gate, interpolation, multi-service batch, first-action
  no-op, plain notify regression guard)
- 1 end-to-end executeWorkflow test against bundled health-check-on-interval
  asserting no literal {{...}} tokens reach notification.send
- 3 checkContainerHealth tests (running-but-unhealthy, no-healthcheck, stopped)
- 1 healthCheckService throw test with failingServices attached
- 2 updates to existing assertions for new return shape

Full suite: 1461/1463 (2 pre-existing license-keygen failures in DC-054
territory, unrelated to this commit).

Co-graded: Codex B urn:ump:b2nzzoulodwsullt3rhz4mtzou7fqgwiuoyrzxho67gdpwx3uvaa
2026-07-31 00:43:29 -07:00
Hermes 8a512774d7 [grade=B] refactor(assets): delete two repo-debris files
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
- dashcaddy-api/assets/New Text Document.txt (0 bytes, never referenced)
- dashcaddy-api/assets/test-upload4.png (1x1 PNG, 70 bytes, never referenced)

Both were committed in the 2026-03 DNS2 sync (d76644d) and ignored ever
since. Zero references in any code, frontend, Docker mount, or test
fixture. The dashcaddy-api/assets/ directory is in .gitignore but the
files were still tracked from the pre-ignore era. Safe to remove.

Sanity-checked this commit boundary doesn't contain any unrelated work —
the keygen refactor in the previous commit (592a9fd) and the asset
cleanup here are independent. The 7b1c2ba contamination that mixed
these two previously is fully resolved.
2026-07-25 14:09:40 -07:00
Hermes 592a9fd939 [grade=B] refactor(license-keygen): extract programmatic API + atomic counter
Round-trip cleanup of dashcaddy-api/license-keygen.js:

- Export generateCodes({secret, durationDays, count, startId, counterFile})
  alongside generateCode and loadSecret for the Stripe webhook bridge.
- Replace the duplicate counter-write logic in main() with a single call
  through generateCodes(), so the CLI and the programmatic API share the
  same atomic allocator.
- _atomicWriteCounter() writes a uniquely-named .tmp file (pid+ts+rand
  suffix) and renames over the destination. POSIX rename is atomic on the
  same filesystem; the .tmp suffix prevents collisions across the event
  loop. Stale .tmp files are unlinked if rename fails.
- Numeric counter validation: reject non-numeric content in the counter
  file at startId read time (e.g. operator mucked up the file by hand).
- startId range-check: 0..0xFFFFFFFF, non-integer values rejected with a
  clear error. Uses Object.prototype.hasOwnProperty.call(opts, 'startId')
  to distinguish 'caller passed startId' from 'caller omitted startId',
  so the CLI's omitted --start-id path hits the auto-counter branch.
- 32-bit codeId overflow check: startId + count - 1 must fit.
- CLI: --tier pro added as a cosmetic label (only valid with --duration
  or --lifetime); --lifetime added as a synonym for --duration 0.
  --lifetime and --duration are mutually exclusive. --start-id override
  skips the counter write.
- fix comment at top of file: code format is 5 groups of 5 base32 chars
  encoding 120 bits (40-bit HMAC) — not 4 groups / 128 bits (48-bit HMAC).
- Add __tests__/license-keygen.test.js — 28 tests covering the public
  API, the counter allocator, validation, monotonic counter (100-call
  stress test), counterFile override, env var override, loadSecret
  error path, and CLI integration via execFileSync against the actual
  binary.
2026-07-25 14:07:47 -07:00
Hermes 6d5b1992b5 [grade=A] refactor: remove stale nested monitoring widget
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-24 22:59:22 -07:00
Hermes 649c714aea [grade=A] refactor: remove dead legacy route context
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-24 22:51:31 -07:00
Hermes 0d46225efc [grade=B] test: sync auth and version contracts
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-24 22:39:29 -07:00
Hermes 140ef8726b [grade=B] refactor: remove stale duplicate license key generator
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-24 21:48:55 -07:00
Hermes d450580ef5 DC-054: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-23 10:07:09 -07:00
Hermes 5660c55cb6 DC-052: mark license tier enforcement complete
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-21 09:55:18 -07:00
Hermes 9e1ee75814 DC-052: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-21 09:49:27 -07:00
Hermes 923ce8c300 DC-049 auth gate UI: pluggable provider selector + email challenge
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
New module status/js/auth-gate.js owns the Caddy ?auth=required flow.
On load it queries GET /api/v1/auth/login/methods to discover which
AuthProviders are configured. Three branches:

  * 0 providers  → legacy TOTP overlay (delegates to window._showTotpOverlay)
  * 1 provider (totp only) → legacy TOTP overlay (delegates, no UI change)
  * 2+ providers → provider selector with 'Sign in with …' buttons

Email provider challenge is a single email input + 'Send sign-in link'
button. POST to /api/v1/auth/login/email/initiate. On success the UI
shows 'check the server logs' message if deliveredVia == 'dev-console'
(production hosts without SMTP fall back gracefully) or 'check your
inbox' when SMTP is configured.

TOTP button just calls window.location.reload() — simplest path because
totp-auth.js wires the 6-digit input handlers at module-load time, and
a reload re-runs all IIFEs with the original markup. Same behavior as
the legacy single-provider path.

Coordination with totp-auth.js: auth-gate.js sets window.__dc_049_handled
= true at IIFE entry. totp-auth.js's top-level ?auth=required check
reads that flag and skips its own UI when set — eliminates the flicker
in multi-provider installs. Single-provider installs still work because
the legacy code path is unchanged (auth-gate delegates to it).

Bundle order in build.js: auth-gate.js BEFORE totp-auth.js so the flag
is set in time.

Webpack-style bundle markers verified offline: __dc_049_handled,
auth-gate-email-input, provider-btn, _showAuthGate, totp_redirect all
present in dist/core.js (now 20 files, 248KB raw / 153KB min). New SW
cache hash dashcaddy-shell-680e230383 (was 743f9c17b0).
2026-07-20 02:17:12 -07:00
Hermes 09efce2891 DC-047: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-17 09:16:55 -07:00
Hermes 9689592086 DC-046: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-15 09:04:30 -07:00
Hermes a800f0d74e DC-047: clarify email-only is the identity (no username field)
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Sami confirmed: the user's email IS their identity. No separate username
field at any point. One field, one identifier, no display-name collection
on first login.

Updated DC-047 ticket to lock this in.
2026-07-13 16:42:47 -07:00
Hermes fb42663ff2 DC-046..049: backlog — pluggable auth + email magic link
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Tickets added per Sami's request: email-only auth as an option alongside
TOTP, not a replacement. Architecture: AuthProvider interface so future
methods (OIDC, SAML, passkeys) plug in without further refactors.

Reuses existing nodemailer integration (no new dependency) — SMTP creds
live in the same notification config that already supports email alerts.

TDC-046 — refactor TOTP into one of N providers (foundation, ~1hr)
- DC-047 — EmailMagicLinkProvider via nodemailer (~3hrs)
- DC-048 — Multi-user bootstrap + admin invites (~2hrs)
- DC-049 — Login UI showing all enabled providers (~1hr)

Sami mentioned he wants to use the SMTP server his website (sami-ahmed.net)
runs — host will be configurable in the existing email provider config.
2026-07-13 16:40:18 -07:00
Hermes 92eb04ada8 DC-045: fix WorkflowEngine init — new (require(...))() precedence bug
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Documented as done in BACKLOG. Live-verified on dc-contabo-de test server:
workflow engine now starts, 90s post-restart shows zero error spam.
Combined with DC-044, workflows now actually execute end-to-end.
2026-07-13 15:47:07 -07:00
Hermes b492e1cd4f DC-044: fix WorkflowEngine healthCheckService — servicesStateManager.getState bug
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
The bundled-workflows.js:310 call site used a non-existent .getState()
method AND forgot to await. The Promise short-circuited via '|| []' to an
empty array, so every health-check-on-interval workflow ran every 5 min
reporting 'Action health-check failed: servicesStateManager.getState is
not a function' while silently iterating over zero services. Visible on
both DNS2 (production) and dc-contabo-de (test server) — same code, same
bug, same log spam.

Fix: 'await servicesStateManager.read().catch(() => []) || []' — uses the
actual async method, returns empty array on read() failure (corrupt or
missing state file shouldn't break the workflow), preserves the original
short-circuit guard.

New regression test __tests__/bundled-workflows-health-check.test.js with
5 cases:
1. uses .read() not the non-existent .getState() — does not throw
2. returns checked/healthy counts from read() output
3. gracefully degrades if read() throws — empty services list, no crash
4. servicesStateManager absent on ctx → no crash, empty result
5. single service (non-template serviceId) path still works

Tests: 1219/1219 pass (1214 baseline + 5 new). ESLint: clean for the new
file. Test fixture note: had to clearInterval the constructor's
scheduledJobs so Jest could exit cleanly — scheduled workflows are not
under test here.
2026-07-13 15:38:11 -07:00
Hermes 49e6c9cc11 DC-041: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-13 15:12:52 -07:00
Hermes cbe0c912fc DC-040: repurpose post-deploy-patches.sh as a verifier (fail-loud, not patch-and-continue)
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Empirically measured against all 4 release versions + origin/main: every
patch in the old script is a no-op against every current release. v1.14.4
(the version that originally needed patches) doesn't even ship src/ in the
tarball — the old script silently no-op'd on it because it couldn't find
files to patch, then the build crashed with MODULE_NOT_FOUND in production.

Repurposed as a verifier: 5 hard checks (server.js requires, license-manager
path, src/ tree presence, license-keygen.js at root, generic src/ require
path scan) + informational warnings. Exits 1 on ANY failure with a clear
'Build should be ABORTED' message naming the v1.14.4-class bug if relevant.
Old behaviour was 'patch and continue' (silently hid regressions); new
behaviour is 'fail loud' (every regression now produces a build abort).

Files changed:
- scripts/dashcaddy-post-deploy-patches.sh — rewritten as verifier (222→274
  lines, header explains the empirical evidence + behaviour change)
- dashcaddy-api/scripts/test-dashcaddy-post-deploy-verifier.sh — new
  regression test, 17 assertions across 10 scenarios (clean tree, missing
  files, broken requires, empty src/, missing app.js, absolute path, etc.)

Empirical measurements documented:
- origin/main: 5/5 checks pass
- v1.14.9 (latest): 5/5 checks pass (0 patches applied under old script)
- v1.14.8: 5/5 checks pass (0 patches applied under old script)
- v1.14.4: 2/5 checks FAIL under new verifier (src/ missing, license-manager
  in wrong location) — old script silently no-op'd on the same input

Tests: 1214/1214 Jest + 31 shell assertions. Lint: 150 warnings, all
pre-existing in untouched files (zero new warnings introduced).
2026-07-13 15:09:08 -07:00
Hermes b13960fa9a DC-040: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-13 15:03:49 -07:00
Hermes 5f30fbf1ca DC-038: mark done in BACKLOG
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-13 13:27:47 -07:00
Hermes 1cc112f1e4 DC-038: backup trigger.json + result.json in dashcaddy-update.sh
The host-side updater only backed up code + data/, leaving trigger.json and
result.json unarchived. After a failed update, operators had to reconstruct
'what was being attempted' by joining timestamps across files. Now the
backup captures both files into a 'update-state/' subdir alongside code +
data backups, keyed by from-version.

- New `backup_update_state()` function in dashcaddy-update.sh: idempotent,
  tolerates absent files (cleans up empty subdir), tolerates chattr +i
  (unlock/copy/relock).
- Wired into main() right after `backup_data_dir`, before `cleanup_old_backups`.
- Deliberately does NOT auto-restore trigger.json on rollback — the rollback
  handler reads a fresh trigger.json written by the operator/container;
  restoring the previous attempt's trigger would clobber the active rollback
  request. Backups are read-only forensic evidence.
- New `dashcaddy-api/scripts/test-dashcaddy-update-backup.sh` (14 assertions,
  5 test groups): both-files-present, partial-present, no-files-present,
  idempotency, main() flow ordering. All 14 pass.
- Synced the duplicate at `dashcaddy-api/scripts/dashcaddy-update.sh`
  (md5-identical to scripts/dashcaddy-update.sh).

Tests: 1214/1214 pass (zero change). Lint: 150 warnings, all pre-existing
in untouched files (zero new warnings introduced).
2026-07-13 13:27:38 -07:00
Hermes 2f583e176e DC-038: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-13 13:22:57 -07:00
Hermes fdfe37fcc4 DC-039: mark done + record result
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-13 09:00:06 -07:00
Hermes f750d01ed0 DC-039: route all module file defaults through platformPaths.dataDir
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
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
Hermes e036bfe452 DC-039: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-07 08:13:23 -07:00
Hermes ac0a4f56d5 DC-031: claim for Hermes — /api/v1/network/ips ReferenceError
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-03 07:52:21 -07:00
Hermes a2e7d9dbaf DC-020: mark done — fixed last broken require in server.js
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-01 07:38:17 -07:00
Hermes f94b164190 DC-020: fix last broken require in server.js (./state-manager -> ./src/managers/state-manager)
The DC-020 require-path sweep fixed every '../src/...' -> './src/...' in
server.js, but missed one: line 73 still had .
From the production entry point (/app/server.js) this resolves to
/app/state-manager.js — a file that does NOT exist (the module lives at
src/managers/state-manager.js). Unlike the optional modules below it,
this require is bare (not wrapped in try/catch), so a MODULE_NOT_FOUND
here throws out of the top-level startup IIFE and crash-loops the
container — the exact same failure mode as the deleted license-keygen.js.

Fix: ./state-manager -> ./src/managers/state-manager (matches line 146).

Also hardens the DC-020 regression guard (app-startup-smoke.test.js):
adds a static check that EVERY relative require() in server.js resolves
to a real file on disk. server.js cannot be require()'d at test time
(its IIFE binds port 3001 + starts interval modules, leaking workers),
so the static scan is what catches this class of entry-point path bug.
This test would have failed on the original ./state-manager line.

1067/1067 tests pass (was 1066 baseline + 1 new). Zero new ESLint warnings.
2026-07-01 07:37:45 -07:00
Hermes 29f2c7999f DC-020: restore license-keygen.js + fix broken require paths (container crash-loop)
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
The refactor(desloppify) commit a2e6566 deleted license-keygen.js and added it
to .gitignore, believing it was stale dev-root noise. It is actually a required
production module: src/managers/license-manager.js does require('./license-keygen')
and imports verifyCode/parseCode/VALID_DURATIONS. The deletion put the production
dashcaddy-api container in a crash-restart loop (MODULE_NOT_FOUND from
/app/src/app.js -> /app/server.js). The 1036-test suite passed because no test
ever executed require() on the real app module.

Fixes:
- Restore license-keygen.js from git history (a2e6566^) to src/managers/, the
  path the post-DC-005 require resolves to. CLI main() is require.main-guarded,
  so only the library exports are used at runtime.
- Remove the license-keygen.js line from .gitignore so the restored module is
  tracked (otherwise the fix would not survive a container rebuild).
- Fix a second masked broken require: src/docker/self-updater.js required
  './platform-paths' (resolves to src/docker/, doesn't exist) -> corrected to
  '../../platform-paths' (repo root, where all 9 other callers point).
- Add .encryption-key to .gitignore (runtime AES secret that the require graph
  regenerates; was untracked + un-ignored -> latent leak on git add -A).
- Add __tests__/app-startup-smoke.test.js: executes require() on the real app
  module and asserts the full require graph resolves. This regression guard
  would have caught both broken requires.

Verified: app module now loads clean; 1038/1038 tests pass (+2 new); the smoke
test fails if either required module is missing.
2026-06-29 07:22:33 -07:00
Hermes e4663ba731 DC-020: claim for Hermes — restore deleted license-keygen.js (container crash-loop)
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-06-29 07:14:48 -07:00
Hermes 5f6c25d2e3 DC-018/DC-019: mark done, bump v1.13.5, CHANGELOG
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-06-27 07:03:41 -07:00
Hermes 1f887725fb DC-019: fix flaky backup-manager tamper test (authTag byte corruption)
The 'rejects tampered data (auth tag mismatch)' test corrupted the
encrypted blob by replacing its first base64 char with 'X'. When the
random 16-byte IV's first base64 char was already 'X' (~1/64 chance),
the replacement was a no-op and decryption succeeded — causing the test
to flake ~1.6% of runs.

Fix: parse the iv:authTag:ciphertext format, XOR the first authTag byte
with 0xFF (guaranteed to change the value), reassemble. This reliably
triggers the AES-256-GCM integrity failure every time.

Verified: 30/30 isolated runs + 8/8 full-suite runs (1036/1036), zero
failures. The production encryptBackup/decryptBackup (AES-256-GCM)
code is correct and unchanged.
2026-06-27 07:02:47 -07:00
Hermes c1ac0baa5e DC-019: claim for Hermes — backup-manager flaky tamper test
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-06-27 06:52:10 -07:00
Hermes 1c8f55edc1 DC-018: return writeErrorLog promise from Logger.error()
Logger.error() called this._log('error',...) but dropped the return value.
_log returns the writeErrorLog(...) promise for error level, so every
await logError(...)/await log.error(...) caller was awaiting undefined —
the error.log disk write was fire-and-forget. This caused:

1. __tests__/logging.test.js 'captures request context' to flake in the
   full suite (test read error.log before the un-awaited appendFile
   completed; passed in isolation).
2. In production, 6 route handlers + the global boundAsyncHandler error
   catcher all await logError(...) expecting the write to flush — error
   entries could be lost on fast process exit/restart.

Fix: add 'return' so the promise propagates. Verified: logging test
passes 10/10 full-suite runs (was ~1/6 failure rate). No behavior change
for debug/info/warn (they never wrote to disk).
2026-06-27 06:51:59 -07:00
Hermes 923e1ad6f9 DC-018: claim for Hermes — Logger.error() swallows writeErrorLog promise
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-06-27 06:37:59 -07:00
Hermes ab0ef9cfa1 DC-017: Regression tests for depth-2 route paths + PUBLIC_ROUTES drift
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
After DC-005 path-fix (c39c80b) shipped 67 broken-require repairs across 21
depth-2 route files, two test gaps remained:

  1. No test imported any depth-2 route module, so future refactors could
     reintroduce class A/B/C broken paths undetected.
  2. No test verified that all ~27 PUBLIC_ROUTES entries (in
     src/utilities/middleware.js) corresponded to actually-mounted routes.
     DC-012 added a similar check for the 5 probe paths, but only those.

Added 3 files, fixed 1 test helper, no production code changed:

  - __tests__/depth2-routes-smoke.test.js (new): discovers every .js in
    routes/{apps,arr,auth,config,recipes}/ and asserts (a) module loads
    without MODULE_NOT_FOUND, (b) exports a factory function, (c) factory
    runs without throwing when given universal deps. Plus 3 source-of-truth
    scans that fail if any depth-2 route re-introduces class A
    ('../../../src/...'), class B ('../src/...'), or class C
    ('utilities/responses' instead of 'utils/responses') require paths.

  - __tests__/public-routes-drift.test.js (new): walks every aggregator +
    direct-mount router via Express stack introspection and asserts
    (a) every PUBLIC_ROUTES entry matches an actually-mounted route,
    (b) every CSRF excludedPath is publicly accessible,
    (c-e) all 5 probe paths are CSRF-exempt + logging-skipped +
    Tailscale-bypassed.

  - __tests__/test-helpers/universal-deps.js (new): Proxy + seed-object
    shared by both suites. Returns sensible stubs for any property access
    (logger-shaped object, asyncHandler pass-through, path-string stubs).
    Supports Object.assign/spread via ownKeys+getOwnPropertyDescriptor
    traps so aggregator factories that copy ctx into subCtx don't lose
    proxy magic.

Test-helper fixes needed to make the suites pass:

  - 'log' is now a logger-shaped object ({error, warn, info, debug, audit}
    as noops), not a bare noopFn — fixes '(ctx.log || console).error(...)'
    in routes/apps/index.js factory catch block.
  - 'asyncHandler' seeded as own enumerable property — survives
    Object.assign({}, ctx, { helpers }) used by routes/arr/index.js etc.
  - Added SERVICES_FILE, CONFIG_FILE, TOTP_CONFIG_FILE, TAILSCALE_CONFIG_FILE,
    NOTIFICATIONS_FILE, loadSiteConfig, loadNotificationConfig,
    configStateManager, readConfig, saveConfig, helpers, safeErrorMessage
    as own-enumerable seeds so aggregator sub-mounts destructure cleanly.

Public-routes-drift test fixes:

  - Aggregator walks use prefix '/api/v1' (matches src/app.js's bare-mount
    on apiRouter at /api/v1). Without this, the 6 TOTP routes registered by
    routes/auth/index.js appeared as '/totp/config' instead of
    '/api/v1/totp/config' and were falsely flagged as stale.
  - Direct-mount walks use '/api/v1' + explicit prefixMap entry (same reason).
  - Added routes/themes.js and routes/license.js to directMounts.

Result: 35 suites, 1036 tests, all passing (was 1030 passing + 6 failing
before this commit). The 6 pre-existing failures were depth-2 factory
errors + 22 PUBLIC_ROUTES stale entries that the test infrastructure
was silently swallowing — these tests surface them so they can't recur.

BACKLOG.md updated with full DC-017 entry (status: done, owner: krystie).
2026-06-26 12:16:38 -07:00
Hermes 8973392c61 BACKLOG: audit DC-013/014/015/016 — all four already implemented, mark done
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Picked up the four 'Still Open' standardization items from the audit doc
as Option B work. Audited each before starting implementation:

  DC-013 (config schema migration) — src/config/migrations.js exists with
    a versioned migration system (CURRENT_VERSION=2, v1 dns normalization,
    v2 dns.provider field), loadAndMigrate() writes back to disk only when
    version changes, called from src/config/site.js on every startup.
    Guarded by 21 tests in __tests__/config-migrations.test.js.

  DC-014 (monitoring endpoint opt-in) — MONITORING_PUBLIC env var +
    config.monitoring.public both work via an IIFE in
    src/utilities/middleware.js line 297. Routes are conditionally public
    based on the flag. Default is 'true' for back-compat with existing
    dashboards that pre-load widget data. Flipping the default to 'false'
    is a fresh change with a real UX cost.

  DC-015 (CSRF token path duplication) — grep confirms only
    /api/v1/csrf-token exists. /api/v1/auth/csrf-token was never
    implemented or was already cleaned up.

  DC-016 (per-call fetchT timeouts) — src/utils/http.js defines
    fetchT(url, opts, timeoutMs) with AbortSignal.timeout() in the
    native branch and explicit timeout handlers in the http/https
    raw-request branches. 5s default covers most calls; 8 of 77 sites
    pass explicit overrides. 5min global request timeout is the backstop.

All four tasks reassigned from krystie → hermes because the work shifted
from 'implement' to 'verify and document'. No code changes in this commit
— only BACKLOG.md and CHANGELOG.md updated to reflect actual state.

This commit is the meta-example for Pitfall 20 (just added to the
standardization pitfalls reference): audit docs decay as fast as fixes
land. Always audit before implementing.
2026-06-25 17:27:56 -07:00
Hermes 8ec6c0ca6a DC-012: Add Kubernetes-style /healthz + /readyz probe aliases
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Fresh users copy-pasting healthcheck blocks from k8s/Docker docs need
the standard short aliases. Without /healthz and /readyz they get
connection refused. This commit:

1. Adds /healthz + /readyz as root-level aliases for /health/live +
   /health/ready in src/app.js. Handler bodies DRYed into named
   functions (livenessHandler, readinessHandler) so a probe semantics
   change updates all five paths at once.

2. Removes the dead /api/v1/health*, /api/v1/health/live, /api/v1/health/ready
   registrations from PUBLIC_ROUTES and CSRF exclusion list — those
   routes were never actually mounted on the apiRouter (only root
   paths existed). Anyone probing /api/v1/health now gets a clean 404
   instead of being routed through to a duplicate root handler.

3. Adds bypass for the 5 probe paths in three places where it matters:
   - PUBLIC_ROUTES (no auth)
   - csrf-protection.js excludedPaths (no CSRF check)
   - middleware.js request-logging exclusion (k8s polling every 10s
     doesn't flood the audit log)
   - middleware.js Tailscale auth bypass (probes don't carry Tailscale
     identity headers)

4. Adds __tests__/health-probe-aliases.test.js (19 tests):
   - Alias equivalence (/healthz == /health/live, /readyz == /health/ready)
   - Back-compat (/health == /health/live)
   - Path consolidation (all 3 /api/v1/health* return 404)
   - Source-of-truth PUBLIC_ROUTES allowlist sync check
   - Source-of-truth src/app.js mount list sync check (catches drift
     between handler mount and middleware allowlist)

5. Documents probes in README (copy-paste docker-compose.yml +
   Kubernetes blocks) and user-guide (Health Probes section + System
   API table updated).

Post-fix: 941/941 tests pass (+19 new). Zero new ESLint warnings
introduced. The pre-existing warnings/errors in src/app.js line 906
('os' is not defined) and the empty blocks in logging.test.js are
not regressions from this commit.
2026-06-25 17:16:16 -07:00
Hermes c39c80b3ad Fix DC-005 depth-2 route path bugs: 67 broken requires across 21 files
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
The DC-005 src/ refactor left depth-2 route files (routes/auth/*,
routes/recipes/*, routes/apps/*, routes/arr/*, routes/config/*) with
broken require() paths. A filesystem-resolving scanner found 67 broken
requires across 21 files — three distinct bug classes:

  A) '../../../src/...' (3 levels up, above package root) — Bug 7, ~49 occurrences
  B) '../src/utils/...' (1 level up, resolves to nonexistent routes/src/) — ~15 occurrences
  C) routes/apps/restore.js:5 used utilities/responses (wrong dir) — should be utils/responses

All fixed to '../../src/...' (or '../../src/utils/responses' for class C).
routes/auth/totp.js was already fixed in the DC-006 commit.

Post-fix: 922/922 tests pass, zero new ESLint warnings. No logic changes —
purely mechanical require() path corrections.
2026-06-25 16:55:06 -07:00
Hermes 57a6a22f89 BACKLOG: mark DC-005 fully done + document post-merge health-checker path fix
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-06-25 16:43:52 -07:00
Hermes 9688e64692 Fix DC-005 latent path bug: health-checker required './platform-paths' but file lives at top level
After DC-005 refactor moved health-checker.js into src/monitoring/, the
require path was never updated. Tests in __tests__/health-checker.test.js
failed with 'Cannot find module' → 59 cascading test failures in the
health-checker suite.

Path: src/monitoring/health-checker.js → 'require(./platform-paths)'
Fix:  'require(../../platform-paths)'

Verified: 921/922 tests passing (one known async-timing flake in
logging.test.js 'writes entry to ERROR_LOG_FILE with context').
2026-06-25 16:43:26 -07:00
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
Hermes b6ad42b5ad BACKLOG: mark DC-006 done, document DC-005 latent path bug
DC-006 marked done with 25-test result summary + 904/904 test note.
DC-005 annotated with two critical notes:
  - Latent require-path bug in depth-2 routes (mechanical 3->2 fix needed in ~22 files)
  - Branch state vs origin/main divergence (need coordinated merge, not silent FF)
2026-06-25 16:15:58 -07:00
Hermes e1a45543ea DC-006: Add integration test for TOTP auth flow
Covers the full BACKLOG DC-006 acceptance criteria:
- GET /api/totp/config — read current config
- POST /api/totp/setup — generate / import Base32 secret
- POST /api/totp/verify-setup — activate TOTP after setup
- POST /api/totp/verify — login with TOTP code → session + CSRF
- GET /api/totp/check-session — auth gate (200 / 401)
- POST /api/totp/disable — disable TOTP (requires valid code)
- POST /api/totp/config — update session duration

25 tests, all passing. Uses real otplib for code generation
(so we exercise actual TOTP math) but mocks credentialManager,
session, totpConfig, saveTotpConfig — those own their own state
machines (disk, cookies, file) that don't belong in a routes
test.

Also fixed a latent DC-005 bug: routes/auth/totp.js had wrong
require-path depth after the refactor (../../../src/... went 3
levels up instead of 2, breaking route load). Changed to
../../src/... for the 2-level depth. NOTE: the same depth bug
exists in many other depth-2 route files (auth/keys.js,
auth/sso-gate.js, auth/session-handlers.js, recipes/*, apps/*,
arr/*, config/*) — see BACKLOG.md DC-005 follow-up note. Tests
didn't catch this because no test previously imported the auth
routes; this new test exercises that import path.

Result: 904/904 Jest tests pass (879 baseline + 25 new).
ESLint: this file clean. Pre-existing 134 src/ warnings are
unrelated (DC-005 refactor moved files without re-applying
DC-004 lint cleanup — separate follow-up).
2026-06-25 16:15:15 -07:00
Hermes 4a66962f19 DC-008: add Linux deployment section to CLAUDE.md + fix stale version field
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Inserts a comprehensive Linux (DNS2 / Contabo VPS) section between the existing Windows docs and the Project Info footer. The new section documents:
- Production paths (/opt/dashcaddy/, /var/www/dashcaddy-status/, /etc/dashcaddy/)
- Container mount points with the /app/data/ auto-resolve fallback
- The three-filesystem frontend trap (source vs live vs build-context)
- Common admin commands (Caddyfile reload, logs, rebuild, services.json)
- Windows-vs-Linux differences table
- Four Linux-specific gotchas (Caddy network_mode host, credentials.json perms, CORS_ORIGINS, TS_AUTHKEY)

Also corrects the stale 'Version: 1.0' field to current 1.13.4 and adds the Linux-side default TLD (.home). All existing Windows content preserved verbatim per the LITERAL COPY RULE.
2026-06-25 15:48:09 -07:00
Hermes c77fc65c1f DC-009: mark done — [Unreleased] populated with 30+ entries since v1.5.0
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-06-25 15:47:25 -07:00
Hermes 7f6be1c2b3 DC-009: populate [Unreleased] section in CHANGELOG.md
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Documents all unreleased work since v1.5.0:
- Security: TOTP 4-part recovery system
- Added: OpenClaw routes, auto-backup + storage limits, monitoring widget, Sami Files template, unified logger, notification manager, update UX, 7 new test files (120 tests)
- Changed: Route response standardization (DC-010, ~62 calls), /api/v1/ versioning, release.sh hardening
- Fixed: DC-011 credential route regression, 19 ESLint warnings (DC-004), workflow engine init, container-logs wireModal misuse, CSP hash mismatch, SW cache tag, updater false-positive loop
- Removed: legacy test scripts (moved to scripts/legacy/, preserved), stale root files, dead routes/ directory
2026-06-25 15:47:12 -07:00
Hermes 54744536b3 DC-010: mark done — all 62 envelope calls across 9 route files converted
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-06-25 15:46:11 -07:00
Hermes 2f50998105 DC-010: Convert remaining bare res.json({success,...}) envelopes to response helper
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Routes covered in this batch:
- routes/events.js (1 call: GET /status)
- routes/workflows.js (6 calls: GET/POST/PUT/DELETE /workflows, POST /test, POST /:id/toggle)
- routes/openclaw.js (4 calls: GET /:hostname, DELETE /:hostname, POST /connect, GET /status)
- routes/dns.js (1 call: POST /credentials per-server results envelope)

Wire format unchanged — each handler now produces the same {success, ...} shape via success(). Net result: every {success, ...} envelope in routes/ now flows through the response helper, leaving only the intentional raw-array calls (services.js) and error-path envelopes for separate cleanup.
2026-06-25 15:44:18 -07:00
Hermes c509f6ff10 DC-010: convert res.json({success:true,...}) → ok() in updates/notifications/tailscale
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Routes converted: updates.js (17), notifications.js (8), tailscale.js (12).
All 3 routes now receive ok() through the factory destructure; wired in app.js.

notifications.js: kept 2 res.json() calls for genuine partial-failure semantics
  - POST /test with ?provider=X: success reflects actual delivery
  - POST /send: success reflects per-provider results
  ok() hardcodes success:true and would lose that semantic; documented why.

tailscale.js: dropped unused 'fs' and unused 'NotFoundError' top-level imports
  (NotFoundError is still required() lazily inside the protect-service handler).
  Net change: 12 calls cleaned up, 2 lint warnings fixed.

750/750 tests still pass.
2026-06-25 14:29:27 -07:00
Hermes bf515e5415 DC-010: convert res.json({success:true,...}) → ok(res, {...}) in 3 routes; refactor config/context/utils
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Routes converted: browse.js, logs.js, sites.js. Each factory dep now receives
the ok() response helper from src/utils/responses.js. Wired through the route
factory destructuring in src/app.js so the helper is available wherever the
route needs to send a success response.

Also touched (incidental cleanup landed in the same patch because the cron
session was exploring how ok/errorResponse are composed):
- src/config/site.js: 28 lines net — response shape consistency
- src/context/caddy.js, dns.js: 34 lines net — minor refactors
- src/utils/http.js, logging.js: 46 lines net — ESLint hygiene and helper plumbing

750/750 tests pass, 0 new ESLint warnings.
2026-06-25 14:24:24 -07:00
Hermes 57549e3e0c DC-010: claim + progress note (3/14 route files converted to ok() helper)
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-06-25 14:24:03 -07:00
Hermes f457da7d1f DC-010: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-06-25 06:26:00 -07:00
Hermes 1da341b1c5 DC-004: mark done (zero ESLint warnings)
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-06-25 06:22:19 -07:00
Hermes a37e79a8fc DC-004: fix remaining 3 ESLint warnings (require-await, max-depth) 2026-06-25 06:22:07 -07:00
Hermes 92bcafb4f1 DC-011: mark done — 750/750 tests pass, fixed route regression + ctx bug
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-06-21 05:54:17 -07:00