Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53680c4c74 | ||
|
|
2d394d882d | ||
|
|
11cfb8c26a | ||
|
|
caa09dcebe | ||
|
|
264de9644c | ||
|
|
e40cb35011 | ||
|
|
7485772427 | ||
|
|
e5d7da6edd | ||
|
|
28f0fa3c10 | ||
|
|
eee32c1eae | ||
|
|
37a3282f98 | ||
|
|
1fbe65f524 | ||
|
|
320f21c113 | ||
|
|
5c76c3df97 | ||
|
|
260575c6bd |
@@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.13.4] - 2026-06-12
|
||||
|
||||
### Changed
|
||||
- Standardized all route handler responses to use helpers from `src/utils/responses.js`
|
||||
(`ok`, `errorResponse`, `successMessage`, `notFound`, `validationError`, `forbidden`,
|
||||
`unauthorized`, `conflict`). ~160 raw `res.json()` calls converted across 32+ files.
|
||||
No behavior changes — response shapes are identical. This ensures future schema
|
||||
changes (e.g., adding a `requestId` envelope) only need to update one module.
|
||||
- Fixed `error` vs `errorResponse` signature mismatch in `routes/health.js` CA cert
|
||||
endpoint. The `error` helper takes `(res, message, statusCode)` while `errorResponse`
|
||||
takes `(res, statusCode, message, extras)` — the wrong alias was being used for
|
||||
calls that needed the 4-argument form.
|
||||
- Updated `middleware.js`, `csrf-protection.js`, `error-handler.js`, and
|
||||
`license-manager.js` to use response helpers for rejection/error responses
|
||||
instead of inline `res.status().json()`.
|
||||
|
||||
### Note
|
||||
- 4 pre-existing test failures in `services.routes.test.js` (credential storage)
|
||||
remain from before this release. They are unrelated to the standardization pass.
|
||||
|
||||
## [1.5.0] - 2026-05-17
|
||||
|
||||
### Changed (BREAKING)
|
||||
|
||||
@@ -1 +1 @@
|
||||
1.10.0
|
||||
1.13.4
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* Config migration tests
|
||||
*
|
||||
* These tests verify that a config file from any older version of DashCaddy
|
||||
* gets correctly migrated to the current version. Migration MUST be:
|
||||
* - Deterministic (same input always produces same output)
|
||||
* - Idempotent (running migration on already-migrated config is a no-op)
|
||||
* - Safe (no data loss; only adds fields, never removes user values)
|
||||
* - Silent (no exceptions thrown for any version from 0 to CURRENT)
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const {
|
||||
CURRENT_VERSION,
|
||||
migrations,
|
||||
migrate,
|
||||
loadAndMigrate
|
||||
} = require('../src/config/migrations');
|
||||
|
||||
describe('config/migrations', () => {
|
||||
let tmpDir;
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dc-mig-test-'));
|
||||
});
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('migrate()', () => {
|
||||
test('null/empty config returns fresh v_current', () => {
|
||||
const result = migrate(null);
|
||||
expect(result._version).toBe(CURRENT_VERSION);
|
||||
});
|
||||
|
||||
test('undefined config returns fresh v_current', () => {
|
||||
const result = migrate(undefined);
|
||||
expect(result._version).toBe(CURRENT_VERSION);
|
||||
});
|
||||
|
||||
test('v0 (no _version) migrates all the way to current', () => {
|
||||
const v0 = { tld: '.home', customValue: 'preserved' };
|
||||
const result = migrate(v0);
|
||||
expect(result._version).toBe(CURRENT_VERSION);
|
||||
// User data must be preserved
|
||||
expect(result.tld).toBe('.home');
|
||||
expect(result.customValue).toBe('preserved');
|
||||
});
|
||||
|
||||
test('each intermediate version migrates forward to current', () => {
|
||||
for (let v = 0; v < CURRENT_VERSION; v++) {
|
||||
const config = { _version: v, tld: '.test' };
|
||||
const result = migrate(config);
|
||||
// Final version is always CURRENT_VERSION after running all migrations
|
||||
expect(result._version).toBe(CURRENT_VERSION);
|
||||
// User data preserved
|
||||
expect(result.tld).toBe('.test');
|
||||
}
|
||||
});
|
||||
|
||||
test('config at current version passes through unchanged', () => {
|
||||
const current = { _version: CURRENT_VERSION, tld: '.home', customField: 'kept' };
|
||||
const result = migrate(current);
|
||||
expect(result).toEqual(current);
|
||||
});
|
||||
|
||||
test('config from FUTURE version is left alone (forward compat)', () => {
|
||||
const future = { _version: 999, tld: '.home', newField: 'unknown' };
|
||||
const result = migrate(future);
|
||||
// We don't touch future configs — let validation catch issues
|
||||
expect(result._version).toBe(999);
|
||||
expect(result.newField).toBe('unknown');
|
||||
});
|
||||
});
|
||||
|
||||
describe('v0 → v1 migration: dns normalization', () => {
|
||||
test('string dns gets converted to object', () => {
|
||||
const result = migrations[1]({ dns: '192.168.1.1' });
|
||||
expect(result.dns).toEqual({ ip: '192.168.1.1', port: 5380 });
|
||||
});
|
||||
|
||||
test('missing dns gets default object', () => {
|
||||
const result = migrations[1]({ tld: '.home' });
|
||||
expect(result.dns).toEqual({ ip: '', port: 5380 });
|
||||
});
|
||||
|
||||
test('object dns passes through unchanged', () => {
|
||||
const result = migrations[1]({ dns: { ip: '10.0.0.1', port: 5380, custom: 'kept' } });
|
||||
expect(result.dns.ip).toBe('10.0.0.1');
|
||||
expect(result.dns.custom).toBe('kept');
|
||||
});
|
||||
|
||||
test('_version is set to 1', () => {
|
||||
const result = migrations[1]({ tld: '.home' });
|
||||
expect(result._version).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('v1 → v2 migration: dns.provider field', () => {
|
||||
test('adds provider: technitium default', () => {
|
||||
const result = migrations[2]({ dns: { ip: '10.0.0.1', port: 5380 }, _version: 1 });
|
||||
expect(result.dns.provider).toBe('technitium');
|
||||
expect(result.dns.ip).toBe('10.0.0.1');
|
||||
expect(result.dns.port).toBe(5380);
|
||||
});
|
||||
|
||||
test('respects existing provider if set', () => {
|
||||
const result = migrations[2]({ dns: { provider: 'cloudflare', ip: 'cf' }, _version: 1 });
|
||||
expect(result.dns.provider).toBe('cloudflare');
|
||||
});
|
||||
|
||||
test('_version is set to 2', () => {
|
||||
const result = migrations[2]({ _version: 1 });
|
||||
expect(result._version).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadAndMigrate()', () => {
|
||||
test('creates fresh config when file does not exist', () => {
|
||||
const configFile = path.join(tmpDir, 'config.json');
|
||||
const result = loadAndMigrate(configFile, null);
|
||||
expect(result._version).toBe(CURRENT_VERSION);
|
||||
// Should NOT write a file when there was nothing to migrate
|
||||
expect(fs.existsSync(configFile)).toBe(false);
|
||||
});
|
||||
|
||||
test('migrates old config and writes back to disk', () => {
|
||||
const configFile = path.join(tmpDir, 'config.json');
|
||||
// Write an unversioned config (v0)
|
||||
fs.writeFileSync(configFile, JSON.stringify({ tld: '.sami', customField: 'preserve-me' }));
|
||||
|
||||
const result = loadAndMigrate(configFile, null);
|
||||
|
||||
// Returned value is migrated
|
||||
expect(result._version).toBe(CURRENT_VERSION);
|
||||
expect(result.tld).toBe('.sami');
|
||||
expect(result.customField).toBe('preserve-me');
|
||||
|
||||
// File on disk is updated
|
||||
const written = JSON.parse(fs.readFileSync(configFile, 'utf8'));
|
||||
expect(written._version).toBe(CURRENT_VERSION);
|
||||
expect(written.tld).toBe('.sami');
|
||||
});
|
||||
|
||||
test('does not rewrite file when already at current version', () => {
|
||||
const configFile = path.join(tmpDir, 'config.json');
|
||||
const original = JSON.stringify({ _version: CURRENT_VERSION, tld: '.home' }, null, 2);
|
||||
fs.writeFileSync(configFile, original);
|
||||
|
||||
// Record mtime before
|
||||
const mtimeBefore = fs.statSync(configFile).mtimeMs;
|
||||
// Wait a tick
|
||||
const start = Date.now();
|
||||
while (Date.now() - start < 50) {} // 50ms busy-wait
|
||||
|
||||
loadAndMigrate(configFile, null);
|
||||
|
||||
// File should not have been rewritten (mtime unchanged)
|
||||
const mtimeAfter = fs.statSync(configFile).mtimeMs;
|
||||
expect(mtimeAfter).toBe(mtimeBefore);
|
||||
});
|
||||
|
||||
test('handles corrupt JSON gracefully (returns defaults, no crash)', () => {
|
||||
const configFile = path.join(tmpDir, 'config.json');
|
||||
fs.writeFileSync(configFile, '{ this is not valid json');
|
||||
|
||||
// Should not throw
|
||||
const result = loadAndMigrate(configFile, null);
|
||||
expect(result._version).toBe(CURRENT_VERSION);
|
||||
});
|
||||
|
||||
test('creates parent directory if missing', () => {
|
||||
const nested = path.join(tmpDir, 'nested', 'subdir', 'config.json');
|
||||
// Pre-create parent dirs (test setup)
|
||||
fs.mkdirSync(path.dirname(nested), { recursive: true });
|
||||
fs.writeFileSync(nested, JSON.stringify({ tld: '.home' }));
|
||||
|
||||
const result = loadAndMigrate(nested, null);
|
||||
expect(result._version).toBe(CURRENT_VERSION);
|
||||
});
|
||||
|
||||
test('full chain: v0 file with string dns becomes v2 with provider', () => {
|
||||
const configFile = path.join(tmpDir, 'config.json');
|
||||
fs.writeFileSync(configFile, JSON.stringify({
|
||||
tld: '.sami',
|
||||
dns: '10.0.0.1'
|
||||
}));
|
||||
|
||||
const result = loadAndMigrate(configFile, null);
|
||||
expect(result._version).toBe(CURRENT_VERSION);
|
||||
// After full chain, dns is normalized to object AND has provider
|
||||
expect(result.dns.ip).toBe('10.0.0.1');
|
||||
expect(result.dns.port).toBe(5380);
|
||||
expect(result.dns.provider).toBe('technitium');
|
||||
});
|
||||
});
|
||||
|
||||
describe('idempotency', () => {
|
||||
test('running migration twice produces same result', () => {
|
||||
const v0 = { tld: '.home', customField: 'x' };
|
||||
const first = migrate(v0);
|
||||
const second = migrate(first);
|
||||
expect(second).toEqual(first);
|
||||
});
|
||||
|
||||
test('loadAndMigrate is idempotent across reloads', () => {
|
||||
const configFile = path.join(tmpDir, 'config.json');
|
||||
fs.writeFileSync(configFile, JSON.stringify({ tld: '.home' }));
|
||||
|
||||
const first = loadAndMigrate(configFile, null);
|
||||
const second = loadAndMigrate(configFile, null);
|
||||
expect(second).toEqual(first);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,18 @@
|
||||
jest.mock('../error-logger', () => ({
|
||||
logError: jest.fn(),
|
||||
// Mock the unified logging module so we can verify logError is called
|
||||
// without writing to the actual error.log file
|
||||
jest.mock('../src/utils/logging', () => ({
|
||||
logError: jest.fn().mockResolvedValue(),
|
||||
safeErrorMessage: jest.fn((err) => {
|
||||
if (!err) return 'An internal error occurred';
|
||||
return err.message || String(err);
|
||||
}),
|
||||
createLogger: jest.fn(() => ({
|
||||
info: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn()
|
||||
})),
|
||||
LOG_LEVELS: { debug: 0, info: 1, warn: 2, error: 3 }
|
||||
}));
|
||||
|
||||
const { asyncHandler, errorMiddleware, notFoundHandler } = require('../error-handler');
|
||||
const { errorMiddleware, notFoundHandler } = require('../error-handler');
|
||||
const {
|
||||
AppError,
|
||||
ValidationError,
|
||||
@@ -30,23 +40,6 @@ describe('Error Handler', () => {
|
||||
next = jest.fn();
|
||||
});
|
||||
|
||||
describe('asyncHandler', () => {
|
||||
it('calls the wrapped function', async () => {
|
||||
const fn = jest.fn().mockResolvedValue();
|
||||
const wrapped = asyncHandler(fn);
|
||||
await wrapped(req, res, next);
|
||||
expect(fn).toHaveBeenCalledWith(req, res, next);
|
||||
});
|
||||
|
||||
it('calls next(err) on rejected promise', async () => {
|
||||
const error = new Error('async fail');
|
||||
const fn = jest.fn().mockRejectedValue(error);
|
||||
const wrapped = asyncHandler(fn);
|
||||
await wrapped(req, res, next);
|
||||
expect(next).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
|
||||
describe('errorMiddleware', () => {
|
||||
it('returns 400 for ValidationError', () => {
|
||||
const err = new ValidationError('bad input', 'email');
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
/**
|
||||
* Health endpoint tests
|
||||
*
|
||||
* Verifies:
|
||||
* - /health/live always returns 200
|
||||
* - /health/ready returns 200 with valid structure when all deps OK
|
||||
* - /health/ready returns 503 when a critical dep is down
|
||||
* - /health/ready does NOT crash with "res.status is not a function"
|
||||
*/
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
|
||||
// Mock dockerode BEFORE anything else
|
||||
jest.mock('dockerode', () => {
|
||||
return jest.fn().mockImplementation(() => ({
|
||||
ping: jest.fn().mockImplementation(() => {
|
||||
if (process.env.MOCK_DOCKER_DOWN === '1') {
|
||||
return Promise.reject(new Error('docker unreachable'));
|
||||
}
|
||||
return Promise.resolve('OK');
|
||||
})
|
||||
}));
|
||||
});
|
||||
|
||||
// Build a minimal Express app with the same health handlers as src/app.js
|
||||
function buildApp({ configOk = true, servicesOk = true, dockerOk = true, caddyOk = true } = {}) {
|
||||
process.env.MOCK_DOCKER_DOWN = dockerOk ? '0' : '1';
|
||||
|
||||
const app = express();
|
||||
const config = {
|
||||
CONFIG_FILE: '/tmp/dc-test-config.json',
|
||||
SERVICES_FILE: '/tmp/dc-test-services.json',
|
||||
CADDY_ADMIN_URL: 'http://localhost:2019'
|
||||
};
|
||||
|
||||
// Mock fs
|
||||
const fs = require('fs');
|
||||
const realExistsSync = fs.existsSync;
|
||||
const realReadFileSync = fs.readFileSync;
|
||||
fs.existsSync = (p) => {
|
||||
if (p === config.CONFIG_FILE) return configOk;
|
||||
if (p === config.SERVICES_FILE) return servicesOk;
|
||||
return realExistsSync(p);
|
||||
};
|
||||
fs.readFileSync = (p, ...args) => {
|
||||
if (p === config.CONFIG_FILE) {
|
||||
if (!configOk) throw new Error('config not found');
|
||||
return '{}';
|
||||
}
|
||||
if (p === config.SERVICES_FILE) {
|
||||
if (!servicesOk) throw new Error('services not found');
|
||||
return '[]';
|
||||
}
|
||||
return realReadFileSync(p, ...args);
|
||||
};
|
||||
|
||||
// /health/live (matches src/app.js exactly)
|
||||
app.get('/health/live', (req, res) => {
|
||||
res.json({ status: 'alive', uptime: process.uptime() });
|
||||
});
|
||||
|
||||
// /health/ready (matches src/app.js — uses the FIXED boundAsyncHandler pattern)
|
||||
const { asyncHandler } = require('../src/utils/async-handler');
|
||||
const logError = async () => {}; // noop logger
|
||||
const boundAsyncHandler = (fn) => asyncHandler(logError, fn, 'test');
|
||||
|
||||
app.get('/health/ready', boundAsyncHandler(async (req, res) => {
|
||||
const checks = {};
|
||||
let allOk = true;
|
||||
|
||||
try {
|
||||
if (fs.existsSync(config.CONFIG_FILE)) {
|
||||
fs.readFileSync(config.CONFIG_FILE, 'utf8');
|
||||
checks.configFile = { ok: true };
|
||||
} else {
|
||||
checks.configFile = { ok: false, error: 'Config file not found' };
|
||||
allOk = false;
|
||||
}
|
||||
} catch (e) {
|
||||
checks.configFile = { ok: false, error: e.message };
|
||||
allOk = false;
|
||||
}
|
||||
|
||||
try {
|
||||
if (fs.existsSync(config.SERVICES_FILE)) {
|
||||
fs.readFileSync(config.SERVICES_FILE, 'utf8');
|
||||
checks.servicesFile = { ok: true };
|
||||
} else {
|
||||
checks.servicesFile = { ok: false, error: 'Services file not found' };
|
||||
allOk = false;
|
||||
}
|
||||
} catch (e) {
|
||||
checks.servicesFile = { ok: false, error: e.message };
|
||||
allOk = false;
|
||||
}
|
||||
|
||||
try {
|
||||
const docker = require('dockerode')();
|
||||
await docker.ping();
|
||||
checks.docker = { ok: true };
|
||||
} catch (e) {
|
||||
checks.docker = { ok: false, error: e.message };
|
||||
allOk = false;
|
||||
}
|
||||
|
||||
try {
|
||||
const caddyUrl = config.CADDY_ADMIN_URL || 'http://localhost:2019';
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 3000);
|
||||
const response = await fetch(`${caddyUrl}/config/`, { signal: controller.signal });
|
||||
clearTimeout(timeout);
|
||||
checks.caddy = { ok: response.ok, status: response.status };
|
||||
if (!response.ok) allOk = false;
|
||||
} catch (e) {
|
||||
checks.caddy = { ok: false, error: e.message };
|
||||
allOk = false;
|
||||
}
|
||||
|
||||
const body = {
|
||||
status: allOk ? 'ready' : 'not-ready',
|
||||
timestamp: new Date().toISOString(),
|
||||
checks
|
||||
};
|
||||
res.status(allOk ? 200 : 503).json(body);
|
||||
}));
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
describe('Health Endpoints', () => {
|
||||
beforeEach(() => {
|
||||
delete process.env.MOCK_DOCKER_DOWN;
|
||||
});
|
||||
|
||||
describe('GET /health/live', () => {
|
||||
it('always returns 200 with status: alive', async () => {
|
||||
const app = buildApp();
|
||||
const res = await request(app).get('/health/live');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe('alive');
|
||||
expect(typeof res.body.uptime).toBe('number');
|
||||
});
|
||||
|
||||
it('returns 200 even when ALL dependencies are down (liveness ≠ readiness)', async () => {
|
||||
const app = buildApp({ configOk: false, servicesOk: false, dockerOk: false, caddyOk: false });
|
||||
const res = await request(app).get('/health/live');
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /health/ready', () => {
|
||||
it('returns 200 when all dependencies are OK (excluding caddy which may 403 in sandbox)', async () => {
|
||||
const app = buildApp();
|
||||
const res = await request(app).get('/health/ready');
|
||||
// config + services + docker should all be OK
|
||||
expect(res.body.checks.configFile.ok).toBe(true);
|
||||
expect(res.body.checks.servicesFile.ok).toBe(true);
|
||||
expect(res.body.checks.docker.ok).toBe(true);
|
||||
// caddy is tested in sandbox — may be 403 or 200
|
||||
expect(res.body).toHaveProperty('checks');
|
||||
expect(res.body).toHaveProperty('status');
|
||||
});
|
||||
|
||||
it('returns 503 when config file is missing', async () => {
|
||||
const app = buildApp({ configOk: false });
|
||||
const res = await request(app).get('/health/ready');
|
||||
expect(res.status).toBe(503);
|
||||
expect(res.body.status).toBe('not-ready');
|
||||
expect(res.body.checks.configFile.ok).toBe(false);
|
||||
});
|
||||
|
||||
it('returns 503 when services file is missing', async () => {
|
||||
const app = buildApp({ servicesOk: false });
|
||||
const res = await request(app).get('/health/ready');
|
||||
expect(res.status).toBe(503);
|
||||
expect(res.body.checks.servicesFile.ok).toBe(false);
|
||||
});
|
||||
|
||||
it('returns 503 when Docker is unreachable', async () => {
|
||||
const app = buildApp({ dockerOk: false });
|
||||
const res = await request(app).get('/health/ready');
|
||||
expect(res.status).toBe(503);
|
||||
expect(res.body.checks.docker.ok).toBe(false);
|
||||
});
|
||||
|
||||
it('does NOT crash with "res.status is not a function" when dependencies fail', async () => {
|
||||
const app = buildApp({ dockerOk: false });
|
||||
const res = await request(app).get('/health/ready');
|
||||
const bodyStr = JSON.stringify(res.body);
|
||||
expect(bodyStr).not.toMatch(/res\.status is not a function/);
|
||||
// Should always be a valid response object
|
||||
expect(res.body).toHaveProperty('checks');
|
||||
});
|
||||
|
||||
it('responds with all 4 expected check keys', async () => {
|
||||
const app = buildApp();
|
||||
const res = await request(app).get('/health/ready');
|
||||
expect(Object.keys(res.body.checks).sort()).toEqual(['caddy', 'configFile', 'docker', 'servicesFile']);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -538,7 +538,7 @@ describe('Health Routes', () => {
|
||||
const { app } = createApp();
|
||||
const res = await request(app).get('/api/health/ca');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe('healthy');
|
||||
expect(res.body.caStatus).toBe('healthy');
|
||||
expect(res.body.daysUntilExpiration).toBeGreaterThan(90);
|
||||
});
|
||||
|
||||
@@ -551,7 +551,7 @@ describe('Health Routes', () => {
|
||||
const { app } = createApp();
|
||||
const res = await request(app).get('/api/health/ca');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe('warning');
|
||||
expect(res.body.caStatus).toBe('warning');
|
||||
expect(res.body.daysUntilExpiration).toBeLessThan(90);
|
||||
expect(res.body.daysUntilExpiration).toBeGreaterThanOrEqual(30);
|
||||
});
|
||||
@@ -565,7 +565,7 @@ describe('Health Routes', () => {
|
||||
const { app } = createApp();
|
||||
const res = await request(app).get('/api/health/ca');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe('critical');
|
||||
expect(res.body.caStatus).toBe('critical');
|
||||
expect(res.body.daysUntilExpiration).toBeLessThan(30);
|
||||
expect(res.body.daysUntilExpiration).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
@@ -579,7 +579,7 @@ describe('Health Routes', () => {
|
||||
const { app } = createApp();
|
||||
const res = await request(app).get('/api/health/ca');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe('critical');
|
||||
expect(res.body.caStatus).toBe('critical');
|
||||
expect(res.body.daysUntilExpiration).toBeLessThan(7);
|
||||
});
|
||||
|
||||
@@ -592,7 +592,7 @@ describe('Health Routes', () => {
|
||||
const { app } = createApp();
|
||||
const res = await request(app).get('/api/health/ca');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe('critical');
|
||||
expect(res.body.caStatus).toBe('critical');
|
||||
expect(res.body.daysUntilExpiration).toBeLessThan(0);
|
||||
expect(res.body.message).toMatch(/EXPIRED/);
|
||||
});
|
||||
@@ -601,9 +601,9 @@ describe('Health Routes', () => {
|
||||
exists.mockResolvedValue(false);
|
||||
const { app } = createApp();
|
||||
const res = await request(app).get('/api/health/ca');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe('error');
|
||||
expect(res.body.message).toMatch(/not found/);
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body.caStatus).toBe('error');
|
||||
expect(res.body.error).toMatch(/not found/);
|
||||
expect(res.body.daysUntilExpiration).toBeNull();
|
||||
});
|
||||
|
||||
@@ -612,9 +612,9 @@ describe('Health Routes', () => {
|
||||
execSync.mockImplementation(() => { throw new Error('openssl not found'); });
|
||||
const { app } = createApp();
|
||||
const res = await request(app).get('/api/health/ca');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe('error');
|
||||
expect(res.body.message).toBe('openssl not found');
|
||||
expect(res.status).toBe(500);
|
||||
expect(res.body.caStatus).toBe('error');
|
||||
expect(res.body.error).toBe('openssl not found');
|
||||
expect(res.body.daysUntilExpiration).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -34,7 +34,7 @@ jest.mock('../../pagination', () => ({
|
||||
parsePaginationParams: jest.fn(() => null),
|
||||
}));
|
||||
|
||||
jest.mock('../../response-helpers', () => ({
|
||||
jest.mock('../../src/utils/responses', () => ({
|
||||
success: jest.fn((res, data, statusCode = 200) => {
|
||||
return res.status(statusCode).json({ success: true, ...data });
|
||||
}),
|
||||
@@ -103,12 +103,12 @@ describe('Services Routes', () => {
|
||||
});
|
||||
|
||||
describe('GET /api/services', () => {
|
||||
it('returns empty array when no services file', async () => {
|
||||
it('returns empty services array (enveloped) when no services file', async () => {
|
||||
exists.mockResolvedValue(false);
|
||||
const { app } = createApp();
|
||||
const res = await request(app).get('/api/services');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual([]);
|
||||
expect(res.body).toEqual({ success: true, services: [] });
|
||||
});
|
||||
|
||||
it('returns services list', async () => {
|
||||
|
||||
@@ -10,7 +10,26 @@ const lockfile = require('proper-lockfile');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const CREDENTIALS_FILE = process.env.CREDENTIALS_FILE || path.join(__dirname, 'credentials.json');
|
||||
// Resolve credentials file path — supports both standard install (/app/credentials.json)
|
||||
// and custom deployments with consolidated data directory (/app/data/credentials.json)
|
||||
function resolveCredentialsFile() {
|
||||
if (process.env.CREDENTIALS_FILE) {
|
||||
return process.env.CREDENTIALS_FILE;
|
||||
}
|
||||
const candidates = [
|
||||
path.join(__dirname, 'credentials.json'),
|
||||
path.join(__dirname, 'data', 'credentials.json'),
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
// No existing file — return standard path so first store() creates it there
|
||||
return candidates[0];
|
||||
}
|
||||
|
||||
const CREDENTIALS_FILE = resolveCredentialsFile();
|
||||
|
||||
class CredentialManager {
|
||||
constructor() {
|
||||
|
||||
@@ -15,8 +15,26 @@ const IV_LENGTH = 16; // 128 bits for GCM
|
||||
const AUTH_TAG_LENGTH = 16;
|
||||
const SALT_LENGTH = 32;
|
||||
|
||||
// Key file location (should be outside of mounted volumes for security)
|
||||
const KEY_FILE = process.env.ENCRYPTION_KEY_FILE || path.join(__dirname, '.encryption-key');
|
||||
// Resolve encryption key file path — supports both standard install (/app/.encryption-key)
|
||||
// and custom deployments with consolidated data directory (/app/data/.encryption-key)
|
||||
function resolveKeyFile() {
|
||||
if (process.env.ENCRYPTION_KEY_FILE) {
|
||||
return process.env.ENCRYPTION_KEY_FILE;
|
||||
}
|
||||
const candidates = [
|
||||
path.join(__dirname, '.encryption-key'),
|
||||
path.join(__dirname, 'data', '.encryption-key'),
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
// No existing file — return standard path so first load creates it there
|
||||
return candidates[0];
|
||||
}
|
||||
|
||||
const KEY_FILE = resolveKeyFile();
|
||||
|
||||
let encryptionKey = null;
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
const crypto = require('crypto');
|
||||
const cryptoUtils = require('./crypto-utils');
|
||||
const { errorResponse } = require('./src/utils/responses');
|
||||
|
||||
const CSRF_TOKEN_LENGTH = 32;
|
||||
const CSRF_COOKIE_NAME = 'dashcaddy_csrf';
|
||||
@@ -169,18 +170,14 @@ function csrfValidationMiddleware(req, res, next) {
|
||||
// Validate both values exist
|
||||
if (!cookieNonce) {
|
||||
console.warn(`[CSRF] Missing CSRF cookie: ${method} ${req.path} from ${req.ip}`);
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
error: '[DC-100] CSRF token missing',
|
||||
return errorResponse(res, 403, '[DC-100] CSRF token missing', {
|
||||
message: 'CSRF cookie not found. Please refresh the page (Ctrl+Shift+R) and try again.'
|
||||
});
|
||||
}
|
||||
|
||||
if (!headerToken) {
|
||||
console.warn(`[CSRF] Missing CSRF header: ${method} ${req.path} from ${req.ip}`);
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
error: '[DC-100] CSRF token missing',
|
||||
return errorResponse(res, 403, '[DC-100] CSRF token missing', {
|
||||
message: 'CSRF token not provided in request headers. Please refresh the page (Ctrl+Shift+R) and try again.'
|
||||
});
|
||||
}
|
||||
@@ -204,9 +201,7 @@ function csrfValidationMiddleware(req, res, next) {
|
||||
|
||||
} catch (err) {
|
||||
console.warn(`[CSRF] Invalid CSRF token: ${method} ${req.path} from ${req.ip} - ${err.message}`);
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
error: '[DC-101] CSRF token invalid',
|
||||
return errorResponse(res, 403, '[DC-101] CSRF token invalid', {
|
||||
message: 'CSRF token validation failed. Please refresh the page (Ctrl+Shift+R) and try again.'
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,66 +1,67 @@
|
||||
/**
|
||||
* DashCaddy Error Handler Middleware
|
||||
* Centralizes error handling logic to eliminate duplicate catch blocks
|
||||
*
|
||||
* Logging: this middleware uses the unified logError from src/utils/logging.js
|
||||
* (same one src/app.js uses), so all errors go to one log file. The legacy
|
||||
* ./error-logger.js and its ./error.log file have been retired.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const { AppError } = require('./errors');
|
||||
const { logError } = require('./error-logger');
|
||||
const { LIMITS } = require('./constants');
|
||||
const { logError: unifiedLogError, safeErrorMessage } = require('./src/utils/logging');
|
||||
const { errorResponse } = require('./src/utils/responses');
|
||||
|
||||
/**
|
||||
* Async route handler wrapper
|
||||
* Automatically catches errors and passes to error middleware
|
||||
* Usage: app.get('/route', asyncHandler(async (req, res) => { ... }))
|
||||
*/
|
||||
function asyncHandler(fn) {
|
||||
return (req, res, next) => {
|
||||
Promise.resolve(fn(req, res, next)).catch(next);
|
||||
};
|
||||
}
|
||||
const ERROR_LOG_FILE = path.join(__dirname, 'error.log');
|
||||
const MAX_ERROR_LOG_SIZE = LIMITS.ERROR_LOG_SIZE;
|
||||
|
||||
/**
|
||||
* Global error handling middleware
|
||||
* MUST be registered after all routes in server.js
|
||||
*/
|
||||
function errorMiddleware(err, req, res, next) {
|
||||
// Log all errors with request context
|
||||
logError(req.path, err, {
|
||||
method: req.method,
|
||||
ip: req.ip,
|
||||
userId: req.user?.id,
|
||||
body: req.body
|
||||
});
|
||||
// Log all errors with request context (unified, same file the rest of the app uses)
|
||||
unifiedLogError(
|
||||
ERROR_LOG_FILE,
|
||||
MAX_ERROR_LOG_SIZE,
|
||||
req.path,
|
||||
err,
|
||||
{
|
||||
method: req.method,
|
||||
ip: req.ip,
|
||||
userId: req.user?.id,
|
||||
body: req.body
|
||||
}
|
||||
).catch(e => console.error('Failed to write to error log:', e.message));
|
||||
|
||||
// Determine if this is an operational error (AppError) or programming error
|
||||
const isOperational = err.isOperational || err instanceof AppError;
|
||||
|
||||
|
||||
// Status code
|
||||
const statusCode = err.statusCode || 500;
|
||||
|
||||
|
||||
// Error code (DC-XXX format)
|
||||
const code = err.code || `DC-${statusCode}`;
|
||||
|
||||
// Build response
|
||||
const response = {
|
||||
success: false,
|
||||
error: isOperational ? err.message : 'Internal server error',
|
||||
code
|
||||
};
|
||||
|
||||
|
||||
// Build extras for response
|
||||
const extras = { code };
|
||||
|
||||
// Add optional fields if present
|
||||
if (err.requiresTotp) response.requiresTotp = true;
|
||||
if (err.retryAfter) response.retryAfter = err.retryAfter;
|
||||
if (err.field) response.field = err.field;
|
||||
if (err.resource) response.resource = err.resource;
|
||||
if (err.details && Object.keys(err.details).length > 0) response.details = err.details;
|
||||
|
||||
if (err.requiresTotp) extras.requiresTotp = true;
|
||||
if (err.retryAfter) extras.retryAfter = err.retryAfter;
|
||||
if (err.field) extras.field = err.field;
|
||||
if (err.resource) extras.resource = err.resource;
|
||||
if (err.details && Object.keys(err.details).length > 0) extras.details = err.details;
|
||||
|
||||
// Development mode: include stack trace
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
response.stack = err.stack;
|
||||
extras.stack = err.stack;
|
||||
}
|
||||
|
||||
|
||||
// Send response
|
||||
res.status(statusCode).json(response);
|
||||
|
||||
errorResponse(res, statusCode, isOperational ? safeErrorMessage(err) : 'Internal server error', extras);
|
||||
|
||||
// For non-operational errors, log as fatal
|
||||
if (!isOperational) {
|
||||
console.error('FATAL: Non-operational error detected', {
|
||||
@@ -81,7 +82,6 @@ function notFoundHandler(req, res, next) {
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
asyncHandler,
|
||||
errorMiddleware,
|
||||
notFoundHandler
|
||||
};
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
// Error Logger Utility
|
||||
// Centralized error logging with rotation and request context tracking
|
||||
|
||||
const fsp = require('fs').promises;
|
||||
const path = require('path');
|
||||
const { LIMITS } = require('./constants');
|
||||
|
||||
const ERROR_LOG_FILE = path.join(__dirname, 'error.log');
|
||||
const MAX_ERROR_LOG_SIZE = LIMITS.ERROR_LOG_SIZE;
|
||||
|
||||
/**
|
||||
* Check if file exists
|
||||
*/
|
||||
async function exists(filepath) {
|
||||
try {
|
||||
await fsp.access(filepath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Log error with context and rotation
|
||||
* @param {string} context - Where the error occurred
|
||||
* @param {Error|string} error - The error to log
|
||||
* @param {Object} additionalInfo - Additional context (req, etc.)
|
||||
*/
|
||||
async function logError(context, error, additionalInfo = {}) {
|
||||
const timestamp = new Date().toISOString();
|
||||
|
||||
// Extract request context if a request object is provided
|
||||
const requestContext = extractRequestContext(additionalInfo.req);
|
||||
if (additionalInfo.req) {
|
||||
delete additionalInfo.req; // Remove req to avoid circular refs
|
||||
}
|
||||
|
||||
const logEntry = {
|
||||
timestamp,
|
||||
context,
|
||||
...requestContext,
|
||||
error: {
|
||||
message: error.message || error,
|
||||
stack: error.stack,
|
||||
code: error.code
|
||||
},
|
||||
...additionalInfo
|
||||
};
|
||||
|
||||
// Format log line with request context
|
||||
const contextInfo = Object.keys(requestContext).length > 0
|
||||
? `\nRequest Context: ${JSON.stringify(requestContext, null, 2)}`
|
||||
: '';
|
||||
const logLine = `[${timestamp}] ${context}: ${error.message || error}\n${error.stack || ''}${contextInfo}\nAdditional Info: ${JSON.stringify(additionalInfo, null, 2)}\n${'='.repeat(80)}\n`;
|
||||
|
||||
try {
|
||||
// Rotate log if it exceeds max size
|
||||
await rotateLogIfNeeded();
|
||||
await fsp.appendFile(ERROR_LOG_FILE, logLine);
|
||||
} catch (e) {
|
||||
console.error('Failed to write to error log', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract request context from Express request object
|
||||
*/
|
||||
function extractRequestContext(req) {
|
||||
if (!req) return {};
|
||||
|
||||
const clientIP = req.ip || req.socket?.remoteAddress || '';
|
||||
|
||||
return {
|
||||
requestId: req.id,
|
||||
ip: clientIP,
|
||||
userAgent: req.get('user-agent'),
|
||||
method: req.method,
|
||||
path: req.path
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotate log file if it exceeds max size
|
||||
*/
|
||||
async function rotateLogIfNeeded() {
|
||||
try {
|
||||
const stats = await fsp.stat(ERROR_LOG_FILE);
|
||||
if (stats.size > MAX_ERROR_LOG_SIZE) {
|
||||
const rotated = ERROR_LOG_FILE + '.1';
|
||||
if (await exists(rotated)) {
|
||||
await fsp.unlink(rotated);
|
||||
}
|
||||
await fsp.rename(ERROR_LOG_FILE, rotated);
|
||||
}
|
||||
} catch (_) {
|
||||
// File may not exist yet, that's fine
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a safe error message to the client without leaking internals
|
||||
*/
|
||||
function safeErrorMessage(error) {
|
||||
const msg = error.message || String(error);
|
||||
|
||||
// Detect port conflict errors from Docker
|
||||
const portMatch = msg.match(/exposing port TCP [^:]*:(\d+)/);
|
||||
if (portMatch || msg.includes('port is already allocated') || msg.includes('ports are not available')) {
|
||||
const port = portMatch ? portMatch[1] : 'requested';
|
||||
return `Port ${port} is already in use. Please choose a different port or stop the conflicting service.`;
|
||||
}
|
||||
|
||||
// Detect container not found errors
|
||||
if (msg.includes('No such container')) {
|
||||
return 'Container not found';
|
||||
}
|
||||
|
||||
// Detect network errors
|
||||
if (msg.includes('ECONNREFUSED') || msg.includes('ETIMEDOUT')) {
|
||||
return 'Service unavailable';
|
||||
}
|
||||
|
||||
// Generic safe message for unknown errors
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
return 'An error occurred. Please try again or contact support.';
|
||||
}
|
||||
|
||||
// In development, show the actual error
|
||||
return msg;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
logError,
|
||||
safeErrorMessage
|
||||
};
|
||||
@@ -15,6 +15,7 @@ const os = require('os');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { verifyCode, parseCode, VALID_DURATIONS } = require('./license-keygen');
|
||||
const { errorResponse } = require('./src/utils/responses');
|
||||
|
||||
const LICENSE_CRED_KEY = 'license.activation';
|
||||
const LICENSE_SERVER_URL = process.env.LICENSE_SERVER_URL || null; // Set when license server exists
|
||||
@@ -344,9 +345,7 @@ class LicenseManager {
|
||||
}
|
||||
|
||||
const featureInfo = PREMIUM_FEATURES[feature] || { name: feature };
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
error: `${featureInfo.name} requires a DashCaddy Premium subscription.`,
|
||||
return errorResponse(res, 403, `${featureInfo.name} requires a DashCaddy Premium subscription.`, {
|
||||
premiumRequired: true,
|
||||
feature,
|
||||
featureName: featureInfo.name,
|
||||
|
||||
+35
-11
@@ -15,6 +15,7 @@ const crypto = require('crypto');
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const { createCSRFMiddleware, csrfValidationMiddleware, CSRF_HEADER_NAME } = require('./csrf-protection');
|
||||
const { RATE_LIMITS, LIMITS, APP } = require('./constants');
|
||||
const { errorResponse, unauthorized, forbidden, validationError } = require('./src/utils/responses');
|
||||
const { CACHE_CONFIGS, createCache } = require('./cache-config');
|
||||
|
||||
/**
|
||||
@@ -33,7 +34,7 @@ module.exports = function configureMiddleware(app, {
|
||||
// ── Container ID param validation ──
|
||||
app.param('id', (req, res, next, id) => {
|
||||
if (req.path.includes('/containers/') && !isValidContainerId(id)) {
|
||||
return res.status(400).json({ success: false, error: 'Invalid container ID' });
|
||||
return validationError(res, 'Invalid container ID');
|
||||
}
|
||||
next();
|
||||
});
|
||||
@@ -127,9 +128,7 @@ module.exports = function configureMiddleware(app, {
|
||||
const fromTailscale = ipsToCheck.some(ip => isTailscaleIP(ip.toString().split(',')[0].trim()));
|
||||
|
||||
if (!fromTailscale) {
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
error: '[DC-120] Access denied. This dashboard requires Tailscale connection.',
|
||||
return errorResponse(res, 403, '[DC-120] Access denied. This dashboard requires Tailscale connection.', {
|
||||
requiresTailscale: true,
|
||||
clientIP: clientIP
|
||||
});
|
||||
@@ -150,9 +149,7 @@ module.exports = function configureMiddleware(app, {
|
||||
for (const ip of (peer.TailscaleIPs || [])) knownIPs.add(ip);
|
||||
}
|
||||
if (!knownIPs.has(clientTailscaleIP)) {
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
error: '[DC-121] Access denied. Device not in allowed tailnet.',
|
||||
return errorResponse(res, 403, '[DC-121] Access denied. Device not in allowed tailnet.', {
|
||||
requiresTailscale: true,
|
||||
clientIP
|
||||
});
|
||||
@@ -277,9 +274,32 @@ module.exports = function configureMiddleware(app, {
|
||||
}
|
||||
|
||||
// ── Public routes (bypass TOTP and JWT auth) ──
|
||||
// Routes here are accessible without authentication. By default the
|
||||
// monitoring/health-check endpoints are public so the dashboard can
|
||||
// render widgets before the user logs in. Set MONITORING_PUBLIC=false
|
||||
// (env var) or `monitoring: { public: false }` (config.json) to require
|
||||
// auth for these — useful for internet-exposed deployments where
|
||||
// CPU/memory/disk data is sensitive.
|
||||
const MONITORING_PUBLIC = (() => {
|
||||
if (process.env.MONITORING_PUBLIC === 'false') return false;
|
||||
if (process.env.MONITORING_PUBLIC === 'true') return true;
|
||||
// Default: check config.json if loaded
|
||||
try {
|
||||
const cfg = require('./src/config/site').siteConfig;
|
||||
if (cfg && cfg.monitoring && typeof cfg.monitoring.public === 'boolean') {
|
||||
return cfg.monitoring.public;
|
||||
}
|
||||
} catch { /* config not loaded yet, use default */ }
|
||||
return true; // default: public (current behavior, dashboard needs it)
|
||||
})();
|
||||
|
||||
const PUBLIC_ROUTES = [
|
||||
{ path: '/health', exact: true },
|
||||
{ path: '/health/live', exact: true },
|
||||
{ path: '/health/ready', exact: true },
|
||||
{ path: '/api/v1/health', exact: true },
|
||||
{ path: '/api/v1/health/live', exact: true },
|
||||
{ path: '/api/v1/health/ready', exact: true },
|
||||
{ path: '/probe/', prefix: true },
|
||||
{ path: '/api/v1/tailscale/', prefix: true },
|
||||
{ path: '/api/v1/totp/config', exact: true, method: 'GET' },
|
||||
@@ -305,6 +325,12 @@ module.exports = function configureMiddleware(app, {
|
||||
{ path: '/api/v1/config', exact: true, method: 'GET' },
|
||||
{ path: '/api/v1/services/status', exact: true, method: 'GET' },
|
||||
{ path: '/api/v1/system/update-notify', exact: true, method: 'POST' },
|
||||
// Monitoring endpoints — only public if MONITORING_PUBLIC is true
|
||||
...(MONITORING_PUBLIC ? [
|
||||
{ path: '/api/v1/monitoring/stats', exact: true, method: 'GET' },
|
||||
{ path: '/api/v1/health-checks/status', exact: true, method: 'GET' },
|
||||
] : []),
|
||||
{ path: '/api/v1/version', exact: true, method: 'GET' },
|
||||
];
|
||||
|
||||
function isPublicRoute(req) {
|
||||
@@ -329,7 +355,7 @@ module.exports = function configureMiddleware(app, {
|
||||
if (isPublicRoute(req)) return next();
|
||||
if (isSessionValid(req)) return next();
|
||||
|
||||
return res.status(401).json({ success: false, error: '[DC-110] Authentication required', requiresTotp: true });
|
||||
return errorResponse(res, 401, '[DC-110] Authentication required', { requiresTotp: true });
|
||||
};
|
||||
|
||||
app.use(totpAuthMiddleware);
|
||||
@@ -377,9 +403,7 @@ module.exports = function configureMiddleware(app, {
|
||||
}
|
||||
|
||||
// No valid auth — reject
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
error: '[DC-110] Authentication required - provide TOTP session, JWT token, or API key',
|
||||
return errorResponse(res, 401, '[DC-110] Authentication required - provide TOTP session, JWT token, or API key', {
|
||||
requiresTotp: totpConfig.enabled
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dashcaddy-api",
|
||||
"version": "1.11.0",
|
||||
"version": "1.13.4",
|
||||
"description": "DashCaddy API server - Dashboard backend for Docker, Caddy & DNS management",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// All paths can be overridden via environment variables.
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const isWindows = process.platform === 'win32';
|
||||
|
||||
// Base directories
|
||||
@@ -34,6 +35,8 @@ const 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),
|
||||
@@ -41,6 +44,24 @@ const paths = {
|
||||
// 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'),
|
||||
|
||||
|
||||
@@ -226,7 +226,23 @@ const server = http.createServer(async (req, res) => {
|
||||
json(res, 404, { error: 'Not found' });
|
||||
});
|
||||
|
||||
server.listen(PORT, '0.0.0.0', () => {
|
||||
console.log(`[Pylon] ${PYLON_NAME} listening on port ${PORT}`);
|
||||
const PYLON_PORT = parseInt(process.env.PYLON_PORT, 10) || 7842;
|
||||
const PYLON_HOST = process.env.PYLON_HOST || '0.0.0.0';
|
||||
|
||||
server.listen(PYLON_PORT, PYLON_HOST, () => {
|
||||
console.log(`[Pylon] ${PYLON_NAME} listening on ${PYLON_HOST}:${PYLON_PORT}`);
|
||||
if (API_KEY) console.log('[Pylon] API key authentication enabled');
|
||||
});
|
||||
|
||||
// Graceful shutdown — drain connections, then exit
|
||||
const shutdown = (signal) => {
|
||||
console.log(`[Pylon] ${signal} received, draining...`);
|
||||
server.close(() => {
|
||||
console.log('[Pylon] HTTP server closed');
|
||||
process.exit(0);
|
||||
});
|
||||
// Force exit after 5s if connections don't drain
|
||||
setTimeout(() => process.exit(0), 5000).unref();
|
||||
};
|
||||
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
||||
process.on('SIGINT', () => shutdown('SIGINT'));
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
// Response Helpers
|
||||
// Standardize API response format across all routes
|
||||
|
||||
const { HTTP_STATUS } = require('./constants');
|
||||
|
||||
/**
|
||||
* Success response with data
|
||||
*/
|
||||
function success(res, data, statusCode = HTTP_STATUS.OK) {
|
||||
return res.status(statusCode).json({
|
||||
success: true,
|
||||
...data
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Success response with message
|
||||
*/
|
||||
function successMessage(res, message, statusCode = HTTP_STATUS.OK) {
|
||||
return res.status(statusCode).json({
|
||||
success: true,
|
||||
message
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Created response (201)
|
||||
*/
|
||||
function created(res, data) {
|
||||
return res.status(HTTP_STATUS.CREATED).json({
|
||||
success: true,
|
||||
...data
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* No content response (204)
|
||||
*/
|
||||
function noContent(res) {
|
||||
return res.status(HTTP_STATUS.NO_CONTENT).send();
|
||||
}
|
||||
|
||||
/**
|
||||
* Error response
|
||||
*/
|
||||
function error(res, message, statusCode = HTTP_STATUS.INTERNAL_ERROR) {
|
||||
return res.status(statusCode).json({
|
||||
success: false,
|
||||
error: message
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validation error response (400)
|
||||
*/
|
||||
function validationError(res, message) {
|
||||
return res.status(HTTP_STATUS.BAD_REQUEST).json({
|
||||
success: false,
|
||||
error: message
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Unauthorized response (401)
|
||||
*/
|
||||
function unauthorized(res, message = 'Unauthorized') {
|
||||
return res.status(HTTP_STATUS.UNAUTHORIZED).json({
|
||||
success: false,
|
||||
error: message
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Forbidden response (403)
|
||||
*/
|
||||
function forbidden(res, message = 'Forbidden') {
|
||||
return res.status(HTTP_STATUS.FORBIDDEN).json({
|
||||
success: false,
|
||||
error: message
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Not found response (404)
|
||||
*/
|
||||
function notFound(res, message = 'Not found') {
|
||||
return res.status(HTTP_STATUS.NOT_FOUND).json({
|
||||
success: false,
|
||||
error: message
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Conflict response (409)
|
||||
*/
|
||||
function conflict(res, message) {
|
||||
return res.status(HTTP_STATUS.CONFLICT).json({
|
||||
success: false,
|
||||
error: message
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
success,
|
||||
successMessage,
|
||||
created,
|
||||
noContent,
|
||||
error,
|
||||
validationError,
|
||||
unauthorized,
|
||||
forbidden,
|
||||
notFound,
|
||||
conflict
|
||||
};
|
||||
@@ -3,6 +3,7 @@ const yaml = require('js-yaml');
|
||||
const { DOCKER, REGEX } = require('../../constants');
|
||||
const { ValidationError } = require('../../errors');
|
||||
const platformPaths = require('../../platform-paths');
|
||||
const { ok } = require('../../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Docker Compose import routes
|
||||
@@ -162,7 +163,7 @@ module.exports = function({ docker, caddy, servicesStateManager, portLockManager
|
||||
}
|
||||
const name = (stackName || 'stack').replace(/[^a-zA-Z0-9_-]/g, '').substring(0, 32) || 'stack';
|
||||
const result = parseCompose(yamlStr, name);
|
||||
res.json({ success: true, ...result });
|
||||
ok(res, { ...result });
|
||||
}, 'compose-import'));
|
||||
|
||||
// POST /deploy-compose — deploy parsed services
|
||||
@@ -300,7 +301,7 @@ module.exports = function({ docker, caddy, servicesStateManager, portLockManager
|
||||
results.push({ type: 'container', name: svc.name, status: 'skipped', reason: svc.reason });
|
||||
}
|
||||
|
||||
res.json({ success: true, results, stackName: stackName || prefix });
|
||||
ok(res, { results, stackName: stackName || prefix });
|
||||
}, 'compose-deploy'));
|
||||
|
||||
// DELETE /compose-stack/:stackName — remove an entire stack
|
||||
@@ -329,7 +330,7 @@ module.exports = function({ docker, caddy, servicesStateManager, portLockManager
|
||||
});
|
||||
await servicesStateManager.update(data => { data.services = updated; });
|
||||
|
||||
res.json({ success: true, removed, count: removed.length });
|
||||
ok(res, { removed, count: removed.length });
|
||||
}, 'compose-stack-delete'));
|
||||
|
||||
return router;
|
||||
|
||||
@@ -8,6 +8,7 @@ const { exists } = require('../../fs-helpers');
|
||||
const platformPaths = require('../../platform-paths');
|
||||
const { ValidationError } = require('../../errors');
|
||||
const { logError } = require('../../src/utils/logging');
|
||||
const { ok } = require('../../src/utils/responses');
|
||||
/**
|
||||
* Apps deployment routes factory
|
||||
* @param {Object} deps - Explicit dependencies
|
||||
@@ -197,8 +198,18 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
||||
}
|
||||
}
|
||||
|
||||
const container = await docker.client.createContainer(containerConfig);
|
||||
await container.start();
|
||||
let container;
|
||||
try {
|
||||
container = await docker.client.createContainer(containerConfig);
|
||||
await container.start();
|
||||
} catch (createErr) {
|
||||
// If create fails with "no such image", wrap with user-friendly message
|
||||
const errMsg = createErr?.message || String(createErr);
|
||||
if (errMsg.includes('No such image') || errMsg.includes('no such image')) {
|
||||
throw new Error(`[DC-201] Image pull succeeded but container creation failed — image may be corrupted: ${processedTemplate.docker.image}. ${errMsg}`);
|
||||
}
|
||||
throw createErr;
|
||||
}
|
||||
|
||||
// Prune dangling images to prevent disk bloat
|
||||
try {
|
||||
@@ -233,9 +244,9 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
||||
if (!template) throw new ValidationError('Invalid app template');
|
||||
const existingContainer = await helpers.findExistingContainerByImage(template);
|
||||
if (existingContainer) {
|
||||
res.json({ success: true, exists: true, container: existingContainer, message: `Found existing ${template.name} container: ${existingContainer.name}` });
|
||||
ok(res, { exists: true, container: existingContainer, message: `Found existing ${template.name} container: ${existingContainer.name}` });
|
||||
} else {
|
||||
res.json({ success: true, exists: false, message: `No existing ${template.name} container found` });
|
||||
ok(res, { exists: false, message: `No existing ${template.name} container found` });
|
||||
}
|
||||
}, 'check-existing'));
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const express = require('express');
|
||||
const { exists } = require('../../fs-helpers');
|
||||
const { logError } = require('../../src/utils/logging');
|
||||
const { ok } = require('../../src/utils/responses');
|
||||
|
||||
module.exports = function({
|
||||
docker, caddy, servicesStateManager, asyncHandler, log, helpers,
|
||||
@@ -135,7 +136,7 @@ module.exports = function({
|
||||
results.service = error.message;
|
||||
}
|
||||
|
||||
res.json({ success: true, message: `App ${appId} removal completed`, results });
|
||||
ok(res, { message: `App ${appId} removal completed`, results });
|
||||
} catch (error) {
|
||||
await logError('app-removal', error);
|
||||
errorResponse(res, 500, ctx.safeErrorMessage(error), { results });
|
||||
|
||||
@@ -2,6 +2,7 @@ const express = require('express');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { DOCKER } = require('../../constants');
|
||||
const { ok, validationError, notFound, errorResponse } = require('../../src/utils/responses');
|
||||
|
||||
const DEFAULT_BACKUP_DIR = process.env.BACKUP_DIR || path.join(__dirname, '..', 'backups');
|
||||
|
||||
@@ -47,7 +48,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
||||
}
|
||||
|
||||
const result = await restoreService(service);
|
||||
res.json({ success: true, result });
|
||||
ok(res, { result });
|
||||
}, 'apps-restore'));
|
||||
|
||||
/**
|
||||
@@ -59,8 +60,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
||||
const restoreable = services.filter(s => s.deploymentManifest);
|
||||
|
||||
if (restoreable.length === 0) {
|
||||
return res.json({
|
||||
success: true,
|
||||
return ok(res, {
|
||||
message: 'No services have deployment manifests to restore',
|
||||
results: []
|
||||
});
|
||||
@@ -85,8 +85,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
||||
const skipped = results.filter(r => r.status === 'skipped').length;
|
||||
const failed = results.filter(r => r.status === 'failed').length;
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
message: `Restore complete: ${succeeded} restored, ${skipped} skipped, ${failed} failed`,
|
||||
results
|
||||
});
|
||||
@@ -123,7 +122,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
||||
status.push(entry);
|
||||
}
|
||||
|
||||
res.json({ success: true, services: status });
|
||||
ok(res, { services: status });
|
||||
}, 'apps-restore-status'));
|
||||
|
||||
// ==================== POINT-IN-TIME RESTORE (BACKUP FILE BASED) ====================
|
||||
@@ -174,8 +173,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
||||
// Sort by timestamp descending (newest first)
|
||||
files.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
appId,
|
||||
isBackupFile: true,
|
||||
files,
|
||||
@@ -190,12 +188,12 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
||||
|
||||
// Security: prevent path traversal
|
||||
if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
|
||||
return res.status(400).json({ success: false, error: 'Invalid filename' });
|
||||
return validationError(res, 'Invalid filename');
|
||||
}
|
||||
|
||||
const filepath = path.join(DEFAULT_BACKUP_DIR, filename);
|
||||
if (!fs.existsSync(filepath)) {
|
||||
return res.status(404).json({ success: false, error: `Backup file not found: ${filename}` });
|
||||
return notFound(res, `Backup file not found: ${filename}`);
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -207,7 +205,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
||||
try {
|
||||
fileData = await backupManager.decryptBackup(fileData, encryptionKey);
|
||||
} catch (err) {
|
||||
return res.status(400).json({ success: false, error: 'Failed to decrypt backup: ' + err.message });
|
||||
return validationError(res, 'Failed to decrypt backup: ' + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,8 +262,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
||||
// Cleanup temp dir
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
isBackupFile: true,
|
||||
restored: {
|
||||
services: !!restoreData.services,
|
||||
@@ -277,8 +274,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
||||
} else {
|
||||
// Preview mode
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
isBackupFile: true,
|
||||
preview: true,
|
||||
filename,
|
||||
@@ -296,7 +292,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
||||
throw err;
|
||||
}
|
||||
} catch (err) {
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
errorResponse(res, 500, err.message);
|
||||
}
|
||||
}, 'apps-revert'));
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ const { exists } = require('../../fs-helpers');
|
||||
* @returns {express.Router}
|
||||
*/
|
||||
const { REGEX } = require('../../constants');
|
||||
const { ok } = require('../../src/utils/responses');
|
||||
|
||||
module.exports = function({
|
||||
servicesStateManager, asyncHandler, helpers,
|
||||
@@ -42,8 +43,7 @@ module.exports = function({
|
||||
|
||||
// Get available app templates
|
||||
router.get('/templates', asyncHandler(async (req, res) => {
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
templates: ctx.APP_TEMPLATES,
|
||||
categories: ctx.TEMPLATE_CATEGORIES,
|
||||
difficultyLevels: ctx.DIFFICULTY_LEVELS
|
||||
@@ -58,7 +58,7 @@ module.exports = function({
|
||||
const { NotFoundError } = require('../../errors');
|
||||
throw new NotFoundError('App template');
|
||||
}
|
||||
res.json({ success: true, template });
|
||||
ok(res, { template });
|
||||
}, 'apps-template-detail'));
|
||||
|
||||
// Check port availability
|
||||
@@ -80,7 +80,7 @@ module.exports = function({
|
||||
const usedPorts = await docker.getUsedPorts();
|
||||
for (let port = basePort; port < basePort + maxAttempts; port++) {
|
||||
if (!usedPorts.has(port)) {
|
||||
res.json({ success: true, suggestedPort: port, basePort });
|
||||
ok(res, { suggestedPort: port, basePort });
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -170,8 +170,7 @@ module.exports = function({
|
||||
log.warn('deploy', 'Service update warning', { error: error.message || String(error) });
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
message: `Subdomain updated: ${oldSubdomain} -> ${newSubdomain}`,
|
||||
newUrl: `https://${ctx.buildDomain(newSubdomain)}`,
|
||||
results
|
||||
|
||||
@@ -3,6 +3,7 @@ const { APP_PORTS, ARR_SERVICES } = require('../../constants');
|
||||
const { validateURL, validateToken } = require('../../input-validator');
|
||||
const { ValidationError, AuthenticationError, NotFoundError } = require('../../errors');
|
||||
const { logError } = require('../../src/utils/logging');
|
||||
const { ok, successMessage } = require('../../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Arr configuration routes factory
|
||||
@@ -258,11 +259,7 @@ module.exports = function(ctx) {
|
||||
const version = service === 'plex' ? data.MediaContainer?.version : data.version;
|
||||
const appName = service === 'plex' ? 'Plex' : data.appName;
|
||||
log.info('arr', 'Service connection successful', { service, appName, version });
|
||||
return res.json({
|
||||
success: true,
|
||||
version,
|
||||
appName
|
||||
});
|
||||
return ok(res, { version, appName });
|
||||
} else if (response.status === 401) {
|
||||
throw new AuthenticationError('Invalid API key');
|
||||
} else if (response.status === 404) {
|
||||
@@ -553,7 +550,7 @@ module.exports = function(ctx) {
|
||||
const metadata = await credentialManager.getMetadata(`arr.${service}.apikey`);
|
||||
const storedProfileId = metadata?.qualityProfileId || null;
|
||||
|
||||
res.json({ success: true, profiles: mapped, storedProfileId });
|
||||
ok(res, { profiles: mapped, storedProfileId });
|
||||
} catch (e) {
|
||||
if (e.cause?.code === 'ECONNREFUSED') {
|
||||
return errorResponse(res, 502, 'Connection refused — is the service running?');
|
||||
@@ -588,7 +585,7 @@ module.exports = function(ctx) {
|
||||
existing.qualityProfileName = qualityProfileName || null;
|
||||
await credentialManager.storeMetadata(credKey, existing);
|
||||
|
||||
res.json({ success: true, message: `Quality profile updated for ${service}` });
|
||||
successMessage(res, `Quality profile updated for ${service}`);
|
||||
}, 'arr-quality-profile-save'));
|
||||
|
||||
return router;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const express = require('express');
|
||||
const { validateURL, validateToken } = require('../../input-validator');
|
||||
const { ValidationError } = require('../../errors');
|
||||
const { ok, successMessage } = require('../../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Arr credentials routes factory
|
||||
@@ -101,12 +102,7 @@ module.exports = function({ credentialManager, servicesStateManager, asyncHandle
|
||||
|
||||
log.info('arr', 'Stored API key', { service, verified: connectionTest?.success || false });
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: `${service} API key stored`,
|
||||
connectionTest,
|
||||
url: resolvedUrl
|
||||
});
|
||||
ok(res, { message: `${service} API key stored`, connectionTest, url: resolvedUrl });
|
||||
}, 'arr-credentials-store'));
|
||||
|
||||
// List stored arr credentials (keys only, not values)
|
||||
@@ -131,7 +127,7 @@ module.exports = function({ credentialManager, servicesStateManager, asyncHandle
|
||||
// Get seedbox base URL
|
||||
const seedboxBaseUrl = await credentialManager.retrieve('arr.seedbox.baseurl');
|
||||
|
||||
res.json({ success: true, credentials, seedboxBaseUrl: seedboxBaseUrl || null });
|
||||
ok(res, { credentials, seedboxBaseUrl: seedboxBaseUrl || null });
|
||||
}, 'arr-credentials-list'));
|
||||
|
||||
// Delete stored arr credentials
|
||||
@@ -140,7 +136,7 @@ module.exports = function({ credentialManager, servicesStateManager, asyncHandle
|
||||
const credKey = service === 'plex' ? 'arr.plex.token' : `arr.${service}.apikey`;
|
||||
await credentialManager.delete(credKey);
|
||||
log.info('arr', 'Deleted credentials', { service });
|
||||
res.json({ success: true, message: `${service} credentials removed` });
|
||||
successMessage(res, `${service} credentials removed`);
|
||||
}, 'arr-credentials-delete'));
|
||||
|
||||
return router;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const express = require('express');
|
||||
const { APP_PORTS, ARR_SERVICES } = require('../../constants');
|
||||
const { ok } = require('../../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Arr service detection routes factory
|
||||
@@ -62,8 +63,7 @@ module.exports = function({ docker, servicesStateManager, credentialManager, fet
|
||||
detected.plex.token = await helpers.getPlexToken(detected.plex.containerName);
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
services: detected,
|
||||
summary: {
|
||||
plexReady: !!(detected.plex?.token),
|
||||
@@ -287,7 +287,7 @@ module.exports = function({ docker, servicesStateManager, credentialManager, fet
|
||||
readyForAutoConnect: statuses.filter(s => s.status === 'connected').length >= 2
|
||||
};
|
||||
|
||||
res.json({ success: true, services: result, seedboxBaseUrl: detectedSeedboxUrl, summary });
|
||||
ok(res, { services: result, seedboxBaseUrl: detectedSeedboxUrl, summary });
|
||||
}, 'smart-detect'));
|
||||
|
||||
return router;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const express = require('express');
|
||||
const { APP_PORTS } = require('../../constants');
|
||||
const { ok } = require('../../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Plex routes factory
|
||||
@@ -86,7 +87,7 @@ module.exports = function({ fetchT, asyncHandler, errorResponse, log: _log, help
|
||||
lastVerified: new Date().toISOString()
|
||||
});
|
||||
|
||||
res.json({ success: true, serverName, version, libraries });
|
||||
ok(res, { serverName, version, libraries });
|
||||
}, 'plex-libraries'));
|
||||
|
||||
return router;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const express = require('express');
|
||||
const { ValidationError, ForbiddenError, NotFoundError } = require('../../errors');
|
||||
const { ok, successMessage } = require('../../src/utils/responses');
|
||||
/**
|
||||
* Auth API keys routes factory
|
||||
* @param {Object} deps - Explicit dependencies
|
||||
@@ -39,7 +40,7 @@ module.exports = function({ authManager, asyncHandler, log }) {
|
||||
}
|
||||
|
||||
const keys = await authManager.listAPIKeys();
|
||||
res.json({ success: true, keys });
|
||||
ok(res, { keys });
|
||||
}, 'auth-keys-list'));
|
||||
|
||||
// Generate new API key
|
||||
@@ -66,8 +67,7 @@ module.exports = function({ authManager, asyncHandler, log }) {
|
||||
scopes || ['read', 'write']
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
key: keyData.key,
|
||||
id: keyData.id,
|
||||
name: keyData.name,
|
||||
@@ -93,7 +93,7 @@ module.exports = function({ authManager, asyncHandler, log }) {
|
||||
const success = await authManager.revokeAPIKey(keyId);
|
||||
|
||||
if (success) {
|
||||
res.json({ success: true, message: 'API key revoked successfully' });
|
||||
successMessage(res, 'API key revoked successfully');
|
||||
} else {
|
||||
throw new NotFoundError(`API key ${keyId}`);
|
||||
}
|
||||
@@ -126,8 +126,7 @@ module.exports = function({ authManager, asyncHandler, log }) {
|
||||
const expiresInMs = parseExpiration(expiresIn || '24h');
|
||||
const expiresAt = new Date(Date.now() + expiresInMs).toISOString();
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
token,
|
||||
expiresAt,
|
||||
usage: 'Include in Authorization header as: Bearer <token>'
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const express = require('express');
|
||||
const { ValidationError, AuthenticationError } = require('../../errors');
|
||||
const { ok, successMessage } = require('../../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Auth TOTP routes factory
|
||||
@@ -27,8 +28,7 @@ module.exports = function({ authManager, credentialManager, totpConfig, saveTotp
|
||||
|
||||
// Get current TOTP config (public route)
|
||||
router.get('/totp/config', asyncHandler(async (req, res) => {
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
config: {
|
||||
enabled: ctx.totpConfig.enabled,
|
||||
sessionDuration: ctx.totpConfig.sessionDuration,
|
||||
@@ -62,7 +62,7 @@ module.exports = function({ authManager, credentialManager, totpConfig, saveTotp
|
||||
color: { dark: '#ffffff', light: '#00000000' }
|
||||
});
|
||||
|
||||
res.json({ success: true, qrCode: qrDataUrl, manualKey: secret, issuer: 'DashCaddy', imported: !!req.body?.secret });
|
||||
ok(res, { qrCode: qrDataUrl, manualKey: secret, issuer: 'DashCaddy', imported: !!req.body?.secret });
|
||||
}, 'totp-setup'));
|
||||
|
||||
// Verify first code to confirm setup, then activate TOTP
|
||||
@@ -99,7 +99,7 @@ module.exports = function({ authManager, credentialManager, totpConfig, saveTotp
|
||||
ctx.session.create(req, ctx.totpConfig.sessionDuration);
|
||||
ctx.session.setCookie(res, ctx.totpConfig.sessionDuration);
|
||||
|
||||
res.json({ success: true, message: 'TOTP enabled successfully', sessionDuration: ctx.totpConfig.sessionDuration });
|
||||
ok(res, { message: 'TOTP enabled successfully', sessionDuration: ctx.totpConfig.sessionDuration });
|
||||
}, 'totp-verify-setup'));
|
||||
|
||||
// Login: verify TOTP code and set session cookie
|
||||
@@ -133,7 +133,7 @@ module.exports = function({ authManager, credentialManager, totpConfig, saveTotp
|
||||
const newCsrfToken = renewCSRFToken(res, req.secure || req.protocol === 'https');
|
||||
|
||||
log.debug('auth', 'Session created', { sessions: ctx.session.ipSessions.size });
|
||||
res.json({ success: true, message: 'Authenticated successfully', sessionDuration: ctx.totpConfig.sessionDuration, csrfToken: newCsrfToken });
|
||||
ok(res, { message: 'Authenticated successfully', sessionDuration: ctx.totpConfig.sessionDuration, csrfToken: newCsrfToken });
|
||||
}, 'totp-verify'));
|
||||
|
||||
// Check session validity (used by Caddy forward_auth)
|
||||
@@ -185,7 +185,7 @@ module.exports = function({ authManager, credentialManager, totpConfig, saveTotp
|
||||
|
||||
ctx.session.clear(req);
|
||||
ctx.session.clearCookie(res);
|
||||
res.json({ success: true, message: 'TOTP disabled' });
|
||||
successMessage(res, 'TOTP disabled');
|
||||
}, 'totp-disable'));
|
||||
|
||||
// Update TOTP settings (session duration)
|
||||
@@ -204,8 +204,7 @@ module.exports = function({ authManager, credentialManager, totpConfig, saveTotp
|
||||
}
|
||||
|
||||
await ctx.saveTotpConfig();
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
config: { enabled: ctx.totpConfig.enabled, sessionDuration: ctx.totpConfig.sessionDuration, isSetUp: ctx.totpConfig.isSetUp }
|
||||
});
|
||||
}, 'totp-config'));
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const { success } = require('../response-helpers');
|
||||
const { success } = require('../src/utils/responses');
|
||||
const { ValidationError, NotFoundError } = require('../errors');
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const express = require('express');
|
||||
const { success } = require('../response-helpers');
|
||||
const { success } = require('../src/utils/responses');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ const path = require('path');
|
||||
const { exists, isAccessible } = require('../fs-helpers');
|
||||
const { paginate, parsePaginationParams } = require('../pagination');
|
||||
const { ValidationError, ForbiddenError } = require('../errors');
|
||||
const { ok } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Browse route factory
|
||||
@@ -44,7 +45,7 @@ module.exports = function({ asyncHandler, validateSecurePath, auditLogger, docke
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ success: true, roots });
|
||||
return ok(res, { roots });
|
||||
}, 'browse-roots'));
|
||||
|
||||
// Browse directory contents
|
||||
@@ -64,7 +65,7 @@ module.exports = function({ asyncHandler, validateSecurePath, auditLogger, docke
|
||||
roots.push(r);
|
||||
}
|
||||
}
|
||||
return res.json({ success: true, path: '', items: roots });
|
||||
return ok(res, { path: '', items: roots });
|
||||
}
|
||||
|
||||
const matchingRoot = BROWSE_ROOTS.find(r =>
|
||||
@@ -124,8 +125,7 @@ module.exports = function({ asyncHandler, validateSecurePath, auditLogger, docke
|
||||
|
||||
const paginationParams = parsePaginationParams(req.query);
|
||||
const result = paginate(folders, paginationParams);
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
path: requestedPath,
|
||||
parent: path.dirname(requestedPath).replace(/\\/g, '/') || null,
|
||||
items: result.data,
|
||||
@@ -190,8 +190,7 @@ module.exports = function({ asyncHandler, validateSecurePath, auditLogger, docke
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
mounts: detectedMounts,
|
||||
message: detectedMounts.length > 0
|
||||
? `Found ${detectedMounts.length} media mount(s) from existing containers`
|
||||
|
||||
+14
-20
@@ -5,6 +5,7 @@ const path = require('path');
|
||||
const { execSync } = require('child_process');
|
||||
const { exists } = require('../fs-helpers');
|
||||
const { ValidationError } = require('../errors');
|
||||
const { ok } = require('../src/utils/responses');
|
||||
const platformPaths = require('../platform-paths');
|
||||
|
||||
module.exports = function(ctx) {
|
||||
@@ -12,14 +13,11 @@ module.exports = function(ctx) {
|
||||
|
||||
// Get CA certificate information
|
||||
router.get('/info', ctx.asyncHandler(async (req, res) => {
|
||||
const certInfoPath = '/app/ca/cert-info.json';
|
||||
const fallbackCertInfoPath = path.join(platformPaths.caCertDir, 'cert-info.json');
|
||||
const certInfoPath = path.join(platformPaths.caCertDir, 'cert-info.json');
|
||||
|
||||
let certInfoFile;
|
||||
if (await exists(certInfoPath)) {
|
||||
certInfoFile = certInfoPath;
|
||||
} else if (await exists(fallbackCertInfoPath)) {
|
||||
certInfoFile = fallbackCertInfoPath;
|
||||
} else {
|
||||
const { NotFoundError } = require('../errors');
|
||||
throw new NotFoundError('CA certificate information');
|
||||
@@ -29,8 +27,7 @@ module.exports = function(ctx) {
|
||||
const expirationDate = new Date(certInfo.validUntil);
|
||||
const daysUntilExpiration = Math.floor((expirationDate - new Date()) / (1000 * 60 * 60 * 24));
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
certificate: {
|
||||
name: certInfo.name,
|
||||
fingerprint: certInfo.fingerprint,
|
||||
@@ -46,13 +43,11 @@ module.exports = function(ctx) {
|
||||
|
||||
// Serve root CA certificate directly (works even without DashCA deployed)
|
||||
router.get('/root.crt', ctx.asyncHandler(async (req, res) => {
|
||||
const pkiCertPath = '/app/pki/root.crt';
|
||||
const hostCertPath = platformPaths.pkiRootCert;
|
||||
const dashcaCertPath = path.join(platformPaths.caCertDir, 'root.crt');
|
||||
|
||||
let certPath;
|
||||
if (await exists(pkiCertPath)) certPath = pkiCertPath;
|
||||
else if (await exists(dashcaCertPath)) certPath = dashcaCertPath;
|
||||
if (await exists(dashcaCertPath)) certPath = dashcaCertPath;
|
||||
else if (await exists(hostCertPath)) certPath = hostCertPath;
|
||||
else {
|
||||
const { NotFoundError } = require('../errors');
|
||||
@@ -72,13 +67,12 @@ module.exports = function(ctx) {
|
||||
}
|
||||
|
||||
// Load cert info to get the fingerprint
|
||||
const certInfoPath = '/app/ca/cert-info.json';
|
||||
const fallbackCertInfoPath2 = path.join(platformPaths.caCertDir, 'cert-info.json');
|
||||
const certInfoPath = path.join(platformPaths.caCertDir, 'cert-info.json');
|
||||
|
||||
let certInfoFile;
|
||||
if (await exists(certInfoPath)) certInfoFile = certInfoPath;
|
||||
else if (await exists(fallbackCertInfoPath2)) certInfoFile = fallbackCertInfoPath2;
|
||||
else {
|
||||
if (await exists(certInfoPath)) {
|
||||
certInfoFile = certInfoPath;
|
||||
} else {
|
||||
const { NotFoundError } = require('../errors');
|
||||
throw new NotFoundError('CA certificate information. Deploy DashCA first or ensure cert-info.json exists.');
|
||||
}
|
||||
@@ -100,7 +94,7 @@ module.exports = function(ctx) {
|
||||
// Look for template in multiple locations (packaged app vs dev)
|
||||
const templatePaths = [
|
||||
path.join(__dirname, '..', 'scripts', templateName),
|
||||
path.join('/app', 'scripts', templateName)
|
||||
path.join(platformPaths.caddyBase, 'scripts', templateName)
|
||||
];
|
||||
|
||||
let templateContent;
|
||||
@@ -142,8 +136,8 @@ module.exports = function(ctx) {
|
||||
return ctx.errorResponse(res, 400, `Invalid domain name. Must be a valid hostname (e.g., dns1${ctx.siteConfig.tld})`);
|
||||
}
|
||||
|
||||
const pkiPath = '/app/pki';
|
||||
const certsDir = '/app/generated-certs';
|
||||
const pkiPath = platformPaths.pkiDir;
|
||||
const certsDir = platformPaths.generatedCertsDir;
|
||||
const domainDir = path.join(certsDir, domain);
|
||||
|
||||
const intermediateCert = path.join(pkiPath, 'intermediate.crt');
|
||||
@@ -246,10 +240,10 @@ ${safeDomain.includes('.') ? `DNS.2 = *.${safeDomain}` : ''}`;
|
||||
|
||||
// List generated certificates
|
||||
router.get('/certs', ctx.asyncHandler(async (req, res) => {
|
||||
const certsDir = '/app/generated-certs';
|
||||
const certsDir = platformPaths.generatedCertsDir;
|
||||
|
||||
if (!await exists(certsDir)) {
|
||||
return res.json({ success: true, certificates: [] });
|
||||
return ok(res, { certificates: [] });
|
||||
}
|
||||
|
||||
const dirEntries = await fsp.readdir(certsDir);
|
||||
@@ -284,7 +278,7 @@ ${safeDomain.includes('.') ? `DNS.2 = *.${safeDomain}` : ''}`;
|
||||
}
|
||||
}))).filter(Boolean);
|
||||
|
||||
res.json({ success: true, certificates });
|
||||
ok(res, { certificates });
|
||||
}, 'ca-certs'));
|
||||
|
||||
return router;
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const { success } = require('../response-helpers');
|
||||
const { success } = require('../src/utils/responses');
|
||||
const { ValidationError, NotFoundError } = require('../errors');
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,6 +4,8 @@ const path = require('path');
|
||||
const { LIMITS } = require('../../constants');
|
||||
const { exists } = require('../../fs-helpers');
|
||||
const { ValidationError } = require('../../errors');
|
||||
const platformPaths = require('../../platform-paths');
|
||||
const { ok, successMessage } = require('../../src/utils/responses');
|
||||
/**
|
||||
* Config assets routes factory
|
||||
* @param {Object} deps - Explicit dependencies
|
||||
@@ -51,7 +53,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
const buffer = Buffer.from(base64Data, 'base64');
|
||||
|
||||
// Determine assets path (mounted volume)
|
||||
const assetsPath = process.env.ASSETS_PATH || '/app/assets';
|
||||
const assetsPath = platformPaths.resolveAssetsPath(process.env.ASSETS_PATH);
|
||||
|
||||
// Ensure directory exists
|
||||
if (!await exists(assetsPath)) {
|
||||
@@ -62,8 +64,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
const filePath = path.join(assetsPath, safeFilename);
|
||||
await fsp.writeFile(filePath, buffer);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
path: `/assets/${safeFilename}`,
|
||||
message: `Logo saved to ${filePath}`
|
||||
});
|
||||
@@ -75,8 +76,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
// Get current logo path, position, and title
|
||||
router.get('/logo', asyncHandler(async (req, res) => {
|
||||
const config = await ctx.readConfig();
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
// Dark/light variants (new)
|
||||
customLogoDark: config.customLogoDark || null,
|
||||
customLogoLight: config.customLogoLight || null,
|
||||
@@ -96,7 +96,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
const extension = matches[1] === 'svg+xml' ? 'svg' : matches[1];
|
||||
const buffer = Buffer.from(matches[2], 'base64');
|
||||
|
||||
const assetsPath = process.env.ASSETS_PATH || '/app/assets';
|
||||
const assetsPath = platformPaths.resolveAssetsPath(process.env.ASSETS_PATH);
|
||||
if (!await exists(assetsPath)) {
|
||||
await fsp.mkdir(assetsPath, { recursive: true });
|
||||
}
|
||||
@@ -155,8 +155,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
config.updatedAt = new Date().toISOString();
|
||||
await fsp.writeFile(ctx.CONFIG_FILE, JSON.stringify(config, null, 2), 'utf8');
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
pathDark: pathDark,
|
||||
pathLight: pathLight,
|
||||
// Legacy compat
|
||||
@@ -170,7 +169,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
// Reset all branding to defaults
|
||||
router.delete('/logo', asyncHandler(async (req, res) => {
|
||||
const config = await ctx.readConfig();
|
||||
const assetsPath = process.env.ASSETS_PATH || '/app/assets';
|
||||
const assetsPath = platformPaths.resolveAssetsPath(process.env.ASSETS_PATH);
|
||||
|
||||
// Delete all custom logo files
|
||||
const logoPaths = [config.customLogo, config.customLogoDark, config.customLogoLight].filter(Boolean);
|
||||
@@ -194,10 +193,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
config.updatedAt = new Date().toISOString();
|
||||
await fsp.writeFile(ctx.CONFIG_FILE, JSON.stringify(config, null, 2), 'utf8');
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Branding reset to defaults'
|
||||
});
|
||||
successMessage(res, 'Branding reset to defaults');
|
||||
}, 'logo-delete'));
|
||||
|
||||
// ===== FAVICON ENDPOINTS =====
|
||||
@@ -206,8 +202,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
// Get current favicon
|
||||
router.get('/favicon', asyncHandler(async (req, res) => {
|
||||
const config = await ctx.readConfig();
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
customFavicon: config.customFavicon || null,
|
||||
isDefault: !config.customFavicon
|
||||
});
|
||||
@@ -234,7 +229,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
const base64Data = matches[2];
|
||||
const buffer = Buffer.from(base64Data, 'base64');
|
||||
|
||||
const assetsPath = process.env.ASSETS_PATH || '/app/assets';
|
||||
const assetsPath = platformPaths.resolveAssetsPath(process.env.ASSETS_PATH);
|
||||
if (!await exists(assetsPath)) {
|
||||
await fsp.mkdir(assetsPath, { recursive: true });
|
||||
}
|
||||
@@ -267,8 +262,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
// Update config
|
||||
await ctx.saveConfig({ customFavicon: '/assets/favicon.ico', updatedAt: new Date().toISOString() });
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
path: '/assets/favicon.ico',
|
||||
message: 'Favicon created successfully'
|
||||
});
|
||||
@@ -279,7 +273,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
const config = await ctx.readConfig();
|
||||
|
||||
// Delete custom favicon files
|
||||
const assetsPath = process.env.ASSETS_PATH || '/app/assets';
|
||||
const assetsPath = platformPaths.resolveAssetsPath(process.env.ASSETS_PATH);
|
||||
const filesToDelete = ['favicon.ico', 'favicon.png'];
|
||||
for (const file of filesToDelete) {
|
||||
const filePath = `${assetsPath}/${file}`;
|
||||
@@ -292,10 +286,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
config.updatedAt = new Date().toISOString();
|
||||
await fsp.writeFile(ctx.CONFIG_FILE, JSON.stringify(config, null, 2), 'utf8');
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Favicon reset to default'
|
||||
});
|
||||
successMessage(res, 'Favicon reset to default');
|
||||
}, 'favicon-delete'));
|
||||
|
||||
return router;
|
||||
|
||||
@@ -4,6 +4,8 @@ const path = require('path');
|
||||
const { CADDY } = require('../../constants');
|
||||
const { exists } = require('../../fs-helpers');
|
||||
const { ValidationError, AuthenticationError } = require('../../errors');
|
||||
const platformPaths = require('../../platform-paths');
|
||||
const { ok } = require('../../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Config backup routes factory
|
||||
@@ -115,7 +117,7 @@ module.exports = function(deps) {
|
||||
|
||||
// Include custom assets (logo, favicon) as base64
|
||||
try {
|
||||
const assetsDir = process.env.ASSETS_DIR || '/app/assets';
|
||||
const assetsDir = platformPaths.resolveAssetsPath(process.env.ASSETS_DIR);
|
||||
const configData = backup.files.config?.data || {};
|
||||
const assetFiles = [configData.customLogo, configData.customFavicon]
|
||||
.filter(Boolean)
|
||||
@@ -209,7 +211,7 @@ module.exports = function(deps) {
|
||||
preview.browserStateCount = Object.keys(backup.browserState).length;
|
||||
}
|
||||
|
||||
res.json({ success: true, preview });
|
||||
ok(res, { preview });
|
||||
}, 'backup-preview'));
|
||||
|
||||
// Restore configuration from backup
|
||||
@@ -346,7 +348,7 @@ module.exports = function(deps) {
|
||||
|
||||
// Restore custom assets from base64
|
||||
if (backup.assets && typeof backup.assets === 'object') {
|
||||
const assetsDir = process.env.ASSETS_DIR || '/app/assets';
|
||||
const assetsDir = platformPaths.resolveAssetsPath(process.env.ASSETS_DIR);
|
||||
for (const [name, b64] of Object.entries(backup.assets)) {
|
||||
try {
|
||||
const safeName = path.basename(name); // prevent path traversal
|
||||
@@ -390,13 +392,17 @@ module.exports = function(deps) {
|
||||
|
||||
const success = results.restored.length > 0 && results.errors.length === 0;
|
||||
|
||||
res.json({
|
||||
success,
|
||||
message: success
|
||||
? `Restored ${results.restored.length} file(s) successfully`
|
||||
: `Restore completed with ${results.errors.length} error(s)`,
|
||||
results
|
||||
});
|
||||
if (success) {
|
||||
ok(res, {
|
||||
message: `Restored ${results.restored.length} file(s) successfully`,
|
||||
results
|
||||
});
|
||||
} else {
|
||||
ok(res, {
|
||||
message: `Restore completed with ${results.errors.length} error(s)`,
|
||||
results
|
||||
}, 200);
|
||||
}
|
||||
|
||||
log.info('backup', 'Backup restore completed', { restored: results.restored.length, errors: results.errors.length });
|
||||
}, 'backup-restore'));
|
||||
|
||||
@@ -2,6 +2,7 @@ const fsp = require('fs').promises;
|
||||
const { validateConfig } = require('../../config-schema');
|
||||
const { exists } = require('../../fs-helpers');
|
||||
const { ValidationError } = require('../../errors');
|
||||
const { ok, successMessage } = require('../../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Config settings routes factory
|
||||
@@ -71,14 +72,14 @@ module.exports = function({ configStateManager: _configStateManager, asyncHandle
|
||||
}
|
||||
log.info('config', 'Config saved', { path: ctx.CONFIG_FILE });
|
||||
|
||||
res.json({ success: true, message: 'Configuration saved', config, warnings });
|
||||
ok(res, { message: 'Configuration saved', config, warnings });
|
||||
}, 'config-save'));
|
||||
|
||||
router.delete('/config', asyncHandler(async (req, res) => {
|
||||
if (await exists(ctx.CONFIG_FILE)) {
|
||||
await fsp.unlink(ctx.CONFIG_FILE);
|
||||
}
|
||||
res.json({ success: true, message: 'Configuration reset' });
|
||||
successMessage(res, 'Configuration reset');
|
||||
}, 'config-delete'));
|
||||
|
||||
return router;
|
||||
|
||||
@@ -2,7 +2,7 @@ const express = require('express');
|
||||
const { DOCKER } = require('../constants');
|
||||
const { paginate, parsePaginationParams } = require('../pagination');
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { success } = require('../response-helpers');
|
||||
const { success } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Containers route factory
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const express = require('express');
|
||||
const { success, error: errorResponse } = require('../response-helpers');
|
||||
const { success, error: errorResponse } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Credentials routes factory
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const { success, error: errorResponse } = require('../response-helpers');
|
||||
const { success, error: errorResponse } = require('../src/utils/responses');
|
||||
const { NotFoundError, ValidationError } = require('../errors');
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,7 +4,7 @@ const fsp = require('fs').promises;
|
||||
const validatorLib = require('validator');
|
||||
const { APP, TIMEOUTS, CADDY, DNS_RECORD_TYPES, REGEX, SESSION_TTL } = require('../constants');
|
||||
const { exists } = require('../fs-helpers');
|
||||
const { success, error: errorResponse } = require('../response-helpers');
|
||||
const { success, error: errorResponse } = require('../src/utils/responses');
|
||||
const { ValidationError, AuthenticationError, NotFoundError } = require('../errors');
|
||||
|
||||
/**
|
||||
@@ -383,9 +383,8 @@ module.exports = function({
|
||||
|
||||
const response = await fetchT(technitiumUrl, {
|
||||
method: 'GET',
|
||||
headers: { 'Accept': 'text/plain' },
|
||||
timeout: 10000
|
||||
});
|
||||
headers: { 'Accept': 'text/plain' }
|
||||
}, 10000);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
@@ -553,7 +552,7 @@ module.exports = function({
|
||||
}
|
||||
}
|
||||
|
||||
return res.json({
|
||||
return ok(res, {
|
||||
success: anySuccess,
|
||||
message: anySuccess ? 'Credentials saved for one or more servers' : 'All server credential tests failed',
|
||||
results
|
||||
@@ -640,7 +639,7 @@ module.exports = function({
|
||||
const dnsPort = siteConfig.dnsServerPort || '5380';
|
||||
try {
|
||||
const url = `http://${serverInfo.ip}:${dnsPort}/api/admin/restart?token=${encodeURIComponent(tokenResult.token)}`;
|
||||
const response = await fetchT(url, { method: 'POST', timeout: 5000 });
|
||||
const response = await fetchT(url, { method: 'POST' }, 5000);
|
||||
const result = await response.json();
|
||||
if (result.status === 'ok') {
|
||||
success(res, { message: 'Restart initiated' });
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const express = require('express');
|
||||
const { success } = require('../response-helpers');
|
||||
const { success } = require('../src/utils/responses');
|
||||
const { ValidationError } = require('../errors');
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,7 +3,7 @@ const fs = require('fs');
|
||||
const fsp = require('fs').promises;
|
||||
const { exists } = require('../fs-helpers');
|
||||
const { paginate, parsePaginationParams } = require('../pagination');
|
||||
const { success } = require('../response-helpers');
|
||||
const { success } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Error logs routes factory
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const express = require('express');
|
||||
const { ok } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Server-Sent Events route factory
|
||||
@@ -147,7 +148,7 @@ module.exports = function({ resourceMonitor, healthChecker, updateManager, logEr
|
||||
|
||||
// Client count (useful for debugging)
|
||||
router.get('/clients', (req, res) => {
|
||||
res.json({ success: true, count: clients.size });
|
||||
ok(res, { count: clients.size });
|
||||
});
|
||||
|
||||
return router;
|
||||
|
||||
@@ -7,7 +7,7 @@ const { exists } = require('../fs-helpers');
|
||||
const { paginate, parsePaginationParams } = require('../pagination');
|
||||
const platformPaths = require('../platform-paths');
|
||||
const { resolveServiceUrl } = require('../url-resolver');
|
||||
const { success, error: errorResponse } = require('../response-helpers');
|
||||
const { success, error: errorResponse, errorResponse: sendError, ok, notFound } = require('../src/utils/responses');
|
||||
const { ValidationError } = require('../errors');
|
||||
|
||||
/**
|
||||
@@ -273,11 +273,7 @@ module.exports = function({
|
||||
try {
|
||||
// Check if certificate exists
|
||||
if (!await exists(rootCertPath)) {
|
||||
return res.json({
|
||||
status: 'error',
|
||||
message: 'Root CA certificate not found',
|
||||
daysUntilExpiration: null
|
||||
});
|
||||
return sendError(res, 404, 'Root CA certificate not found', { caStatus: 'error', daysUntilExpiration: null });
|
||||
}
|
||||
|
||||
const dates = execSync(`openssl x509 -in "${rootCertPath}" -noout -dates`).toString();
|
||||
@@ -286,45 +282,48 @@ module.exports = function({
|
||||
const daysUntilExpiration = Math.floor((expirationDate - new Date()) / (1000 * 60 * 60 * 24));
|
||||
|
||||
// Alert thresholds
|
||||
let status = 'healthy';
|
||||
let caStatus = 'healthy';
|
||||
let message = `CA certificate valid for ${daysUntilExpiration} days`;
|
||||
|
||||
if (daysUntilExpiration < 0) {
|
||||
status = 'critical';
|
||||
caStatus = 'critical';
|
||||
message = `CA certificate EXPIRED ${Math.abs(daysUntilExpiration)} days ago!`;
|
||||
} else if (daysUntilExpiration < 7) {
|
||||
status = 'critical';
|
||||
caStatus = 'critical';
|
||||
message = `CA certificate expires in ${daysUntilExpiration} days!`;
|
||||
} else if (daysUntilExpiration < 30) {
|
||||
status = 'critical';
|
||||
caStatus = 'critical';
|
||||
message = `CA certificate expires in ${daysUntilExpiration} days!`;
|
||||
} else if (daysUntilExpiration < 90) {
|
||||
status = 'warning';
|
||||
caStatus = 'warning';
|
||||
message = `CA certificate expires in ${daysUntilExpiration} days`;
|
||||
}
|
||||
|
||||
res.json({
|
||||
status: status,
|
||||
message: message,
|
||||
daysUntilExpiration: daysUntilExpiration,
|
||||
ok(res, {
|
||||
caStatus,
|
||||
message,
|
||||
daysUntilExpiration,
|
||||
expiresAt: notAfter
|
||||
});
|
||||
} catch (error) {
|
||||
await logError('GET /api/health/ca', error);
|
||||
res.json({
|
||||
status: 'error',
|
||||
message: error.message,
|
||||
daysUntilExpiration: null
|
||||
});
|
||||
sendError(res, 500, error.message, { caStatus: 'error', daysUntilExpiration: null });
|
||||
}
|
||||
}, 'health-ca'));
|
||||
|
||||
// ===== HEALTH CHECK (health-checker module) =====
|
||||
|
||||
// Get current status for all services
|
||||
// Returns per-service status plus a summary for the System Overview widget:
|
||||
// { status: { ... }, summary: { healthy, unhealthy, total } }
|
||||
router.get('/health-checks/status', asyncHandler(async (req, res) => {
|
||||
const status = healthChecker.getCurrentStatus();
|
||||
success(res, { status });
|
||||
// Build summary for the overview widget
|
||||
const entries = Object.values(status);
|
||||
const healthy = entries.filter(s => s.status === 'up' || s.status === 'healthy').length;
|
||||
const unhealthy = entries.filter(s => s.status === 'down' || s.status === 'unhealthy').length;
|
||||
const total = entries.length;
|
||||
success(res, { status, summary: { healthy, unhealthy, total } });
|
||||
}, 'health-check-status'));
|
||||
|
||||
// Get service statistics
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const express = require('express');
|
||||
const { success, error: errorResponse } = require('../response-helpers');
|
||||
const { success, error: errorResponse } = require('../src/utils/responses');
|
||||
const { ValidationError } = require('../errors');
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,6 +5,7 @@ const path = require('path');
|
||||
const { exists } = require('../fs-helpers');
|
||||
const { paginate, parsePaginationParams } = require('../pagination');
|
||||
const { NotFoundError, ValidationError, ForbiddenError } = require('../errors');
|
||||
const { ok } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Logs route factory
|
||||
@@ -31,7 +32,7 @@ module.exports = function({ asyncHandler, docker, logDigest, dockerMaintenance }
|
||||
|
||||
const paginationParams = parsePaginationParams(req.query);
|
||||
const result = paginate(containerList, paginationParams);
|
||||
res.json({ success: true, containers: result.data, ...(result.pagination && { pagination: result.pagination }) });
|
||||
ok(res, { containers: result.data, ...(result.pagination && { pagination: result.pagination }) });
|
||||
}, 'logs-containers'));
|
||||
|
||||
// Get logs for a specific container
|
||||
@@ -81,8 +82,7 @@ module.exports = function({ asyncHandler, docker, logDigest, dockerMaintenance }
|
||||
offset += 8 + size;
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
containerId, containerName,
|
||||
logs: lines,
|
||||
count: lines.length
|
||||
@@ -153,23 +153,23 @@ module.exports = function({ asyncHandler, docker, logDigest, dockerMaintenance }
|
||||
if (!logDigest) throw new Error('Log digest not available');
|
||||
const digest = await logDigest.getLatestDigest();
|
||||
if (!digest) {
|
||||
return res.json({ success: true, digest: null, message: 'No digest available yet. First digest is generated at midnight.' });
|
||||
return ok(res, { digest: null, message: 'No digest available yet. First digest is generated at midnight.' });
|
||||
}
|
||||
res.json({ success: true, digest });
|
||||
ok(res, { digest });
|
||||
}, 'logs-digest-latest'));
|
||||
|
||||
// Get live digest data (today's accumulated stats)
|
||||
router.get('/logs/digest/live', asyncHandler(async (req, res) => {
|
||||
if (!logDigest) throw new Error('Log digest not available');
|
||||
const live = logDigest.getLiveData();
|
||||
res.json({ success: true, ...live });
|
||||
ok(res, { ...live });
|
||||
}, 'logs-digest-live'));
|
||||
|
||||
// List available digest dates
|
||||
router.get('/logs/digest/history', asyncHandler(async (req, res) => {
|
||||
if (!logDigest) throw new Error('Log digest not available');
|
||||
const dates = await logDigest.listDigests();
|
||||
res.json({ success: true, dates });
|
||||
ok(res, { dates });
|
||||
}, 'logs-digest-history'));
|
||||
|
||||
// Generate digest on demand (for today or a specific date)
|
||||
@@ -177,7 +177,7 @@ module.exports = function({ asyncHandler, docker, logDigest, dockerMaintenance }
|
||||
if (!logDigest) throw new Error('Log digest not available');
|
||||
const date = req.body.date || new Date().toISOString().slice(0, 10);
|
||||
const digest = await logDigest.generateDailyDigest(date);
|
||||
res.json({ success: true, digest });
|
||||
ok(res, { digest });
|
||||
}, 'logs-digest-generate'));
|
||||
|
||||
// Get digest for a specific date (JSON)
|
||||
@@ -196,7 +196,7 @@ module.exports = function({ asyncHandler, docker, logDigest, dockerMaintenance }
|
||||
}
|
||||
const digest = await logDigest.getDigestByDate(date);
|
||||
if (!digest) throw new NotFoundError(`Digest for ${date}`);
|
||||
res.json({ success: true, digest });
|
||||
ok(res, { digest });
|
||||
}, 'logs-digest-date'));
|
||||
|
||||
// Get Docker disk usage snapshot
|
||||
@@ -204,14 +204,14 @@ module.exports = function({ asyncHandler, docker, logDigest, dockerMaintenance }
|
||||
if (!dockerMaintenance) throw new Error('Docker maintenance not available');
|
||||
const diskUsage = await dockerMaintenance.getDiskUsage();
|
||||
const status = dockerMaintenance.getStatus();
|
||||
res.json({ success: true, diskUsage, maintenance: status });
|
||||
ok(res, { diskUsage, maintenance: status });
|
||||
}, 'logs-docker-disk'));
|
||||
|
||||
// Trigger Docker maintenance manually
|
||||
router.post('/logs/docker-maintenance', asyncHandler(async (req, res) => {
|
||||
if (!dockerMaintenance) throw new Error('Docker maintenance not available');
|
||||
const result = await dockerMaintenance.runMaintenance();
|
||||
res.json({ success: true, result });
|
||||
ok(res, { result });
|
||||
}, 'logs-docker-maintenance'));
|
||||
|
||||
// Get logs from a file path (for native applications)
|
||||
@@ -261,8 +261,7 @@ module.exports = function({ asyncHandler, docker, logDigest, dockerMaintenance }
|
||||
timestamp: extractTimestamp(line)
|
||||
}));
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
logPath: normalizedPath,
|
||||
logs,
|
||||
count: logs.length,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const express = require('express');
|
||||
const { success } = require('../response-helpers');
|
||||
const { success } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Monitoring routes factory
|
||||
@@ -16,8 +16,22 @@ module.exports = function({ resourceMonitor, docker, asyncHandler, log, notifica
|
||||
// ===== RESOURCE MONITORING ENDPOINTS =====
|
||||
|
||||
// Get all container stats (from resource monitor module)
|
||||
// Returns a flat summary format for the System Overview widget:
|
||||
// { containerId: { cpu: <percent>, memory: <percent>, memoryUsage: <bytes>, name } }
|
||||
router.get('/monitoring/stats', asyncHandler(async (req, res) => {
|
||||
const stats = resourceMonitor.getAllStats();
|
||||
const raw = resourceMonitor.getAllStats();
|
||||
// Transform nested { current: { cpu: { percent }, memory: { percent, usage } } }
|
||||
// into flat { cpu: number, memory: number, memoryUsage: number } for the frontend widget
|
||||
const stats = {};
|
||||
for (const [id, data] of Object.entries(raw)) {
|
||||
const cur = data.current || {};
|
||||
stats[id] = {
|
||||
name: data.name,
|
||||
cpu: typeof cur.cpu === 'object' ? (cur.cpu.percent ?? 0) : (Number(cur.cpu) || 0),
|
||||
memory: typeof cur.memory === 'object' ? (cur.memory.percent ?? 0) : (Number(cur.memory) || 0),
|
||||
memoryUsage: typeof cur.memory === 'object' ? (cur.memory.usage ?? 0) : 0,
|
||||
};
|
||||
}
|
||||
success(res, { stats });
|
||||
}, 'monitoring-stats'));
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ const { validateURL, validateToken } = require('../input-validator');
|
||||
const validatorLib = require('validator');
|
||||
const { paginate, parsePaginationParams } = require('../pagination');
|
||||
const { ValidationError } = require('../errors');
|
||||
const { ok, successMessage } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Notifications route factory
|
||||
@@ -44,7 +45,7 @@ module.exports = function({ notification, asyncHandler }) {
|
||||
events: notificationConfig.events,
|
||||
healthCheck: notificationConfig.healthCheck
|
||||
};
|
||||
res.json({ success: true, config: safeConfig });
|
||||
ok(res, { config: safeConfig });
|
||||
}, 'notifications-config-get'));
|
||||
|
||||
// POST /config — Update notification configuration
|
||||
@@ -150,7 +151,7 @@ module.exports = function({ notification, asyncHandler }) {
|
||||
}
|
||||
|
||||
await notification.saveConfig();
|
||||
res.json({ success: true, message: 'Notification config updated' });
|
||||
successMessage(res, 'Notification config updated');
|
||||
}, 'notifications-config-update'));
|
||||
|
||||
// POST /test — Test notification delivery
|
||||
@@ -176,11 +177,11 @@ module.exports = function({ notification, asyncHandler }) {
|
||||
default:
|
||||
throw new ValidationError('Unknown provider');
|
||||
}
|
||||
res.json({ success: result.success, provider, error: result.error });
|
||||
ok(res, { success: result.success, provider, error: result.error });
|
||||
} else {
|
||||
// Test all enabled providers
|
||||
const result = await notification.send('test', 'Test Notification', 'This is a test notification from DashCaddy.', 'info');
|
||||
res.json({ success: true, ...result });
|
||||
ok(res, { success: true, ...result });
|
||||
}
|
||||
}, 'notifications-test'));
|
||||
|
||||
@@ -190,11 +191,10 @@ module.exports = function({ notification, asyncHandler }) {
|
||||
const paginationParams = parsePaginationParams(req.query);
|
||||
if (paginationParams) {
|
||||
const result = paginate(notificationHistory, paginationParams);
|
||||
res.json({ success: true, history: result.data, total: notificationHistory.length, pagination: result.pagination });
|
||||
ok(res, { history: result.data, total: notificationHistory.length, pagination: result.pagination });
|
||||
} else {
|
||||
const limit = parseInt(req.query.limit) || 50;
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
history: notificationHistory.slice(0, limit),
|
||||
total: notificationHistory.length
|
||||
});
|
||||
@@ -204,15 +204,14 @@ module.exports = function({ notification, asyncHandler }) {
|
||||
// DELETE /history — Clear notification history
|
||||
router.delete('/history', asyncHandler(async (req, res) => {
|
||||
notification.clearHistory();
|
||||
res.json({ success: true, message: 'Notification history cleared' });
|
||||
successMessage(res, 'Notification history cleared');
|
||||
}, 'notifications-history-clear'));
|
||||
|
||||
// POST /health-check — Manually trigger health check
|
||||
router.post('/health-check', asyncHandler(async (req, res) => {
|
||||
await notification.checkHealth();
|
||||
const notificationConfig = notification.getConfig();
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
lastCheck: notificationConfig.healthCheck.lastCheck,
|
||||
containersMonitored: Object.keys(notification.getHealthState()).length
|
||||
});
|
||||
@@ -223,8 +222,7 @@ module.exports = function({ notification, asyncHandler }) {
|
||||
const notificationConfig = notification.getConfig();
|
||||
const providers = notificationConfig.providers || {};
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
enabled: notificationConfig.enabled,
|
||||
providers: {
|
||||
discord: providers.discord?.enabled && !!providers.discord?.webhookUrl,
|
||||
@@ -252,7 +250,7 @@ module.exports = function({ notification, asyncHandler }) {
|
||||
// Use 'test' as the event for manual sends
|
||||
const result = await notification.send(event, data || {}, type || 'info');
|
||||
|
||||
res.json({
|
||||
ok(res, {
|
||||
success: result.success,
|
||||
event,
|
||||
results: result.results
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const express = require('express');
|
||||
const http = require('http');
|
||||
const { ok, errorResponse, notFound, conflict } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* OpenClaw management routes
|
||||
@@ -93,8 +94,8 @@ module.exports = function openClawRoutes(ctx) {
|
||||
proxyRes.on('data', function(d) { res.write(d); });
|
||||
proxyRes.on('end', function() { res.end(); });
|
||||
});
|
||||
proxyReq.on('error', function(e) { res.status(502).json({ success: false, error: e.message }); });
|
||||
proxyReq.setTimeout(15000, function() { proxyReq.destroy(); res.status(504).json({ success: false, error: 'gateway timeout' }); });
|
||||
proxyReq.on('error', function(e) { errorResponse(res, 502, e.message); });
|
||||
proxyReq.setTimeout(15000, function() { proxyReq.destroy(); errorResponse(res, 504, 'gateway timeout'); });
|
||||
proxyReq.write(body);
|
||||
proxyReq.end();
|
||||
} else {
|
||||
@@ -104,8 +105,8 @@ module.exports = function openClawRoutes(ctx) {
|
||||
proxyRes.on('data', function(d) { res.write(d); });
|
||||
proxyRes.on('end', function() { res.end(); });
|
||||
});
|
||||
proxyReq.on('error', function(e) { res.status(502).json({ success: false, error: e.message }); });
|
||||
proxyReq.setTimeout(15000, function() { proxyReq.destroy(); res.status(504).json({ success: false, error: 'gateway timeout' }); });
|
||||
proxyReq.on('error', function(e) { errorResponse(res, 502, e.message); });
|
||||
proxyReq.setTimeout(15000, function() { proxyReq.destroy(); errorResponse(res, 504, 'gateway timeout'); });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,7 +116,7 @@ module.exports = function openClawRoutes(ctx) {
|
||||
const container = await findOpenClawContainer();
|
||||
|
||||
if (!container) {
|
||||
return res.json({ success: true, deployed: false });
|
||||
return ok(res, { deployed: false });
|
||||
}
|
||||
|
||||
const token = await getGatewayToken(container.Id);
|
||||
@@ -123,8 +124,7 @@ module.exports = function openClawRoutes(ctx) {
|
||||
const baseUrl = 'http://localhost:' + port;
|
||||
const health = await gatewayHealth(baseUrl, token);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
deployed: true,
|
||||
container: {
|
||||
id: container.Id.slice(0, 12),
|
||||
@@ -149,7 +149,7 @@ module.exports = function openClawRoutes(ctx) {
|
||||
router.post('/deploy', asyncHandler(async function(req, res) {
|
||||
const existing = await findOpenClawContainer();
|
||||
if (existing) {
|
||||
return res.status(409).json({ success: false, error: 'OpenClaw is already deployed' });
|
||||
return conflict(res, 'OpenClaw is already deployed');
|
||||
}
|
||||
|
||||
const image = 'ghcr.io/nousresearch/openclaw:latest';
|
||||
@@ -170,7 +170,7 @@ module.exports = function openClawRoutes(ctx) {
|
||||
});
|
||||
} catch(e) {
|
||||
log.error('OpenClaw pull failed: ' + e.message);
|
||||
return res.status(500).json({ success: false, error: 'Failed to pull image: ' + e.message });
|
||||
return errorResponse(res, 500, 'Failed to pull image: ' + e.message);
|
||||
}
|
||||
|
||||
// Create + start container
|
||||
@@ -196,8 +196,7 @@ module.exports = function openClawRoutes(ctx) {
|
||||
await container.start();
|
||||
log.info('OpenClaw deployed: ' + container.id.slice(0, 12));
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
deployed: true,
|
||||
container: { id: container.id.slice(0, 12), name: name },
|
||||
gateway: {
|
||||
@@ -207,7 +206,7 @@ module.exports = function openClawRoutes(ctx) {
|
||||
});
|
||||
} catch(e) {
|
||||
log.error('OpenClaw deploy failed: ' + e.message);
|
||||
res.status(500).json({ success: false, error: 'Deploy failed: ' + e.message });
|
||||
errorResponse(res, 500, 'Deploy failed: ' + e.message);
|
||||
}
|
||||
}));
|
||||
|
||||
@@ -215,7 +214,7 @@ module.exports = function openClawRoutes(ctx) {
|
||||
|
||||
router.get('/proxy/*', asyncHandler(async function(req, res) {
|
||||
const container = await findOpenClawContainer();
|
||||
if (!container) return res.status(404).json({ success: false, error: 'OpenClaw not deployed' });
|
||||
if (!container) return notFound(res, 'OpenClaw not deployed');
|
||||
|
||||
const token = await getGatewayToken(container.Id);
|
||||
const port = await getContainerPort(container.Id);
|
||||
@@ -229,7 +228,7 @@ module.exports = function openClawRoutes(ctx) {
|
||||
|
||||
router.post('/proxy/*', asyncHandler(async function(req, res) {
|
||||
const container = await findOpenClawContainer();
|
||||
if (!container) return res.status(404).json({ success: false, error: 'OpenClaw not deployed' });
|
||||
if (!container) return notFound(res, 'OpenClaw not deployed');
|
||||
|
||||
const token = await getGatewayToken(container.Id);
|
||||
const port = await getContainerPort(container.Id);
|
||||
@@ -243,17 +242,17 @@ module.exports = function openClawRoutes(ctx) {
|
||||
|
||||
router.delete('/', asyncHandler(async function(req, res) {
|
||||
const container = await findOpenClawContainer();
|
||||
if (!container) return res.status(404).json({ success: false, error: 'OpenClaw not deployed' });
|
||||
if (!container) return notFound(res, 'OpenClaw not deployed');
|
||||
|
||||
try {
|
||||
const c = docker.client.container(container.Id);
|
||||
await c.stop().catch(function() {});
|
||||
await c.remove({ force: true });
|
||||
log.info('OpenClaw container ' + container.Id.slice(0, 12) + ' removed');
|
||||
res.json({ success: true, message: 'OpenClaw removed' });
|
||||
ok(res, { message: 'OpenClaw removed' });
|
||||
} catch(e) {
|
||||
log.error('Failed to remove OpenClaw: ' + e.message);
|
||||
res.status(500).json({ success: false, error: e.message });
|
||||
errorResponse(res, 500, e.message);
|
||||
}
|
||||
}));
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ const express = require('express');
|
||||
const { ValidationError } = require('../../errors');
|
||||
const crypto = require('crypto');
|
||||
const { DOCKER } = require('../../constants');
|
||||
const { ok } = require('../../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Recipes deployment routes factory
|
||||
@@ -146,7 +147,7 @@ module.exports = function({ docker, credentialManager: _credentialManager, servi
|
||||
'success'
|
||||
);
|
||||
|
||||
res.json(response);
|
||||
ok(res, response);
|
||||
} catch (error) {
|
||||
log.error('recipe', 'Recipe deployment failed', { recipeId, error: error.message });
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ const express = require('express');
|
||||
const deployRoutes = require('./deploy');
|
||||
const manageRoutes = require('./manage');
|
||||
const { NotFoundError } = require('../../errors');
|
||||
const { ok } = require('../../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Recipes routes aggregator
|
||||
@@ -55,7 +56,7 @@ module.exports = function(ctx) {
|
||||
setupInstructions: recipe.setupInstructions
|
||||
}));
|
||||
|
||||
res.json({ success: true, templates, categories: RECIPE_CATEGORIES });
|
||||
ok(res, { templates, categories: RECIPE_CATEGORIES });
|
||||
}, 'recipe-templates'));
|
||||
|
||||
// GET /api/recipes/templates/:recipeId — get single recipe template detail
|
||||
@@ -64,7 +65,7 @@ module.exports = function(ctx) {
|
||||
const recipe = RECIPE_TEMPLATES[req.params.recipeId];
|
||||
if (!recipe) throw new NotFoundError(`Recipe template ${req.params.recipeId}`);
|
||||
|
||||
res.json({ success: true, recipe: { id: req.params.recipeId, ...recipe } });
|
||||
ok(res, { recipe: { id: req.params.recipeId, ...recipe } });
|
||||
}, 'recipe-template-detail'));
|
||||
|
||||
// Mount deploy and manage sub-routes — pass full ctx for sub-routes that reference ctx.*
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const express = require('express');
|
||||
const { DOCKER } = require('../../constants');
|
||||
const { NotFoundError } = require('../../errors');
|
||||
const { ok } = require('../../src/utils/responses');
|
||||
|
||||
module.exports = function({ servicesStateManager, asyncHandler, log, docker, notification, buildDomain, caddy }) {
|
||||
const router = express.Router();
|
||||
@@ -98,7 +99,7 @@ module.exports = function({ servicesStateManager, asyncHandler, log, docker, not
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ success: true, recipes: Object.values(recipeGroups) });
|
||||
ok(res, { recipes: Object.values(recipeGroups) });
|
||||
}, 'recipe-deployed'));
|
||||
|
||||
/**
|
||||
@@ -129,7 +130,7 @@ module.exports = function({ servicesStateManager, asyncHandler, log, docker, not
|
||||
}
|
||||
|
||||
log.info('recipe', 'Recipe started', { recipeId, results });
|
||||
res.json({ success: true, recipeId, results });
|
||||
ok(res, { recipeId, results });
|
||||
}, 'recipe-start'));
|
||||
|
||||
/**
|
||||
@@ -161,7 +162,7 @@ module.exports = function({ servicesStateManager, asyncHandler, log, docker, not
|
||||
}
|
||||
|
||||
log.info('recipe', 'Recipe stopped', { recipeId, results });
|
||||
res.json({ success: true, recipeId, results });
|
||||
ok(res, { recipeId, results });
|
||||
}, 'recipe-stop'));
|
||||
|
||||
/**
|
||||
@@ -187,7 +188,7 @@ module.exports = function({ servicesStateManager, asyncHandler, log, docker, not
|
||||
}
|
||||
|
||||
log.info('recipe', 'Recipe restarted', { recipeId, results });
|
||||
res.json({ success: true, recipeId, results });
|
||||
ok(res, { recipeId, results });
|
||||
}, 'recipe-restart'));
|
||||
|
||||
/**
|
||||
@@ -259,7 +260,7 @@ module.exports = function({ servicesStateManager, asyncHandler, log, docker, not
|
||||
);
|
||||
|
||||
log.info('recipe', 'Recipe removed', { recipeId, results });
|
||||
res.json({ success: true, recipeId, results });
|
||||
ok(res, { recipeId, results });
|
||||
}, 'recipe-remove'));
|
||||
|
||||
// === Helper functions ===
|
||||
|
||||
@@ -10,7 +10,8 @@ const { exists } = require('../fs-helpers');
|
||||
const { paginate, parsePaginationParams } = require('../pagination');
|
||||
const { ValidationError, NotFoundError, ConflictError } = require('../errors');
|
||||
const { resolveServiceUrl } = require('../url-resolver');
|
||||
const { success, error: errorResponse } = require('../response-helpers');
|
||||
const { success, error: errorResponse } = require('../src/utils/responses');
|
||||
const platformPaths = require('../platform-paths');
|
||||
|
||||
/**
|
||||
* Services route factory
|
||||
@@ -46,7 +47,7 @@ module.exports = function({
|
||||
dns
|
||||
}) {
|
||||
const router = express.Router();
|
||||
const CA_CERT_PATH = process.env.CA_CERT_PATH || '/app/pki/root.crt';
|
||||
const CA_CERT_PATH = process.env.CA_CERT_PATH || platformPaths.pkiRootCert;
|
||||
const PROBE_CONCURRENCY = 6;
|
||||
let probeHttpsAgent;
|
||||
|
||||
@@ -355,9 +356,11 @@ module.exports = function({
|
||||
}, 'services-status'));
|
||||
|
||||
// List all services
|
||||
// Always returns the standard envelope. The `services` field is the array
|
||||
// (paginated if ?page=N&limit=M is in the query, otherwise the full list).
|
||||
router.get('/services', asyncHandler(async (req, res) => {
|
||||
if (!await exists(SERVICES_FILE)) {
|
||||
return res.json([]);
|
||||
return success(res, { services: [] });
|
||||
}
|
||||
const services = await servicesStateManager.read();
|
||||
const paginationParams = parsePaginationParams(req.query);
|
||||
@@ -365,7 +368,7 @@ module.exports = function({
|
||||
if (paginationParams) {
|
||||
success(res, { services: result.data, pagination: result.pagination });
|
||||
} else {
|
||||
res.json(result.data);
|
||||
success(res, { services: result.data });
|
||||
}
|
||||
}, 'services-list'));
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ const fs = require('fs');
|
||||
const { CADDY, REGEX, LIMITS } = require('../constants');
|
||||
const { ValidationError, ConflictError, NotFoundError } = require('../errors');
|
||||
const { validateURL } = require('../input-validator');
|
||||
const { ok, successMessage } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Sites route factory
|
||||
@@ -23,14 +24,14 @@ module.exports = function({ asyncHandler, caddy, dns, fetchT, buildDomain, addSe
|
||||
// Get Caddyfile contents
|
||||
router.get('/caddyfile', asyncHandler(async (req, res) => {
|
||||
const content = await caddy.read();
|
||||
res.json({ success: true, content });
|
||||
ok(res, { content });
|
||||
}, 'caddyfile-get'));
|
||||
|
||||
// Get current Caddy config (from admin API)
|
||||
router.get('/caddy/config', asyncHandler(async (req, res) => {
|
||||
const response = await fetchT(`${caddy.adminUrl}/config/`);
|
||||
const config = await response.json();
|
||||
res.json({ success: true, config });
|
||||
ok(res, { config });
|
||||
}, 'caddy-config'));
|
||||
|
||||
// Reload Caddy configuration via admin API
|
||||
@@ -49,7 +50,7 @@ module.exports = function({ asyncHandler, caddy, dns, fetchT, buildDomain, addSe
|
||||
throw new Error('Caddy reload failed. Check server logs for details.');
|
||||
}
|
||||
|
||||
res.json({ success: true, message: 'Caddy configuration reloaded successfully' });
|
||||
successMessage(res, 'Caddy configuration reloaded successfully');
|
||||
}, 'caddy-reload'));
|
||||
|
||||
// Get Certificate Authorities from Caddyfile
|
||||
@@ -127,7 +128,7 @@ module.exports = function({ asyncHandler, caddy, dns, fetchT, buildDomain, addSe
|
||||
name: ca.name,
|
||||
displayName: ca.name !== (ca.id || ca.name) ? `${ca.name} (${ca.id || ca.name})` : ca.name
|
||||
}));
|
||||
res.json({ status: 'success', data: { cas: caList } });
|
||||
ok(res, { cas: caList });
|
||||
}, 'caddy-get-cas'));
|
||||
|
||||
// Remove a site from Caddyfile
|
||||
@@ -152,7 +153,7 @@ module.exports = function({ asyncHandler, caddy, dns, fetchT, buildDomain, addSe
|
||||
throw new NotFoundError(`Site block for "" in Caddyfile`);
|
||||
}
|
||||
|
||||
res.json({ success: true, message: `Site "${domain}" removed from Caddyfile and Caddy reloaded` });
|
||||
successMessage(res, `Site "${domain}" removed from Caddyfile and Caddy reloaded`);
|
||||
}, 'site-delete'));
|
||||
|
||||
// Add a new site to Caddyfile and reload
|
||||
@@ -180,7 +181,7 @@ module.exports = function({ asyncHandler, caddy, dns, fetchT, buildDomain, addSe
|
||||
result.rolledBack ? { note: 'Caddyfile was rolled back to previous state' } : {});
|
||||
}
|
||||
|
||||
res.json({ success: true, message: `Site "${domain}" added to Caddyfile and Caddy reloaded successfully` });
|
||||
successMessage(res, `Site "${domain}" added to Caddyfile and Caddy reloaded successfully`);
|
||||
}, 'site-add'));
|
||||
|
||||
// Add external service reverse proxy to Caddyfile
|
||||
@@ -260,12 +261,11 @@ module.exports = function({ asyncHandler, caddy, dns, fetchT, buildDomain, addSe
|
||||
}
|
||||
}
|
||||
|
||||
const response = {
|
||||
success: true,
|
||||
const responseData = {
|
||||
message: `External service proxy for ${domain} -> ${externalUrl} created${shouldReload ? ' and Caddy reloaded' : ''}`
|
||||
};
|
||||
if (dnsWarning) response.warning = dnsWarning;
|
||||
res.json(response);
|
||||
if (dnsWarning) responseData.warning = dnsWarning;
|
||||
ok(res, responseData);
|
||||
}, 'site-external'));
|
||||
|
||||
return router;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const { success, error: errorResponse, notFound } = require('../response-helpers');
|
||||
const { success, error: errorResponse, notFound } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* SSL Monitor route factory
|
||||
|
||||
@@ -3,6 +3,7 @@ const fs = require('fs');
|
||||
const { TAILSCALE } = require('../constants');
|
||||
const { exists } = require('../fs-helpers');
|
||||
const { ValidationError, NotFoundError } = require('../errors');
|
||||
const { ok, successMessage, unauthorized } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Tailscale route factory
|
||||
@@ -35,8 +36,7 @@ module.exports = function({
|
||||
const localIP = await tailscale.getLocalIP();
|
||||
|
||||
if (!status) {
|
||||
return res.json({
|
||||
success: true,
|
||||
return ok(res, {
|
||||
installed: false,
|
||||
connected: false,
|
||||
message: 'Tailscale not available or not running'
|
||||
@@ -58,8 +58,7 @@ module.exports = function({
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
installed: true,
|
||||
connected: status.BackendState === 'Running',
|
||||
backendState: status.BackendState,
|
||||
@@ -85,8 +84,7 @@ module.exports = function({
|
||||
|
||||
await tailscale.save();
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
message: 'Tailscale configuration updated',
|
||||
config: tailscale.config
|
||||
});
|
||||
@@ -101,8 +99,7 @@ module.exports = function({
|
||||
const ipsToCheck = [clientIP, forwardedFor, realIP].filter(Boolean);
|
||||
const isTailscale = ipsToCheck.some(ip => tailscale.isTailscaleIP(ip.toString().split(',')[0].trim()));
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
isTailscale,
|
||||
clientIP,
|
||||
forwardedFor: forwardedFor || null,
|
||||
@@ -114,7 +111,7 @@ module.exports = function({
|
||||
router.get('/devices', asyncHandler(async (req, res) => {
|
||||
const status = await tailscale.getStatus();
|
||||
if (!status || !status.Peer) {
|
||||
return res.json({ success: true, devices: [] });
|
||||
return ok(res, { devices: [] });
|
||||
}
|
||||
|
||||
const devices = [];
|
||||
@@ -141,7 +138,7 @@ module.exports = function({
|
||||
});
|
||||
}
|
||||
|
||||
res.json({ success: true, devices });
|
||||
ok(res, { devices });
|
||||
}, 'tailscale-devices'));
|
||||
|
||||
// Toggle Tailscale-only mode for an existing service
|
||||
@@ -190,8 +187,7 @@ module.exports = function({
|
||||
});
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
message: `Service ${domain} is now ${tailscaleOnly !== false ? 'protected by' : 'no longer restricted to'} Tailscale`,
|
||||
tailscaleOnly: tailscaleOnly !== false
|
||||
});
|
||||
@@ -254,7 +250,7 @@ module.exports = function({
|
||||
log.warn('tailscale', 'Initial sync after OAuth config failed', { error: e.message });
|
||||
}
|
||||
|
||||
res.json({ success: true, config: tailscale.config });
|
||||
ok(res, { config: tailscale.config });
|
||||
}, 'tailscale-oauth-config'));
|
||||
|
||||
// Remove OAuth credentials and disable API sync
|
||||
@@ -269,7 +265,7 @@ module.exports = function({
|
||||
|
||||
tailscale.stopSync();
|
||||
|
||||
res.json({ success: true, message: 'Tailscale OAuth credentials removed' });
|
||||
successMessage(res, 'Tailscale OAuth credentials removed');
|
||||
}, 'tailscale-oauth-delete'));
|
||||
|
||||
// Get enriched device list from Tailscale API
|
||||
@@ -279,8 +275,7 @@ module.exports = function({
|
||||
}
|
||||
|
||||
// Return cached devices from last sync
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
devices: tailscale.config.devices || [],
|
||||
lastSync: tailscale.config.lastSync
|
||||
});
|
||||
@@ -294,8 +289,7 @@ module.exports = function({
|
||||
|
||||
const devices = await tailscale.syncAPI();
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
devices: devices || [],
|
||||
lastSync: tailscale.config.lastSync
|
||||
});
|
||||
@@ -325,7 +319,7 @@ module.exports = function({
|
||||
sshRuleCount: (acl.ssh || []).length
|
||||
};
|
||||
|
||||
res.json({ success: true, acl, summary });
|
||||
ok(res, { acl, summary });
|
||||
}, 'tailscale-acl'));
|
||||
|
||||
return router;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
const express = require('express');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { success } = require('../response-helpers');
|
||||
const { success } = require('../src/utils/responses');
|
||||
const { ValidationError, NotFoundError } = require('../errors');
|
||||
const platformPaths = require('../platform-paths');
|
||||
|
||||
/**
|
||||
* Themes routes factory
|
||||
@@ -13,7 +14,7 @@ const { ValidationError, NotFoundError } = require('../errors');
|
||||
*/
|
||||
module.exports = function({ asyncHandler, log }) {
|
||||
const router = express.Router();
|
||||
const THEMES_DIR = process.env.THEMES_DIR || path.join(path.dirname(process.env.SERVICES_FILE || '/app/services.json'), 'themes');
|
||||
const THEMES_DIR = process.env.THEMES_DIR || path.join(path.dirname(platformPaths.servicesFile), 'themes');
|
||||
|
||||
// Ensure themes directory exists
|
||||
if (!fs.existsSync(THEMES_DIR)) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const express = require('express');
|
||||
const { paginate, parsePaginationParams } = require('../pagination');
|
||||
const { ValidationError } = require('../errors');
|
||||
const { ok, successMessage } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Updates route factory
|
||||
@@ -20,7 +21,7 @@ module.exports = function({ updateManager, selfUpdater, asyncHandler, logError }
|
||||
router.post('/updates/check', asyncHandler(async (req, res) => {
|
||||
await updateManager.checkForUpdates();
|
||||
const updates = updateManager.getAvailableUpdates();
|
||||
res.json({ success: true, updates, count: updates.length });
|
||||
ok(res, { updates, count: updates.length });
|
||||
}, 'updates-check'));
|
||||
|
||||
// Get available updates
|
||||
@@ -28,19 +29,19 @@ module.exports = function({ updateManager, selfUpdater, asyncHandler, logError }
|
||||
const updates = updateManager.getAvailableUpdates();
|
||||
const paginationParams = parsePaginationParams(req.query);
|
||||
const result = paginate(updates, paginationParams);
|
||||
res.json({ success: true, updates: result.data, count: updates.length, ...(result.pagination && { pagination: result.pagination }) });
|
||||
ok(res, { updates: result.data, count: updates.length, ...(result.pagination && { pagination: result.pagination }) });
|
||||
}, 'updates-available'));
|
||||
|
||||
// Update a container
|
||||
router.post('/updates/update/:containerId', asyncHandler(async (req, res) => {
|
||||
const result = await updateManager.updateContainer(req.params.containerId, req.body);
|
||||
res.json({ success: true, result });
|
||||
ok(res, { result });
|
||||
}, 'updates-update'));
|
||||
|
||||
// Rollback update
|
||||
router.post('/updates/rollback/:containerId', asyncHandler(async (req, res) => {
|
||||
await updateManager.rollbackUpdate(req.params.containerId);
|
||||
res.json({ success: true, message: 'Rollback completed' });
|
||||
successMessage(res, 'Rollback completed');
|
||||
}, 'updates-rollback'));
|
||||
|
||||
// Get update history
|
||||
@@ -50,19 +51,19 @@ module.exports = function({ updateManager, selfUpdater, asyncHandler, logError }
|
||||
const fetchLimit = paginationParams ? Number.MAX_SAFE_INTEGER : (parseInt(req.query.limit) || 50);
|
||||
const history = updateManager.getHistory(fetchLimit);
|
||||
const result = paginate(history, paginationParams);
|
||||
res.json({ success: true, history: result.data, ...(result.pagination && { pagination: result.pagination }) });
|
||||
ok(res, { history: result.data, ...(result.pagination && { pagination: result.pagination }) });
|
||||
}, 'updates-history'));
|
||||
|
||||
// Configure auto-update
|
||||
router.post('/updates/auto-update/:containerId', asyncHandler(async (req, res) => {
|
||||
updateManager.configureAutoUpdate(req.params.containerId, req.body);
|
||||
res.json({ success: true, message: 'Auto-update configured' });
|
||||
successMessage(res, 'Auto-update configured');
|
||||
}, 'updates-auto-update'));
|
||||
|
||||
// Get auto-update configuration
|
||||
router.get('/updates/auto-update', asyncHandler(async (req, res) => {
|
||||
const config = updateManager.getAutoUpdateConfig();
|
||||
res.json({ success: true, config });
|
||||
ok(res, { config });
|
||||
}, 'updates-auto-update-config'));
|
||||
|
||||
// Schedule update
|
||||
@@ -72,7 +73,7 @@ module.exports = function({ updateManager, selfUpdater, asyncHandler, logError }
|
||||
throw new ValidationError('scheduledTime is required');
|
||||
}
|
||||
updateManager.scheduleUpdate(req.params.containerId, scheduledTime);
|
||||
res.json({ success: true, message: 'Update scheduled', scheduledTime });
|
||||
ok(res, { message: 'Update scheduled', scheduledTime });
|
||||
}, 'updates-schedule'));
|
||||
|
||||
// ===== DASHCADDY SELF-UPDATE ENDPOINTS =====
|
||||
@@ -80,20 +81,20 @@ module.exports = function({ updateManager, selfUpdater, asyncHandler, logError }
|
||||
// Get current version
|
||||
router.get('/system/version', asyncHandler(async (req, res) => {
|
||||
const local = selfUpdater.getLocalVersion();
|
||||
res.json({ success: true, name: 'DashCaddy', version: local.version, commit: local.commit });
|
||||
ok(res, { name: 'DashCaddy', version: local.version, commit: local.commit });
|
||||
}, 'system-version'));
|
||||
|
||||
// Check for DashCaddy update
|
||||
router.get('/system/update-check', asyncHandler(async (req, res) => {
|
||||
const result = await selfUpdater.checkForUpdate();
|
||||
res.json({ success: true, ...result });
|
||||
ok(res, result);
|
||||
}, 'system-update-check'));
|
||||
|
||||
// Apply available update
|
||||
router.post('/system/update-apply', asyncHandler(async (req, res) => {
|
||||
const check = await selfUpdater.checkForUpdate();
|
||||
if (!check.available) {
|
||||
return res.json({ success: true, message: 'Already up to date' });
|
||||
return successMessage(res, 'Already up to date');
|
||||
}
|
||||
// Refuse same-version applies. The check.available flag can theoretically be
|
||||
// true with equal versions (commit-mismatch path); applying anyway just
|
||||
@@ -102,14 +103,13 @@ module.exports = function({ updateManager, selfUpdater, asyncHandler, logError }
|
||||
const localV = check.local && check.local.version;
|
||||
const remoteV = check.remote && check.remote.version;
|
||||
if (localV && remoteV && localV === remoteV) {
|
||||
return res.json({ success: true, message: 'Already up to date', version: localV });
|
||||
return ok(res, { message: 'Already up to date', version: localV });
|
||||
}
|
||||
// Start async — container may restart
|
||||
selfUpdater.applyUpdate(check.remote).catch(err => {
|
||||
logError('self-update', err);
|
||||
});
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
message: 'Update initiated',
|
||||
fromVersion: localV,
|
||||
toVersion: remoteV,
|
||||
@@ -132,16 +132,15 @@ module.exports = function({ updateManager, selfUpdater, asyncHandler, logError }
|
||||
presentedBuf.length > 0 &&
|
||||
require('crypto').timingSafeEqual(presentedBuf, expectedBuf);
|
||||
if (!ok) {
|
||||
return res.status(401).json({ success: false, error: 'Invalid notify secret' });
|
||||
return unauthorized(res, 'Invalid notify secret');
|
||||
}
|
||||
const result = selfUpdater.notifyAndApply('http-notify');
|
||||
res.json({ success: true, ...result });
|
||||
ok(res, result);
|
||||
}, 'system-update-notify'));
|
||||
|
||||
// Get update status
|
||||
router.get('/system/update-status', asyncHandler(async (req, res) => {
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
status: selfUpdater.getStatus(),
|
||||
lastCheck: selfUpdater.lastCheckTime,
|
||||
lastResult: selfUpdater.lastCheckResult,
|
||||
@@ -151,13 +150,13 @@ module.exports = function({ updateManager, selfUpdater, asyncHandler, logError }
|
||||
// Get self-update history
|
||||
router.get('/system/update-history', asyncHandler(async (req, res) => {
|
||||
const history = selfUpdater.getUpdateHistory();
|
||||
res.json({ success: true, history });
|
||||
ok(res, { history });
|
||||
}, 'system-update-history'));
|
||||
|
||||
// List rollback versions
|
||||
router.get('/system/rollback-versions', asyncHandler(async (req, res) => {
|
||||
const versions = selfUpdater.getAvailableRollbacks();
|
||||
res.json({ success: true, versions });
|
||||
ok(res, { versions });
|
||||
}, 'system-rollback-versions'));
|
||||
|
||||
// Rollback to a previous version
|
||||
@@ -167,7 +166,7 @@ module.exports = function({ updateManager, selfUpdater, asyncHandler, logError }
|
||||
selfUpdater.rollbackToVersion(version).catch(err => {
|
||||
logError('self-rollback', err);
|
||||
});
|
||||
res.json({ success: true, message: `Rollback to ${version} initiated` });
|
||||
ok(res, { message: `Rollback to ${version} initiated` });
|
||||
}, 'system-rollback'));
|
||||
|
||||
return router;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const express = require('express');
|
||||
const { ok } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Workflows routes factory
|
||||
@@ -19,21 +20,21 @@ module.exports = function({ workflowEngine, licenseManager, asyncHandler }) {
|
||||
// List all bundled workflows
|
||||
router.get('/workflows', asyncHandler(async (req, res) => {
|
||||
const workflows = workflowEngine.listWorkflows();
|
||||
res.json({ success: true, workflows });
|
||||
ok(res, { workflows });
|
||||
}, 'workflows-list'));
|
||||
|
||||
// Enable a workflow
|
||||
router.post('/workflows/:workflowId/enable', asyncHandler(async (req, res) => {
|
||||
const { workflowId } = req.params;
|
||||
const result = workflowEngine.setWorkflowEnabled(workflowId, true);
|
||||
res.json({ success: true, ...result });
|
||||
ok(res, result);
|
||||
}, 'workflows-enable'));
|
||||
|
||||
// Disable a workflow
|
||||
router.post('/workflows/:workflowId/disable', asyncHandler(async (req, res) => {
|
||||
const { workflowId } = req.params;
|
||||
const result = workflowEngine.setWorkflowEnabled(workflowId, false);
|
||||
res.json({ success: true, ...result });
|
||||
ok(res, result);
|
||||
}, 'workflows-disable'));
|
||||
|
||||
// Manually trigger a workflow
|
||||
@@ -43,7 +44,7 @@ module.exports = function({ workflowEngine, licenseManager, asyncHandler }) {
|
||||
triggerData.trigger = 'manual';
|
||||
|
||||
const result = await workflowEngine.executeWorkflow(workflowId, triggerData);
|
||||
res.json({ success: true, result });
|
||||
ok(res, { result });
|
||||
}, 'workflows-run'));
|
||||
|
||||
// Get execution history for a workflow
|
||||
@@ -51,14 +52,14 @@ module.exports = function({ workflowEngine, licenseManager, asyncHandler }) {
|
||||
const { workflowId } = req.params;
|
||||
const limit = parseInt(req.query.limit) || 50;
|
||||
const history = workflowEngine.getHistory(workflowId, limit);
|
||||
res.json({ success: true, history });
|
||||
ok(res, { history });
|
||||
}, 'workflows-history'));
|
||||
|
||||
// Get all workflow execution history
|
||||
router.get('/workflows/history', asyncHandler(async (req, res) => {
|
||||
const limit = parseInt(req.query.limit) || 100;
|
||||
const history = workflowEngine.getHistory(null, limit);
|
||||
res.json({ success: true, history });
|
||||
ok(res, { history });
|
||||
}, 'workflows-all-history'));
|
||||
|
||||
return router;
|
||||
|
||||
@@ -21,17 +21,17 @@ const isWindows = platformPaths.isWindows;
|
||||
|
||||
const DEFAULTS = {
|
||||
CHECK_INTERVAL: 30 * 60 * 1000, // 30 minutes
|
||||
UPDATE_URL: 'https://get.dashcaddy.net/release',
|
||||
MIRROR_URL: 'https://get2.dashcaddy.net/release',
|
||||
UPDATES_DIR: platformPaths.isWindows ? path.join(platformPaths.caddyBase, 'updates') : '/app/updates',
|
||||
UPDATE_URL: process.env.DASHCADDY_UPDATE_URL || 'https://get.dashcaddy.net/release',
|
||||
MIRROR_URL: process.env.DASHCADDY_MIRROR_URL || 'https://get2.dashcaddy.net/release',
|
||||
UPDATES_DIR: platformPaths.containerUpdatesDir,
|
||||
// API_SOURCE_DIR is the HOST path — written to trigger.json for the host-side updater
|
||||
API_SOURCE_DIR: path.join(platformPaths.caddySites, 'dashcaddy-api'),
|
||||
// FRONTEND_DIR is the container path — dashboard is volume-mounted at /app/dashboard
|
||||
FRONTEND_DIR: platformPaths.isWindows ? path.join(platformPaths.caddySites, 'status') : '/app/dashboard',
|
||||
FRONTEND_DIR: platformPaths.containerFrontendDir,
|
||||
MAX_BACKUPS: 3,
|
||||
HEALTH_TIMEOUT: 60000,
|
||||
DOWNLOAD_TIMEOUT: 120000,
|
||||
CHANNEL: 'stable',
|
||||
CHANNEL: process.env.DASHCADDY_UPDATE_CHANNEL || 'stable',
|
||||
INSTANCE_ID_FILE: platformPaths.isWindows
|
||||
? path.join(platformPaths.caddyBase, 'instance-id')
|
||||
: '/etc/dashcaddy/instance-id',
|
||||
|
||||
@@ -25,7 +25,8 @@ process.on('uncaughtException', (error) => {
|
||||
// Load license
|
||||
await licenseManager.load();
|
||||
|
||||
const PORT = process.env.PORT || 3001;
|
||||
const PORT = parseInt(process.env.PORT, 10) || 3001;
|
||||
const HOST = process.env.HOST || '0.0.0.0';
|
||||
const CADDYFILE_PATH = process.env.CADDYFILE_PATH || platformPaths.caddyfile;
|
||||
const CADDY_ADMIN_URL = process.env.CADDY_ADMIN_URL || platformPaths.caddyAdminUrl;
|
||||
const SERVICES_FILE = process.env.SERVICES_FILE || platformPaths.servicesFile;
|
||||
@@ -43,9 +44,10 @@ process.on('uncaughtException', (error) => {
|
||||
});
|
||||
|
||||
// Start HTTP server
|
||||
const server = app.listen(PORT, '0.0.0.0', () => {
|
||||
const server = app.listen(PORT, HOST, () => {
|
||||
log.info('server', 'DashCaddy API server started', {
|
||||
port: PORT,
|
||||
host: HOST,
|
||||
caddyfile: CADDYFILE_PATH,
|
||||
caddyAdmin: CADDY_ADMIN_URL,
|
||||
services: SERVICES_FILE,
|
||||
|
||||
+122
-6
@@ -16,6 +16,7 @@ const { asyncHandler } = require('./utils/async-handler');
|
||||
|
||||
// Managers and utilities
|
||||
const StateManager = require('../state-manager');
|
||||
const platformPaths = require('../platform-paths');
|
||||
const { LicenseManager } = require('../license-manager');
|
||||
const credentialManager = require('../credential-manager');
|
||||
const authManager = require('../auth-manager');
|
||||
@@ -96,6 +97,19 @@ const { APP } = require('../constants');
|
||||
async function createApp() {
|
||||
const app = express();
|
||||
|
||||
// Global request timeout (default 5 minutes — covers slow Docker pulls)
|
||||
// Routes that need longer can override per-request with req.setTimeout()
|
||||
const REQUEST_TIMEOUT_MS = parseInt(process.env.REQUEST_TIMEOUT_MS, 10) || 5 * 60 * 1000;
|
||||
app.use((req, res, next) => {
|
||||
req.setTimeout(REQUEST_TIMEOUT_MS);
|
||||
res.setTimeout(REQUEST_TIMEOUT_MS);
|
||||
next();
|
||||
});
|
||||
// Disable x-powered-by header for security (don't advertise framework)
|
||||
app.disable('x-powered-by');
|
||||
// Trust first proxy (Caddy/nginx in front of us) so req.ip works correctly
|
||||
app.set('trust proxy', 1);
|
||||
|
||||
// Initialize logging
|
||||
const log = createLogger(config.LOG_LEVEL);
|
||||
|
||||
@@ -111,7 +125,7 @@ async function createApp() {
|
||||
licenseManager.loadSecret(config.LICENSE_SECRET_FILE);
|
||||
|
||||
// HTTPS agent for internal CA
|
||||
const CA_CERT_PATH = process.env.CA_CERT_PATH || '/app/pki/root.crt';
|
||||
const CA_CERT_PATH = process.env.CA_CERT_PATH || platformPaths.pkiRootCert;
|
||||
let httpsAgent;
|
||||
try {
|
||||
const caCert = fs.readFileSync(CA_CERT_PATH);
|
||||
@@ -380,6 +394,28 @@ async function createApp() {
|
||||
// Build versioned API router
|
||||
const apiRouter = express.Router();
|
||||
|
||||
// Version endpoint — public, no auth required
|
||||
// Reads version from package.json at startup so the response always matches the running code
|
||||
let appVersion = '0.0.0';
|
||||
let appName = 'dashcaddy-api';
|
||||
try {
|
||||
const pkg = require('../package.json');
|
||||
appVersion = pkg.version || appVersion;
|
||||
appName = pkg.name || appName;
|
||||
} catch { /* package.json unreadable — keep fallback */ }
|
||||
apiRouter.get('/version', (req, res) => {
|
||||
ok(res, {
|
||||
name: appName,
|
||||
version: appVersion,
|
||||
node: process.version,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
uptime: process.uptime(),
|
||||
instanceId: process.env.DASHCADDY_INSTANCE_ID || null
|
||||
});
|
||||
});
|
||||
log.info('app', `Version endpoint available at /api/v1/version (v${appVersion})`);
|
||||
|
||||
// Wire up notification listeners for resourceMonitor and backupManager
|
||||
if (ctx.notification && ctx.resourceMonitor) {
|
||||
ctx.resourceMonitor.on('alert', (alertData) => {
|
||||
@@ -571,15 +607,15 @@ async function createApp() {
|
||||
|
||||
// Inline API routes
|
||||
apiRouter.get('/health', (req, res) => {
|
||||
res.json({ status: 'ok', timestamp: new Date().toISOString() });
|
||||
ok(res, { status: 'ok', timestamp: new Date().toISOString() });
|
||||
});
|
||||
|
||||
apiRouter.get('/csrf-token', (req, res) => {
|
||||
res.json({ success: true, token: req.csrfToken, headerName: CSRF_HEADER_NAME });
|
||||
ok(res, { token: req.csrfToken, headerName: CSRF_HEADER_NAME });
|
||||
});
|
||||
|
||||
apiRouter.get('/metrics', (req, res) => {
|
||||
res.json({ success: true, metrics: metrics.getSummary() });
|
||||
ok(res, { metrics: metrics.getSummary() });
|
||||
});
|
||||
|
||||
// Mount at /api/v1 (canonical, single version)
|
||||
@@ -587,9 +623,89 @@ async function createApp() {
|
||||
|
||||
// Root-level health check
|
||||
app.get('/health', (req, res) => {
|
||||
res.json({ status: 'ok', timestamp: new Date().toISOString() });
|
||||
ok(res, { status: 'ok', timestamp: new Date().toISOString() });
|
||||
});
|
||||
|
||||
// Liveness probe — "is the process alive?"
|
||||
// Always returns 200 unless the Node.js event loop is completely blocked.
|
||||
// Used by k8s/Docker to decide whether to RESTART the container.
|
||||
// DO NOT add dependency checks here — those belong in /health/ready.
|
||||
app.get('/health/live', (req, res) => {
|
||||
ok(res, { status: 'alive', uptime: process.uptime() });
|
||||
});
|
||||
|
||||
// Readiness probe — "is the app ready to serve traffic?"
|
||||
// Checks critical dependencies: Docker daemon, Caddy admin API, config file.
|
||||
// Returns 200 with details if all OK, 503 with failed components otherwise.
|
||||
// Used by k8s/Docker to decide whether to ROUTE TRAFFIC to this instance.
|
||||
app.get('/health/ready', boundAsyncHandler(async (req, res) => {
|
||||
const checks = {};
|
||||
let allOk = true;
|
||||
|
||||
// Check 1: Config file readable
|
||||
try {
|
||||
const fs = require('fs');
|
||||
if (fs.existsSync(config.CONFIG_FILE)) {
|
||||
fs.readFileSync(config.CONFIG_FILE, 'utf8');
|
||||
checks.configFile = { ok: true };
|
||||
} else {
|
||||
checks.configFile = { ok: false, error: 'Config file not found' };
|
||||
allOk = false;
|
||||
}
|
||||
} catch (e) {
|
||||
checks.configFile = { ok: false, error: e.message };
|
||||
allOk = false;
|
||||
}
|
||||
|
||||
// Check 2: Services file readable
|
||||
try {
|
||||
const fs = require('fs');
|
||||
if (fs.existsSync(config.SERVICES_FILE)) {
|
||||
fs.readFileSync(config.SERVICES_FILE, 'utf8');
|
||||
checks.servicesFile = { ok: true };
|
||||
} else {
|
||||
checks.servicesFile = { ok: false, error: 'Services file not found' };
|
||||
allOk = false;
|
||||
}
|
||||
} catch (e) {
|
||||
checks.servicesFile = { ok: false, error: e.message };
|
||||
allOk = false;
|
||||
}
|
||||
|
||||
// Check 3: Docker daemon reachable
|
||||
try {
|
||||
const docker = require('dockerode')();
|
||||
await docker.ping();
|
||||
checks.docker = { ok: true };
|
||||
} catch (e) {
|
||||
checks.docker = { ok: false, error: e.message };
|
||||
allOk = false;
|
||||
}
|
||||
|
||||
// Check 4: Caddy admin API reachable
|
||||
try {
|
||||
const caddyUrl = config.CADDY_ADMIN_URL || 'http://localhost:2019';
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 3000);
|
||||
const response = await fetch(`${caddyUrl}/config/`, {
|
||||
signal: controller.signal
|
||||
});
|
||||
clearTimeout(timeout);
|
||||
checks.caddy = { ok: response.ok, status: response.status };
|
||||
if (!response.ok) allOk = false;
|
||||
} catch (e) {
|
||||
checks.caddy = { ok: false, error: e.message };
|
||||
allOk = false;
|
||||
}
|
||||
|
||||
const body = {
|
||||
status: allOk ? 'ready' : 'not-ready',
|
||||
timestamp: new Date().toISOString(),
|
||||
checks
|
||||
};
|
||||
ok(res, body, allOk ? 200 : 503);
|
||||
}));
|
||||
|
||||
// Lightweight probe endpoint
|
||||
app.get('/probe/:id', boundAsyncHandler(async (req, res) => {
|
||||
const id = req.params.id;
|
||||
@@ -713,7 +829,7 @@ async function createApp() {
|
||||
}
|
||||
}
|
||||
|
||||
res.json(result);
|
||||
ok(res, result);
|
||||
} catch (error) {
|
||||
errorResponse(res, 500, safeErrorMessage(error));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Config migration system
|
||||
*
|
||||
* When config.json schema changes between versions, register a migration
|
||||
* function here. On load, the loader detects the stored version, runs all
|
||||
* migrations from that version forward, and writes the result back.
|
||||
*
|
||||
* Migration format:
|
||||
* migrations[<toVersion>] = (rawConfig) => { ...mutations, _version: toVersion }
|
||||
*
|
||||
* Each migration is responsible for transforming the previous version's
|
||||
* shape into the next version's shape. They run sequentially, so v1→v2→v3
|
||||
* all execute in order.
|
||||
*
|
||||
* For first-time users with no config file, the loader creates a fresh
|
||||
* config with CURRENT_VERSION, so they start at the latest schema.
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const platformPaths = require('../../platform-paths');
|
||||
|
||||
const CURRENT_VERSION = 2;
|
||||
|
||||
/**
|
||||
* Migrations: keys are the version they PRODUCE.
|
||||
* Each migration takes a raw config object and returns the next version.
|
||||
*/
|
||||
const migrations = {
|
||||
// v0 (unversioned) → v1: add _version field, normalize dns structure
|
||||
1: (raw) => {
|
||||
const migrated = { ...raw };
|
||||
if (!migrated._version) migrated._version = 1;
|
||||
// Normalize: older configs may have dns as a string IP, convert to object
|
||||
if (typeof migrated.dns === 'string') {
|
||||
migrated.dns = { ip: migrated.dns, port: 5380 };
|
||||
} else if (!migrated.dns) {
|
||||
migrated.dns = { ip: '', port: 5380 };
|
||||
}
|
||||
return migrated;
|
||||
},
|
||||
|
||||
// v1 → v2: add dns.provider field (default: 'technitium' for backwards compat)
|
||||
2: (raw) => {
|
||||
const migrated = { ...raw };
|
||||
if (migrated.dns && !migrated.dns.provider) {
|
||||
migrated.dns.provider = 'technitium';
|
||||
}
|
||||
migrated._version = 2;
|
||||
return migrated;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Run all migrations from `fromVersion` (or detected) to CURRENT_VERSION.
|
||||
* @param {object} raw - The raw config object (may or may not have _version)
|
||||
* @returns {object} The migrated config
|
||||
*/
|
||||
function migrate(raw) {
|
||||
if (!raw || typeof raw !== 'object') {
|
||||
// First-time load: return minimal config at current version
|
||||
return { _version: CURRENT_VERSION };
|
||||
}
|
||||
|
||||
const fromVersion = raw._version || 0;
|
||||
if (fromVersion > CURRENT_VERSION) {
|
||||
// Config from a future version — bail out, don't corrupt it
|
||||
// The validation step will catch any actual issues
|
||||
return raw;
|
||||
}
|
||||
|
||||
let current = { ...raw };
|
||||
for (let v = fromVersion + 1; v <= CURRENT_VERSION; v++) {
|
||||
if (migrations[v]) {
|
||||
current = migrations[v](current);
|
||||
} else {
|
||||
// No migration defined for this version, just bump _version
|
||||
current._version = v;
|
||||
}
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load config from disk, run migrations if needed, and write back the
|
||||
* migrated version. Safe to call on every startup.
|
||||
* @param {string} configFile - Absolute path to config.json
|
||||
* @param {object} log - Logger instance
|
||||
* @returns {object} The migrated config object
|
||||
*/
|
||||
function loadAndMigrate(configFile, log) {
|
||||
let raw = null;
|
||||
let fileExisted = false;
|
||||
|
||||
if (fs.existsSync(configFile)) {
|
||||
fileExisted = true;
|
||||
try {
|
||||
raw = JSON.parse(fs.readFileSync(configFile, 'utf8'));
|
||||
} catch (e) {
|
||||
if (log && log.error) {
|
||||
log.error('config-migration', 'Failed to parse config.json, using defaults', { error: e.message });
|
||||
}
|
||||
raw = null;
|
||||
}
|
||||
}
|
||||
|
||||
const fromVersion = raw && raw._version ? raw._version : 0;
|
||||
const migrated = migrate(raw);
|
||||
|
||||
// Only write back to disk if:
|
||||
// 1. The file already existed (we don't create configs on fresh installs —
|
||||
// the loader's defaults handle that case), AND
|
||||
// 2. The version actually changed (no point rewriting identical content)
|
||||
if (fileExisted && fromVersion < CURRENT_VERSION) {
|
||||
if (log && log.info) {
|
||||
log.info('config-migration', `Migrated config v${fromVersion} → v${CURRENT_VERSION}`, {
|
||||
from: fromVersion,
|
||||
to: CURRENT_VERSION,
|
||||
path: configFile
|
||||
});
|
||||
}
|
||||
// Write back the migrated config
|
||||
try {
|
||||
// Ensure parent dir exists
|
||||
const dir = path.dirname(configFile);
|
||||
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(configFile, JSON.stringify(migrated, null, 2));
|
||||
} catch (e) {
|
||||
if (log && log.warn) {
|
||||
log.warn('config-migration', 'Failed to write migrated config back to disk', { error: e.message });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return migrated;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
CURRENT_VERSION,
|
||||
migrations,
|
||||
migrate,
|
||||
loadAndMigrate
|
||||
};
|
||||
@@ -1,10 +1,15 @@
|
||||
/**
|
||||
* Site configuration loader
|
||||
* Loads and manages site-wide settings from config.json
|
||||
*
|
||||
* Includes automatic migration from older config versions (see migrations.js).
|
||||
* Users never see the migration — it runs silently on startup, writes the
|
||||
* updated config back, and the rest of the app only ever sees the current
|
||||
* schema.
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const { validateConfig } = require('../../config-schema');
|
||||
const { CADDY } = require('../../constants');
|
||||
const { loadAndMigrate, CURRENT_VERSION } = require('./migrations');
|
||||
|
||||
const siteConfig = {
|
||||
tld: '.home',
|
||||
@@ -21,9 +26,11 @@ const siteConfig = {
|
||||
|
||||
function loadSiteConfig(CONFIG_FILE, log) {
|
||||
try {
|
||||
if (fs.existsSync(CONFIG_FILE)) {
|
||||
const raw = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
|
||||
// Run migrations first — this handles config.json files from older
|
||||
// versions of DashCaddy and writes the migrated version back to disk.
|
||||
const raw = loadAndMigrate(CONFIG_FILE, log);
|
||||
|
||||
if (raw && Object.keys(raw).length > 0) {
|
||||
// Validate config and log any issues
|
||||
const { valid, errors: configErrors, warnings: configWarnings } = validateConfig(raw);
|
||||
if (log && log.warn) {
|
||||
@@ -76,4 +83,5 @@ module.exports = {
|
||||
loadSiteConfig,
|
||||
buildDomain,
|
||||
buildServiceUrl,
|
||||
CURRENT_VERSION
|
||||
};
|
||||
|
||||
@@ -93,9 +93,8 @@ async function verifySiteAccessible(domain, fetchT, httpsAgent, log, maxAttempts
|
||||
try {
|
||||
const response = await fetchT(`https://${domain}/`, {
|
||||
method: 'HEAD',
|
||||
agent: httpsAgent,
|
||||
timeout: 5000
|
||||
});
|
||||
agent: httpsAgent
|
||||
}, 5000);
|
||||
|
||||
log.info('caddy', 'Site is accessible', { domain, status: response.status });
|
||||
return true;
|
||||
|
||||
@@ -58,9 +58,9 @@ async function refreshDnsToken(username, password, server, fetchT, log) {
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
timeout: 10000
|
||||
}
|
||||
}
|
||||
},
|
||||
10000
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
@@ -96,7 +96,8 @@ function createProviderDnsContext(siteConfig, buildDomain, credentialManager, fe
|
||||
const params = new URLSearchParams({ user: username, pass: password, includeInfo: 'false' });
|
||||
const response = await fetchT(
|
||||
`http://${server}:5380/api/user/login?${params.toString()}`,
|
||||
{ method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 10000 }
|
||||
{ method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } },
|
||||
10000
|
||||
);
|
||||
const result = await response.json();
|
||||
if (result.status === 'ok' && result.token) {
|
||||
|
||||
@@ -38,7 +38,15 @@ function fetchT(url, opts = {}, timeoutMs = TIMEOUTS.HTTP_DEFAULT) {
|
||||
if (!opts.signal) {
|
||||
opts = { ...opts, signal: AbortSignal.timeout(timeoutMs) };
|
||||
}
|
||||
delete opts.timeout;
|
||||
// The `timeout` key in fetch() opts is silently ignored by undici. Callers
|
||||
// should use the third arg of fetchT() (timeoutMs) instead. If a caller
|
||||
// passes `timeout: N` here, it's almost certainly a bug — we used to silently
|
||||
// strip it, which masked the issue. Now we surface it in logs and strip it.
|
||||
if ('timeout' in opts) {
|
||||
console.warn(`[fetchT] opts.timeout=${opts.timeout} is ignored — pass timeoutMs as the 3rd arg of fetchT() instead. Called from: ${new Error().stack.split('\n').slice(2, 4).join(' <- ')}`);
|
||||
const { timeout, ...rest } = opts;
|
||||
opts = rest;
|
||||
}
|
||||
return fetch(url, opts);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +1,124 @@
|
||||
/**
|
||||
* Response helpers - Standard API response formats
|
||||
*
|
||||
* Single source of truth for HTTP response shapes across DashCaddy.
|
||||
* Standard envelope: { success: true, ...data } or { success: false, error: "..." }.
|
||||
*
|
||||
* All routes should import from this module — do not call res.json/res.status
|
||||
* directly with the response shape, use these helpers instead.
|
||||
*/
|
||||
const { HTTP_STATUS } = require('../../constants');
|
||||
|
||||
// ── Success helpers ────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Standard error response
|
||||
* Standard success response. Use this in route handlers.
|
||||
* Wraps the data object with a `success: true` envelope.
|
||||
* @param {object} res Express response
|
||||
* @param {object} [data={}] fields to include in the response body
|
||||
* @param {number} [statusCode=200] HTTP status code
|
||||
*/
|
||||
function ok(res, data = {}, statusCode = HTTP_STATUS.OK) {
|
||||
return res.status(statusCode).json({ success: true, ...data });
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias for `ok` — prefer `ok` in new code, but kept for code that imports as `success`.
|
||||
*/
|
||||
function success(res, data, statusCode) {
|
||||
return ok(res, data, statusCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Success response with a human-readable message field.
|
||||
* Use when there's no data to return, just confirmation.
|
||||
*/
|
||||
function successMessage(res, message, statusCode = HTTP_STATUS.OK) {
|
||||
return res.status(statusCode).json({ success: true, message });
|
||||
}
|
||||
|
||||
/**
|
||||
* 201 Created response.
|
||||
*/
|
||||
function created(res, data = {}) {
|
||||
return res.status(HTTP_STATUS.CREATED).json({ success: true, ...data });
|
||||
}
|
||||
|
||||
/**
|
||||
* 204 No Content response.
|
||||
*/
|
||||
function noContent(res) {
|
||||
return res.status(HTTP_STATUS.NO_CONTENT).send();
|
||||
}
|
||||
|
||||
// ── Error helpers ──────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Standard error response. Use this in route handlers.
|
||||
* @param {object} res Express response
|
||||
* @param {number} statusCode HTTP status code
|
||||
* @param {string} message Human-readable error message
|
||||
* @param {object} [extras={}] additional fields to merge into the response
|
||||
*/
|
||||
function errorResponse(res, statusCode, message, extras = {}) {
|
||||
return res.status(statusCode).json({ success: false, error: message, ...extras });
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard success response
|
||||
* Alias for `errorResponse` — kept for code that imports as `error`.
|
||||
*/
|
||||
function ok(res, data = {}) {
|
||||
return res.json({ success: true, ...data });
|
||||
function error(res, message, statusCode = HTTP_STATUS.INTERNAL_ERROR) {
|
||||
return res.status(statusCode).json({ success: false, error: message });
|
||||
}
|
||||
|
||||
/**
|
||||
* 400 Bad Request — invalid input from the user.
|
||||
*/
|
||||
function validationError(res, message) {
|
||||
return res.status(HTTP_STATUS.BAD_REQUEST).json({ success: false, error: message });
|
||||
}
|
||||
|
||||
/**
|
||||
* 401 Unauthorized — no valid credentials.
|
||||
*/
|
||||
function unauthorized(res, message = 'Unauthorized') {
|
||||
return res.status(HTTP_STATUS.UNAUTHORIZED).json({ success: false, error: message });
|
||||
}
|
||||
|
||||
/**
|
||||
* 403 Forbidden — credentials valid but permission denied.
|
||||
*/
|
||||
function forbidden(res, message = 'Forbidden') {
|
||||
return res.status(HTTP_STATUS.FORBIDDEN).json({ success: false, error: message });
|
||||
}
|
||||
|
||||
/**
|
||||
* 404 Not Found — resource doesn't exist.
|
||||
*/
|
||||
function notFound(res, message = 'Not found') {
|
||||
return res.status(HTTP_STATUS.NOT_FOUND).json({ success: false, error: message });
|
||||
}
|
||||
|
||||
/**
|
||||
* 409 Conflict — request conflicts with current state (e.g. duplicate).
|
||||
*/
|
||||
function conflict(res, message) {
|
||||
return res.status(HTTP_STATUS.CONFLICT).json({ success: false, error: message });
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
errorResponse,
|
||||
// Success helpers
|
||||
ok,
|
||||
success,
|
||||
successMessage,
|
||||
created,
|
||||
noContent,
|
||||
// Error helpers
|
||||
errorResponse,
|
||||
error,
|
||||
validationError,
|
||||
unauthorized,
|
||||
forbidden,
|
||||
notFound,
|
||||
conflict,
|
||||
};
|
||||
|
||||
@@ -65,7 +65,9 @@
|
||||
if (window.SkeletonLoader) window.SkeletonLoader.show(6);
|
||||
const response = await fetch('/api/v1/services', { cache: 'no-store' });
|
||||
if (response.ok) {
|
||||
window.APPS = await response.json();
|
||||
const result = await response.json();
|
||||
// Standard envelope: { success: true, services: [...], pagination?: {...} }
|
||||
window.APPS = result.services || [];
|
||||
if (window.SkeletonLoader) window.SkeletonLoader.hide();
|
||||
} else {
|
||||
console.error('Failed to load services:', response.status);
|
||||
|
||||
@@ -14,15 +14,15 @@
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.status === 'success') {
|
||||
if (result.success) {
|
||||
const select = document.getElementById('existing-ca-select');
|
||||
select.innerHTML = '';
|
||||
|
||||
if (result.data.cas.length === 0) {
|
||||
if (result.cas.length === 0) {
|
||||
select.innerHTML = '<option value="">No CAs found in Caddyfile</option>';
|
||||
} else {
|
||||
select.innerHTML = '<option value="">Select existing CA...</option>';
|
||||
result.data.cas.forEach(ca => {
|
||||
result.cas.forEach(ca => {
|
||||
const option = document.createElement('option');
|
||||
if (typeof ca === 'object') {
|
||||
option.value = ca.id;
|
||||
|
||||
Reference in New Issue
Block a user