Merge krystie-improvements into main
Resolves 24 conflicts between Hermes (DC-008/009/010 + response-helper
envelope standardization) and Krystie (DC-005 src/ refactor path fixes,
DC-006 TOTP integration, DC-007 new test suites, cloud backup
destinations).
Conflict resolutions:
- src/utils/logging.js: took ours (consumers depend on logError/
safeErrorMessage/createLogger exports)
- src/config/site.js: merged (her factored validateAndLogConfig +
applyConfigFields helpers)
- src/context/dns.js: took hers (admin/readonly role iteration for
write operations)
- src/utilities/backup-
manager.js: took hers (Dropbox/WebDAV/SFTP cloud feature)
- status/dist/*, status/
sw.js: took hers (minified bundles + newer SW cache)
Additional fix (post-merge regression):
- src/monitoring/health-checker.js: fixed DC-005 path miss —
'require(./platform-paths)' → 'require(../../platform-paths)'
Test status: 921/922 passing. One known failure in logging.test.js
(async file-handle timing) tracked as follow-up.
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
const express = require('express');
|
||||
const yaml = require('js-yaml');
|
||||
const { DOCKER, REGEX } = require('../../constants');
|
||||
const { ValidationError } = require('../../errors');
|
||||
const { DOCKER, REGEX } = require('../../../src/utilities/constants');
|
||||
const { ValidationError } = require('../../../src/utilities/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;
|
||||
|
||||
@@ -2,12 +2,13 @@ const express = require('express');
|
||||
const fsp = require('fs').promises;
|
||||
const path = require('path');
|
||||
const validatorLib = require('validator');
|
||||
const { REGEX, DOCKER } = require('../../constants');
|
||||
const { isValidPort } = require('../../input-validator');
|
||||
const { exists } = require('../../fs-helpers');
|
||||
const { REGEX, DOCKER } = require('../../../src/utilities/constants');
|
||||
const { isValidPort } = require('../../../src/security/input-validator');
|
||||
const { exists } = require('../../../src/utilities/fs-helpers');
|
||||
const platformPaths = require('../../platform-paths');
|
||||
const { ValidationError } = require('../../errors');
|
||||
const { logError } = require('../../src/utils/logging');
|
||||
const { ValidationError } = require('../../../src/utilities/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'));
|
||||
|
||||
@@ -306,7 +317,7 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
||||
} else {
|
||||
containerId = await deployContainer(appId, config, template);
|
||||
log.info('deploy', 'Container deployed', { containerId });
|
||||
await helpers.waitForHealthCheck(containerId, template.healthCheck, config.port || template.defaultPort);
|
||||
await helpers.waitForHealthCheck(containerId, template.healthCheck, config.port || template.defaultPort, 30);
|
||||
log.info('deploy', 'Container is healthy', { containerId });
|
||||
}
|
||||
|
||||
@@ -316,7 +327,7 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
||||
let dnsWarning = null;
|
||||
if (config.createDns && !isSubdirectoryMode) {
|
||||
try {
|
||||
await ctx.dns.createRecord(config.subdomain, config.ip);
|
||||
await ctx.dns.universalCreateRecord(config.subdomain, config.ip);
|
||||
log.info('deploy', 'DNS record created', { domain: ctx.buildDomain(config.subdomain), ip: config.ip });
|
||||
} catch (dnsError) {
|
||||
await logError('app-deploy-dns', dnsError, { appId, subdomain: config.subdomain, ip: config.ip });
|
||||
@@ -420,10 +431,11 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
||||
|
||||
res.json(response);
|
||||
} catch (error) {
|
||||
await logError('app-deploy', error, { appId, config });
|
||||
log.error('deploy', 'Deployment failed', { appId, error: error.message });
|
||||
try { await logError('app-deploy', error, { appId, config }); } catch (_) { /* logError failure should not mask original error */ }
|
||||
const msg = error?.message || String(error || 'Unknown error');
|
||||
log.error('deploy', 'Deployment failed', { appId, error: msg });
|
||||
const template = ctx.APP_TEMPLATES[appId];
|
||||
ctx.notification.send('deploymentFailed', 'Deployment Failed', `Failed to deploy **${template?.name || appId}**.\nError: ${error.message}`, 'error');
|
||||
try { ctx.notification.send('deploymentFailed', 'Deployment Failed', `Failed to deploy **${template?.name || appId}**.\nError: ${msg}`, 'error'); } catch (_) {}
|
||||
errorResponse(res, 500, ctx.safeErrorMessage(error));
|
||||
}
|
||||
}, 'apps-deploy'));
|
||||
|
||||
@@ -2,8 +2,8 @@ const fs = require('fs');
|
||||
const fsp = require('fs').promises;
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const { REGEX, DOCKER } = require('../../constants');
|
||||
const { exists } = require('../../fs-helpers');
|
||||
const { REGEX, DOCKER } = require('../../../src/utilities/constants');
|
||||
const { exists } = require('../../../src/utilities/fs-helpers');
|
||||
const platformPaths = require('../../platform-paths');
|
||||
|
||||
/**
|
||||
@@ -379,9 +379,12 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
||||
return content.slice(0, endIdx) + injection + content.slice(endIdx);
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
if (!result.success && result.error !== 'No changes to apply') {
|
||||
throw new Error(`[DC-303] Failed to add subpath config for ${subdomain}: ${result.error}`);
|
||||
}
|
||||
if (result.error === 'No changes to apply') {
|
||||
log.info('caddy', 'Subpath config already exists, reusing', { subdomain });
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove a subpath config block from between its markers in the Caddyfile. */
|
||||
|
||||
@@ -25,7 +25,6 @@ module.exports = function(ctx) {
|
||||
asyncHandler: ctx.asyncHandler,
|
||||
errorResponse: ctx.errorResponse,
|
||||
log: ctx.log,
|
||||
// Additional context properties needed by routes
|
||||
APP_TEMPLATES: ctx.APP_TEMPLATES,
|
||||
TEMPLATE_CATEGORIES: ctx.TEMPLATE_CATEGORIES,
|
||||
DIFFICULTY_LEVELS: ctx.DIFFICULTY_LEVELS,
|
||||
@@ -40,26 +39,27 @@ module.exports = function(ctx) {
|
||||
ctx: ctx
|
||||
};
|
||||
|
||||
// Initialize helpers with dependencies (ctx is the Koa context)
|
||||
const helpers = initHelpers({ ...deps, ctx });
|
||||
|
||||
// Mount sub-routes — pass full ctx so sub-routes can reference ctx.* properties
|
||||
const subCtx = Object.assign({}, ctx, { helpers });
|
||||
|
||||
try { router.use('/deploy', initDeploy(subCtx)); }
|
||||
catch(e) { (ctx.log || console).error('[apps] deploy routes init failed:', e.message); }
|
||||
// Mount sub-routers at their prefix paths.
|
||||
// Sub-modules define routes at '/' (root of their sub-router).
|
||||
// Final paths: /api/v1/apps/deploy, /api/v1/apps/remove, /api/v1/apps/templates, etc.
|
||||
|
||||
try { router.use('/remove', initRemoval(subCtx)); }
|
||||
catch(e) { (ctx.log || console).error('[apps] removal routes init failed:', e.message); }
|
||||
try { router.use('/apps', initDeploy(subCtx)); }
|
||||
catch(e) { (ctx.log || console).error('[apps] deploy routes init failed:', e.message, e.stack); }
|
||||
|
||||
try { router.use('/apps', initRemoval(subCtx)); }
|
||||
catch(e) { (ctx.log || console).error('[apps] removal routes init failed:', e.message, e.stack); }
|
||||
|
||||
try { router.use('/apps', initTemplates(subCtx)); }
|
||||
catch(e) { (ctx.log || console).error('[apps] templates routes init failed:', e.message); }
|
||||
catch(e) { (ctx.log || console).error('[apps] templates routes init failed:', e.message, e.stack); }
|
||||
|
||||
try { router.use('/restore', initRestore(Object.assign({}, subCtx, { backupManager: ctx.backupManager }))); }
|
||||
catch(e) { (ctx.log || console).error('[apps] restore routes init failed:', e.message); }
|
||||
try { router.use('/apps', initRestore(Object.assign({}, subCtx, { backupManager: ctx.backupManager }))); }
|
||||
catch(e) { (ctx.log || console).error('[apps] restore routes init failed:', e.message, e.stack); }
|
||||
|
||||
try { router.use('/compose', initCompose(subCtx)); }
|
||||
catch(e) { (ctx.log || console).error('[apps] compose routes init failed:', e.message); }
|
||||
try { router.use('/apps', initCompose(subCtx)); }
|
||||
catch(e) { (ctx.log || console).error('[apps] compose routes init failed:', e.message, e.stack); }
|
||||
|
||||
return router;
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const express = require('express');
|
||||
const { exists } = require('../../fs-helpers');
|
||||
const { logError } = require('../../src/utils/logging');
|
||||
const { exists } = require('../../../src/utilities/fs-helpers');
|
||||
const { logError } = require('../src/utils/logging');
|
||||
const { ok } = require('../src/utils/responses');
|
||||
|
||||
module.exports = function({
|
||||
docker, caddy, servicesStateManager, asyncHandler, log, helpers,
|
||||
@@ -71,18 +72,13 @@ module.exports = function({
|
||||
if (shouldDeleteContainer && subdomain && ctx.dns.getToken()) {
|
||||
try {
|
||||
const domain = ctx.buildDomain(subdomain);
|
||||
const getResult = await ctx.dns.call(ctx.siteConfig.dnsServerIp, '/api/zones/records/get', {
|
||||
token: ctx.dns.getToken(), domain, zone: ctx.siteConfig.tld.replace(/^\./, ''), listZone: 'true'
|
||||
});
|
||||
const resolveResult = await ctx.dns.universalResolveRecord(domain, 'A');
|
||||
let recordIp = ip || 'localhost';
|
||||
if (getResult.status === 'ok' && getResult.response?.records) {
|
||||
const aRecord = getResult.response.records.find(r => r.type === 'A');
|
||||
if (aRecord && aRecord.rData?.ipAddress) recordIp = aRecord.rData.ipAddress;
|
||||
if (resolveResult) {
|
||||
recordIp = resolveResult;
|
||||
}
|
||||
const dnsResult = await ctx.dns.call(ctx.siteConfig.dnsServerIp, '/api/zones/records/delete', {
|
||||
token: ctx.dns.getToken(), domain, type: 'A', ipAddress: recordIp
|
||||
});
|
||||
results.dns = dnsResult.status === 'ok' ? 'deleted' : (dnsResult.errorMessage || 'failed');
|
||||
await ctx.dns.universalDeleteRecord(domain, recordIp);
|
||||
results.dns = 'deleted';
|
||||
log.info('dns', 'DNS record removal', { result: results.dns });
|
||||
} catch (error) {
|
||||
results.dns = error.message;
|
||||
@@ -140,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 });
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
const express = require('express');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { DOCKER } = require('../../constants');
|
||||
const { DOCKER } = require('../../../src/utilities/constants');
|
||||
const { ok, validationError, notFound, errorResponse } = require('../../../src/utilities/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'));
|
||||
|
||||
@@ -458,7 +454,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
||||
// DNS record
|
||||
if (manifest.config.createDns && manifest.caddy.routingMode !== 'subdirectory') {
|
||||
try {
|
||||
await ctx.dns.createRecord(manifest.config.subdomain, manifest.config.ip);
|
||||
await ctx.dns.universalCreateRecord(manifest.config.subdomain, manifest.config.ip);
|
||||
log.info('restore', 'DNS record recreated', { subdomain: manifest.config.subdomain });
|
||||
} catch (e) {
|
||||
log.warn('restore', `DNS recreation failed: ${e.message}`);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const express = require('express');
|
||||
const { exists } = require('../../fs-helpers');
|
||||
const { exists } = require('../../../src/utilities/fs-helpers');
|
||||
/**
|
||||
* Apps templates routes factory
|
||||
* @param {Object} deps - Explicit dependencies
|
||||
@@ -19,7 +19,8 @@ const { exists } = require('../../fs-helpers');
|
||||
* @param {string} deps.SERVICES_FILE - Services file path
|
||||
* @returns {express.Router}
|
||||
*/
|
||||
const { REGEX } = require('../../constants');
|
||||
const { REGEX } = require('../../../src/utilities/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
|
||||
@@ -55,10 +55,10 @@ module.exports = function({
|
||||
const { appId } = req.params;
|
||||
const template = ctx.APP_TEMPLATES[appId];
|
||||
if (!template) {
|
||||
const { NotFoundError } = require('../../errors');
|
||||
const { NotFoundError } = require('../../../src/utilities/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;
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,7 @@ module.exports = function({
|
||||
// Update subdomain for deployed app
|
||||
router.post('/update-subdomain', asyncHandler(async (req, res) => {
|
||||
const { serviceId, oldSubdomain, newSubdomain, containerId, ip } = req.body;
|
||||
const { ValidationError } = require('../../errors');
|
||||
const { ValidationError } = require('../../../src/utilities/errors');
|
||||
|
||||
if (!oldSubdomain || typeof oldSubdomain !== 'string') {
|
||||
throw new ValidationError('oldSubdomain is required');
|
||||
@@ -107,10 +107,8 @@ module.exports = function({
|
||||
if (oldSubdomain && ctx.dns.getToken()) {
|
||||
try {
|
||||
const oldDomain = oldSubdomain.includes('.') ? oldSubdomain : ctx.buildDomain(oldSubdomain);
|
||||
const result = await ctx.dns.call(ctx.siteConfig.dnsServerIp, '/api/zones/records/delete', {
|
||||
token: ctx.dns.getToken(), domain: oldDomain, type: 'A', ipAddress: ip || 'localhost'
|
||||
});
|
||||
results.oldDns = result.status === 'ok' ? 'deleted' : result.errorMessage;
|
||||
await ctx.dns.universalDeleteRecord(oldDomain, ip || 'localhost');
|
||||
results.oldDns = 'deleted';
|
||||
log.info('dns', 'Old DNS record deleted', { domain: oldDomain });
|
||||
} catch (error) {
|
||||
results.oldDns = `failed: ${error.message}`;
|
||||
@@ -120,7 +118,7 @@ module.exports = function({
|
||||
|
||||
if (newSubdomain && ctx.dns.getToken()) {
|
||||
try {
|
||||
await ctx.dns.createRecord(newSubdomain, ip || 'localhost');
|
||||
await ctx.dns.universalCreateRecord(newSubdomain, ip || 'localhost');
|
||||
results.newDns = 'created';
|
||||
log.info('dns', 'New DNS record created', { domain: ctx.buildDomain(newSubdomain) });
|
||||
} catch (error) {
|
||||
@@ -172,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
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
const express = require('express');
|
||||
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 { APP_PORTS, ARR_SERVICES } = require('../../../src/utilities/constants');
|
||||
const { validateURL, validateToken } = require('../../../src/security/input-validator');
|
||||
const { ValidationError, AuthenticationError, NotFoundError } = require('../../../src/utilities/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 { validateURL, validateToken } = require('../../../src/security/input-validator');
|
||||
const { ValidationError } = require('../../../src/utilities/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 { APP_PORTS, ARR_SERVICES } = require('../../../src/utilities/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,4 +1,4 @@
|
||||
const { APP_PORTS } = require('../../constants');
|
||||
const { APP_PORTS } = require('../../../src/utilities/constants');
|
||||
|
||||
/**
|
||||
* Arr helpers factory
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const express = require('express');
|
||||
const { APP_PORTS } = require('../../constants');
|
||||
const { APP_PORTS } = require('../../../src/utilities/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,5 @@
|
||||
const express = require('express');
|
||||
const { APP_PORTS } = require('../../constants');
|
||||
const { APP_PORTS } = require('../../../src/utilities/constants');
|
||||
|
||||
/**
|
||||
* Arr smart-connect routes factory
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const express = require('express');
|
||||
const { ValidationError, ForbiddenError, NotFoundError } = require('../../errors');
|
||||
const { ValidationError, ForbiddenError, NotFoundError } = require('../../../src/utilities/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,5 @@
|
||||
const { SESSION_TTL, APP, PLEX, TIMEOUTS, buildMediaAuth } = require('../../constants');
|
||||
const { createCache, CACHE_CONFIGS } = require('../../cache-config');
|
||||
const { SESSION_TTL, APP, PLEX, TIMEOUTS, buildMediaAuth } = require('../../../src/utilities/constants');
|
||||
const { createCache, CACHE_CONFIGS } = require('../../../src/utilities/cache-config');
|
||||
|
||||
/**
|
||||
* Auth session handlers routes factory
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const express = require('express');
|
||||
const { SESSION_TTL, APP, PLEX, TIMEOUTS, buildMediaAuth } = require('../../constants');
|
||||
const { AuthenticationError, NotFoundError } = require('../../errors');
|
||||
const { SESSION_TTL, APP, PLEX, TIMEOUTS, buildMediaAuth } = require('../../../src/utilities/constants');
|
||||
const { AuthenticationError, NotFoundError } = require('../../../src/utilities/errors');
|
||||
|
||||
/**
|
||||
* Auth SSO gate routes factory
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const express = require('express');
|
||||
const { ValidationError, AuthenticationError } = require('../../errors');
|
||||
const { ValidationError, AuthenticationError } = require('../../src/utilities/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,
|
||||
@@ -122,7 +122,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
|
||||
@@ -159,7 +159,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
|
||||
@@ -193,7 +193,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)
|
||||
@@ -245,7 +245,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)
|
||||
@@ -264,8 +264,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'));
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* Auto-Restart Policy Routes
|
||||
*
|
||||
* CRUD endpoints for per-container auto-restart policies.
|
||||
* Also provides a dry-run test endpoint.
|
||||
*
|
||||
* @module routes/auto-restart
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const { success } = require('../src/utils/responses');
|
||||
const { ValidationError, NotFoundError } = require('../src/utilities/errors');
|
||||
|
||||
/**
|
||||
* Auto-restart route factory
|
||||
*
|
||||
* @param {Object} deps - Explicit dependencies
|
||||
* @param {Object} deps.autoRestartManager - AutoRestartManager instance
|
||||
* @param {Function} deps.asyncHandler - Async route handler wrapper
|
||||
* @param {Function} deps.logError - Error logging function
|
||||
* @returns {express.Router}
|
||||
*/
|
||||
module.exports = function ({ autoRestartManager, asyncHandler, logError }) {
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* GET /auto-restart/policies
|
||||
* List all configured auto-restart policies.
|
||||
*/
|
||||
router.get('/policies', asyncHandler(async (_req, res) => {
|
||||
const policies = autoRestartManager.listPolicies();
|
||||
success(res, { policies });
|
||||
}, 'auto-restart-list'));
|
||||
|
||||
/**
|
||||
* GET /auto-restart/policies/:serviceId
|
||||
* Get the restart policy for a single service.
|
||||
*/
|
||||
router.get('/policies/:serviceId', asyncHandler(async (req, res) => {
|
||||
const { serviceId } = req.params;
|
||||
|
||||
if (!serviceId || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,100}$/.test(serviceId)) {
|
||||
throw new ValidationError('Invalid service ID format');
|
||||
}
|
||||
|
||||
const policy = autoRestartManager.getPolicy(serviceId);
|
||||
if (!policy) {
|
||||
throw new NotFoundError(`Auto-restart policy for "${serviceId}"`);
|
||||
}
|
||||
|
||||
success(res, { policy });
|
||||
}, 'auto-restart-get'));
|
||||
|
||||
/**
|
||||
* POST /auto-restart/policies/:serviceId
|
||||
* Create or update a restart policy.
|
||||
*
|
||||
* Body: { enabled, maxRetries, retryIntervalMs, windowMinutes }
|
||||
*/
|
||||
router.post('/policies/:serviceId', asyncHandler(async (req, res) => {
|
||||
const { serviceId } = req.params;
|
||||
|
||||
if (!serviceId || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,100}$/.test(serviceId)) {
|
||||
throw new ValidationError('Invalid service ID format');
|
||||
}
|
||||
|
||||
const { enabled, maxRetries, retryIntervalMs, windowMinutes } = req.body;
|
||||
|
||||
// Validate inputs
|
||||
if (enabled !== undefined && typeof enabled !== 'boolean') {
|
||||
throw new ValidationError('enabled must be a boolean');
|
||||
}
|
||||
if (maxRetries !== undefined) {
|
||||
if (!Number.isInteger(maxRetries) || maxRetries < 0 || maxRetries > 100) {
|
||||
throw new ValidationError('maxRetries must be an integer between 0 and 100');
|
||||
}
|
||||
}
|
||||
if (retryIntervalMs !== undefined) {
|
||||
if (!Number.isInteger(retryIntervalMs) || retryIntervalMs < 0 || retryIntervalMs > 3600000) {
|
||||
throw new ValidationError('retryIntervalMs must be an integer between 0 and 3600000');
|
||||
}
|
||||
}
|
||||
if (windowMinutes !== undefined) {
|
||||
if (!Number.isInteger(windowMinutes) || windowMinutes < 0 || windowMinutes > 1440) {
|
||||
throw new ValidationError('windowMinutes must be an integer between 0 and 1440');
|
||||
}
|
||||
}
|
||||
|
||||
const policy = await autoRestartManager.setPolicy(serviceId, {
|
||||
...(enabled !== undefined && { enabled }),
|
||||
...(maxRetries !== undefined && { maxRetries }),
|
||||
...(retryIntervalMs !== undefined && { retryIntervalMs }),
|
||||
...(windowMinutes !== undefined && { windowMinutes }),
|
||||
});
|
||||
|
||||
success(res, { policy, message: `Policy ${serviceId} saved` });
|
||||
}, 'auto-restart-set'));
|
||||
|
||||
/**
|
||||
* DELETE /auto-restart/policies/:serviceId
|
||||
* Remove a restart policy.
|
||||
*/
|
||||
router.delete('/policies/:serviceId', asyncHandler(async (req, res) => {
|
||||
const { serviceId } = req.params;
|
||||
|
||||
if (!serviceId || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,100}$/.test(serviceId)) {
|
||||
throw new ValidationError('Invalid service ID format');
|
||||
}
|
||||
|
||||
const removed = await autoRestartManager.removePolicy(serviceId);
|
||||
if (!removed) {
|
||||
throw new NotFoundError(`Auto-restart policy for "${serviceId}"`);
|
||||
}
|
||||
|
||||
success(res, { message: `Policy for "${serviceId}" removed` });
|
||||
}, 'auto-restart-delete'));
|
||||
|
||||
/**
|
||||
* POST /auto-restart/policies/:serviceId/test
|
||||
* Dry-run: simulate a restart attempt without actually restarting.
|
||||
* Returns what *would* happen given the current policy state.
|
||||
*/
|
||||
router.post('/policies/:serviceId/test', asyncHandler(async (req, res) => {
|
||||
const { serviceId } = req.params;
|
||||
|
||||
if (!serviceId || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,100}$/.test(serviceId)) {
|
||||
throw new ValidationError('Invalid service ID format');
|
||||
}
|
||||
|
||||
const policy = autoRestartManager.getPolicy(serviceId);
|
||||
if (!policy) {
|
||||
throw new NotFoundError(`Auto-restart policy for "${serviceId}"`);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const inCooldown = policy.cooldownUntil && now < policy.cooldownUntil;
|
||||
const wouldRetry = !inCooldown && policy.currentRetries < policy.maxRetries;
|
||||
const nextAttempt = policy.currentRetries + 1;
|
||||
|
||||
success(res, {
|
||||
dryRun: true,
|
||||
serviceId,
|
||||
policy: {
|
||||
enabled: policy.enabled,
|
||||
currentRetries: policy.currentRetries,
|
||||
maxRetries: policy.maxRetries,
|
||||
cooldownUntil: policy.cooldownUntil,
|
||||
inCooldown,
|
||||
},
|
||||
wouldRestart: policy.enabled && wouldRetry,
|
||||
wouldMaxOut: !wouldRetry && !inCooldown,
|
||||
nextAttempt: wouldRetry ? nextAttempt : null,
|
||||
message: !policy.enabled
|
||||
? 'Policy is disabled — no restart would occur'
|
||||
: inCooldown
|
||||
? `In cooldown until ${new Date(policy.cooldownUntil).toISOString()} — would skip`
|
||||
: wouldRetry
|
||||
? `Would attempt restart ${nextAttempt}/${policy.maxRetries}`
|
||||
: `Max retries (${policy.maxRetries}) already reached — would enter cooldown`,
|
||||
});
|
||||
}, 'auto-restart-test'));
|
||||
|
||||
return router;
|
||||
};
|
||||
@@ -1,8 +1,8 @@
|
||||
const express = require('express');
|
||||
const fsp = require('fs').promises;
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { success } = require('../response-helpers');
|
||||
const path = require('path');
|
||||
const { success } = require('../src/utils/responses');
|
||||
|
||||
const DEFAULT_BACKUP_DIR = process.env.BACKUP_DIR || path.join(__dirname, '..', 'backups');
|
||||
const DEFAULT_MAX_STORAGE_BYTES = process.env.BACKUP_MAX_STORAGE_BYTES
|
||||
@@ -60,7 +60,7 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||
const { appId, enabled, schedule, retention, runImmediately, destination, destinationPath, maxStorageBytes } = req.body;
|
||||
|
||||
if (!appId) {
|
||||
const { ValidationError } = require('../errors');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
throw new ValidationError('appId is required');
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||
const config = backupManager.getConfig();
|
||||
|
||||
if (!config.backups || !config.backups[appId]) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError(`No backup schedule found for app: ${appId}`, 'DC-404');
|
||||
}
|
||||
|
||||
@@ -164,7 +164,7 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||
|
||||
const backupConfig = config.backups && config.backups[appId];
|
||||
if (!backupConfig) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError(`No backup schedule found for app: ${appId}`, 'DC-404');
|
||||
}
|
||||
|
||||
@@ -240,13 +240,13 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||
|
||||
// Security: prevent path traversal
|
||||
if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
|
||||
const { ValidationError } = require('../errors');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
throw new ValidationError('Invalid filename');
|
||||
}
|
||||
|
||||
const filepath = path.join(DEFAULT_BACKUP_DIR, filename);
|
||||
if (!fs.existsSync(filepath)) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError(`Backup file not found: ${filename}`, 'DC-404');
|
||||
}
|
||||
|
||||
@@ -376,13 +376,13 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||
|
||||
// Security: prevent path traversal
|
||||
if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
|
||||
const { ValidationError } = require('../errors');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
throw new ValidationError('Invalid filename');
|
||||
}
|
||||
|
||||
const filepath = path.join(DEFAULT_BACKUP_DIR, filename);
|
||||
if (!fs.existsSync(filepath)) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError(`Backup file not found: ${filename}`, 'DC-404');
|
||||
}
|
||||
|
||||
@@ -546,7 +546,7 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||
router.post('/backups/test-destination', asyncHandler(async (req, res) => {
|
||||
const destination = req.body;
|
||||
if (!destination || !destination.type) {
|
||||
const { ValidationError } = require('../errors');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
throw new ValidationError('destination.type is required');
|
||||
}
|
||||
const result = await backupManager.testDestination(destination);
|
||||
@@ -556,10 +556,10 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||
// Get cloud credentials (masked) for a provider
|
||||
// Provider: dropbox | webdav | sftp
|
||||
router.get('/backups/credentials/:provider', asyncHandler(async (req, res) => {
|
||||
const credentialManager = require('../credential-manager');
|
||||
const credentialManager = require('../src/managers/credential-manager');
|
||||
const provider = req.params.provider;
|
||||
if (!['dropbox', 'webdav', 'sftp'].includes(provider)) {
|
||||
const { ValidationError } = require('../errors');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
throw new ValidationError('Invalid provider');
|
||||
}
|
||||
|
||||
@@ -588,8 +588,8 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||
|
||||
// Save cloud credentials for a provider
|
||||
router.post('/backups/credentials/:provider', asyncHandler(async (req, res) => {
|
||||
const credentialManager = require('../credential-manager');
|
||||
const { ValidationError } = require('../errors');
|
||||
const credentialManager = require('../src/managers/credential-manager');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
const provider = req.params.provider;
|
||||
|
||||
if (!['dropbox', 'webdav', 'sftp'].includes(provider)) {
|
||||
@@ -629,8 +629,8 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||
|
||||
// Delete cloud credentials for a provider
|
||||
router.delete('/backups/credentials/:provider', asyncHandler(async (req, res) => {
|
||||
const credentialManager = require('../credential-manager');
|
||||
const { ValidationError } = require('../errors');
|
||||
const credentialManager = require('../src/managers/credential-manager');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
const provider = req.params.provider;
|
||||
|
||||
if (!['dropbox', 'webdav', 'sftp'].includes(provider)) {
|
||||
|
||||
@@ -2,9 +2,10 @@ const express = require('express');
|
||||
const fs = require('fs');
|
||||
const fsp = require('fs').promises;
|
||||
const path = require('path');
|
||||
const { exists, isAccessible } = require('../fs-helpers');
|
||||
const { paginate, parsePaginationParams } = require('../pagination');
|
||||
const { ValidationError, ForbiddenError } = require('../errors');
|
||||
const { exists, isAccessible } = require('../src/utilities/fs-helpers');
|
||||
const { paginate, parsePaginationParams } = require('../src/utilities/pagination');
|
||||
const { ValidationError, ForbiddenError } = require('../src/utilities/errors');
|
||||
const { ok } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Browse route factory
|
||||
@@ -44,7 +45,7 @@ module.exports = function({ asyncHandler, ok, validateSecurePath, auditLogger, d
|
||||
}
|
||||
}
|
||||
|
||||
ok(res, { roots });
|
||||
return ok(res, { roots });
|
||||
}, 'browse-roots'));
|
||||
|
||||
// Browse directory contents
|
||||
@@ -98,7 +99,7 @@ module.exports = function({ asyncHandler, ok, validateSecurePath, auditLogger, d
|
||||
}
|
||||
|
||||
if (!await exists(resolvedPath)) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError('Path');
|
||||
}
|
||||
|
||||
@@ -124,8 +125,7 @@ module.exports = function({ asyncHandler, ok, validateSecurePath, auditLogger, d
|
||||
|
||||
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, ok, validateSecurePath, auditLogger, d
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
ok(res, {
|
||||
mounts: detectedMounts,
|
||||
message: detectedMounts.length > 0
|
||||
? `Found ${detectedMounts.length} media mount(s) from existing containers`
|
||||
|
||||
+20
-26
@@ -3,8 +3,9 @@ const fs = require('fs');
|
||||
const fsp = require('fs').promises;
|
||||
const path = require('path');
|
||||
const { execSync } = require('child_process');
|
||||
const { exists } = require('../fs-helpers');
|
||||
const { ValidationError } = require('../errors');
|
||||
const { exists } = require('../src/utilities/fs-helpers');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
const { ok } = require('../src/utils/responses');
|
||||
const platformPaths = require('../platform-paths');
|
||||
|
||||
module.exports = function(ctx) {
|
||||
@@ -12,16 +13,13 @@ 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');
|
||||
const { NotFoundError } = require('../src/utilities/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,16 +43,14 @@ 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');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError('Root CA certificate');
|
||||
}
|
||||
|
||||
@@ -72,14 +67,13 @@ 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 {
|
||||
const { NotFoundError } = require('../errors');
|
||||
if (await exists(certInfoPath)) {
|
||||
certInfoFile = certInfoPath;
|
||||
} else {
|
||||
const { NotFoundError } = require('../src/utilities/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;
|
||||
@@ -112,7 +106,7 @@ module.exports = function(ctx) {
|
||||
}
|
||||
|
||||
if (!templateContent) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError(`Install script template (${templateName})`);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Config Drift Detection Routes
|
||||
*
|
||||
* API endpoints for running drift detection, reading cached reports,
|
||||
* auto-fixing drift, and controlling periodic polling.
|
||||
*
|
||||
* @module routes/config-drift
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const { success } = require('../src/utils/responses');
|
||||
const { ValidationError, NotFoundError } = require('../src/utilities/errors');
|
||||
|
||||
/**
|
||||
* Config-drift route factory
|
||||
*
|
||||
* @param {Object} deps - Explicit dependencies
|
||||
* @param {Object} deps.driftDetector - ConfigDriftDetector instance
|
||||
* @param {Function} deps.asyncHandler - Async route handler wrapper
|
||||
* @param {Function} deps.logError - Error logging function
|
||||
* @returns {express.Router}
|
||||
*/
|
||||
module.exports = function ({ driftDetector, asyncHandler, logError }) {
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* GET /config-drift/report
|
||||
* Run a fresh drift detection and return the full report.
|
||||
*/
|
||||
router.get('/report', asyncHandler(async (_req, res) => {
|
||||
const report = await driftDetector.detect();
|
||||
success(res, { report });
|
||||
}, 'drift-report'));
|
||||
|
||||
/**
|
||||
* GET /config-drift/last
|
||||
* Return the last cached drift report (no re-detection).
|
||||
*/
|
||||
router.get('/last', asyncHandler(async (_req, res) => {
|
||||
if (!driftDetector.lastReport) {
|
||||
throw new NotFoundError('No cached drift report — run detection first');
|
||||
}
|
||||
|
||||
success(res, { report: driftDetector.lastReport });
|
||||
}, 'drift-last'));
|
||||
|
||||
/**
|
||||
* POST /config-drift/fix
|
||||
* Auto-fix detected drift: remove stale records, flag unknown containers.
|
||||
*/
|
||||
router.post('/fix', asyncHandler(async (_req, res) => {
|
||||
const result = await driftDetector.autoFix();
|
||||
success(res, {
|
||||
message: 'Auto-fix applied',
|
||||
staleRemoved: result.staleRemoved,
|
||||
unknownFlagged: result.unknownFlagged,
|
||||
});
|
||||
}, 'drift-fix'));
|
||||
|
||||
/**
|
||||
* POST /config-drift/polling
|
||||
* Enable or disable periodic drift detection polling.
|
||||
*
|
||||
* Body: { enabled: boolean, intervalMs?: number }
|
||||
*/
|
||||
router.post('/polling', asyncHandler(async (req, res) => {
|
||||
const { enabled, intervalMs } = req.body;
|
||||
|
||||
if (typeof enabled !== 'boolean') {
|
||||
throw new ValidationError('enabled must be a boolean');
|
||||
}
|
||||
|
||||
if (intervalMs !== undefined) {
|
||||
if (!Number.isInteger(intervalMs) || intervalMs < 10000 || intervalMs > 86400000) {
|
||||
throw new ValidationError('intervalMs must be an integer between 10000 and 86400000 (10s – 24h)');
|
||||
}
|
||||
}
|
||||
|
||||
if (enabled) {
|
||||
driftDetector.startPolling(intervalMs || 300000);
|
||||
success(res, {
|
||||
message: 'Drift polling enabled',
|
||||
intervalMs: intervalMs || 300000,
|
||||
});
|
||||
} else {
|
||||
driftDetector.stopPolling();
|
||||
success(res, { message: 'Drift polling disabled' });
|
||||
}
|
||||
}, 'drift-polling'));
|
||||
|
||||
return router;
|
||||
};
|
||||
@@ -1,9 +1,11 @@
|
||||
const express = require('express');
|
||||
const fsp = require('fs').promises;
|
||||
const path = require('path');
|
||||
const { LIMITS } = require('../../constants');
|
||||
const { exists } = require('../../fs-helpers');
|
||||
const { ValidationError } = require('../../errors');
|
||||
const { LIMITS } = require('../../../src/utilities/constants');
|
||||
const { exists } = require('../../../src/utilities/fs-helpers');
|
||||
const { ValidationError } = require('../../../src/utilities/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;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
const fsp = require('fs').promises;
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { CADDY } = require('../../constants');
|
||||
const { exists } = require('../../fs-helpers');
|
||||
const { ValidationError, AuthenticationError } = require('../../errors');
|
||||
const { CADDY } = require('../../../src/utilities/constants');
|
||||
const { exists } = require('../../../src/utilities/fs-helpers');
|
||||
const { ValidationError, AuthenticationError } = require('../../../src/utilities/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
|
||||
@@ -378,7 +380,7 @@ module.exports = function(deps) {
|
||||
if (results.restored.includes('encryptionKey')) {
|
||||
try {
|
||||
// Clear the cached key so crypto-utils reloads from the new file on next use
|
||||
const cryptoUtils = require('../../crypto-utils');
|
||||
const cryptoUtils = require('../../../src/security/crypto-utils');
|
||||
if (typeof cryptoUtils.clearCachedKey === 'function') {
|
||||
cryptoUtils.clearCachedKey();
|
||||
}
|
||||
@@ -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'));
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
const fsp = require('fs').promises;
|
||||
const { validateConfig } = require('../../config-schema');
|
||||
const { exists } = require('../../fs-helpers');
|
||||
const { ValidationError } = require('../../errors');
|
||||
const { validateConfig } = require('../../../src/utilities/config-schema');
|
||||
const { exists } = require('../../../src/utilities/fs-helpers');
|
||||
const { ValidationError } = require('../../../src/utilities/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;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
const express = require('express');
|
||||
const { DOCKER } = require('../constants');
|
||||
const { paginate, parsePaginationParams } = require('../pagination');
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { success } = require('../response-helpers');
|
||||
const { DOCKER } = require('../src/utilities/constants');
|
||||
const { paginate, parsePaginationParams } = require('../src/utilities/pagination');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
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
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* Dependencies Route — REST API for service dependency tracking
|
||||
*
|
||||
* Endpoints:
|
||||
* GET /dependencies/graph Full dependency graph
|
||||
* GET /dependencies/validate Validate a proposed dep chain
|
||||
* GET /dependencies/:serviceId Direct deps for one service
|
||||
* GET /dependencies/:serviceId/chain Ordered restart chain
|
||||
* GET /dependencies/:serviceId/status Dependency health status
|
||||
* POST /dependencies/:serviceId Set dependencies
|
||||
* DELETE /dependencies/:serviceId Remove all dependencies
|
||||
* POST /dependencies/:serviceId/restart Restart with dependency chain
|
||||
*
|
||||
* @module routes/dependencies
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const { success, error: errorResponse } = require('../src/utils/responses');
|
||||
const { NotFoundError, ValidationError } = require('../src/utilities/errors');
|
||||
|
||||
/**
|
||||
* Dependencies route factory
|
||||
*
|
||||
* @param {Object} deps - Explicit dependencies
|
||||
* @param {Object} deps.dependencyManager - DependencyManager instance
|
||||
* @param {Object} deps.servicesStateManager - State manager for services.json
|
||||
* @param {Object} deps.docker - Docker client wrapper
|
||||
* @param {Function} deps.asyncHandler - Async route handler wrapper
|
||||
* @param {Function} deps.logError - Error logging function
|
||||
* @param {Function} deps.resyncHealthChecker - Health checker resync function
|
||||
* @param {Object} deps.log - Logger instance
|
||||
* @returns {express.Router}
|
||||
*/
|
||||
module.exports = function({
|
||||
dependencyManager,
|
||||
servicesStateManager,
|
||||
docker,
|
||||
asyncHandler,
|
||||
logError,
|
||||
resyncHealthChecker,
|
||||
log,
|
||||
}) {
|
||||
const router = express.Router();
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// GET /dependencies/graph — Full dependency graph
|
||||
// -------------------------------------------------------------------------
|
||||
router.get('/graph', asyncHandler(async (req, res) => {
|
||||
const graph = await dependencyManager.getDependencyGraph();
|
||||
success(res, { graph });
|
||||
}, 'dep-graph'));
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// GET /dependencies/validate — Validate a proposed dep chain (query params)
|
||||
// -------------------------------------------------------------------------
|
||||
router.get('/validate', asyncHandler(async (req, res) => {
|
||||
const { serviceId, dependsOn } = req.query;
|
||||
|
||||
if (!serviceId) {
|
||||
throw new ValidationError('serviceId query parameter is required');
|
||||
}
|
||||
|
||||
// dependsOn may be a comma-separated string or already an array
|
||||
let parsed;
|
||||
if (Array.isArray(dependsOn)) {
|
||||
parsed = dependsOn;
|
||||
} else if (typeof dependsOn === 'string' && dependsOn.length > 0) {
|
||||
parsed = dependsOn.split(',').map(s => s.trim()).filter(Boolean);
|
||||
} else {
|
||||
parsed = [];
|
||||
}
|
||||
|
||||
const result = await dependencyManager.validateDependencies(serviceId, parsed);
|
||||
success(res, result);
|
||||
}, 'dep-validate'));
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// GET /dependencies/:serviceId — Direct deps for one service
|
||||
// -------------------------------------------------------------------------
|
||||
router.get('/:serviceId', asyncHandler(async (req, res) => {
|
||||
const { serviceId } = req.params;
|
||||
const dependencies = await dependencyManager.getDependencies(serviceId);
|
||||
const dependents = await dependencyManager.getDependents(serviceId);
|
||||
|
||||
// Read the service's current dependsOn array
|
||||
const services = await servicesStateManager.read();
|
||||
const allServices = Array.isArray(services) ? services : (services.services || []);
|
||||
const service = allServices.find(s => s.id === serviceId);
|
||||
|
||||
if (!service) {
|
||||
throw new NotFoundError(`Service "${serviceId}"`);
|
||||
}
|
||||
|
||||
success(res, {
|
||||
serviceId,
|
||||
dependsOn: service.dependsOn || [],
|
||||
dependencies,
|
||||
dependents: dependents.map(d => ({ id: d.id, name: d.name })),
|
||||
});
|
||||
}, 'dep-get'));
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// GET /dependencies/:serviceId/chain — Ordered restart chain
|
||||
// -------------------------------------------------------------------------
|
||||
router.get('/:serviceId/chain', asyncHandler(async (req, res) => {
|
||||
const { serviceId } = req.params;
|
||||
const chain = await dependencyManager.getOrderedRestartChain(serviceId);
|
||||
success(res, { serviceId, chain });
|
||||
}, 'dep-chain'));
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// GET /dependencies/:serviceId/status — Dependency health status
|
||||
// -------------------------------------------------------------------------
|
||||
router.get('/:serviceId/status', asyncHandler(async (req, res) => {
|
||||
const { serviceId } = req.params;
|
||||
const statuses = await dependencyManager.getDependencyStatus(serviceId);
|
||||
success(res, { serviceId, statuses });
|
||||
}, 'dep-status'));
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// POST /dependencies/:serviceId — Set dependencies
|
||||
// -------------------------------------------------------------------------
|
||||
router.post('/:serviceId', asyncHandler(async (req, res) => {
|
||||
const { serviceId } = req.params;
|
||||
const { dependsOn } = req.body;
|
||||
|
||||
if (!Array.isArray(dependsOn)) {
|
||||
throw new ValidationError('Request body must include dependsOn as an array of service IDs');
|
||||
}
|
||||
|
||||
// Validate first
|
||||
const validation = await dependencyManager.validateDependencies(serviceId, dependsOn);
|
||||
if (!validation.valid) {
|
||||
return errorResponse(res, validation.errors.join('; '), 400);
|
||||
}
|
||||
|
||||
// Update the service
|
||||
let found = false;
|
||||
await servicesStateManager.update(services => {
|
||||
const arr = Array.isArray(services) ? services : [];
|
||||
return arr.map(s => {
|
||||
if (s.id === serviceId) {
|
||||
found = true;
|
||||
return { ...s, dependsOn: dependsOn.slice() };
|
||||
}
|
||||
return s;
|
||||
});
|
||||
});
|
||||
|
||||
if (!found) {
|
||||
throw new NotFoundError(`Service "${serviceId}"`);
|
||||
}
|
||||
|
||||
log.info('dependency', 'Dependencies updated', { serviceId, dependsOn });
|
||||
|
||||
success(res, {
|
||||
message: `Dependencies updated for "${serviceId}"`,
|
||||
serviceId,
|
||||
dependsOn,
|
||||
});
|
||||
}, 'dep-set'));
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// DELETE /dependencies/:serviceId — Remove all dependencies for a service
|
||||
// -------------------------------------------------------------------------
|
||||
router.delete('/:serviceId', asyncHandler(async (req, res) => {
|
||||
const { serviceId } = req.params;
|
||||
|
||||
let found = false;
|
||||
await servicesStateManager.update(services => {
|
||||
const arr = Array.isArray(services) ? services : [];
|
||||
return arr.map(s => {
|
||||
if (s.id === serviceId) {
|
||||
found = true;
|
||||
const updated = { ...s };
|
||||
delete updated.dependsOn;
|
||||
return updated;
|
||||
}
|
||||
return s;
|
||||
});
|
||||
});
|
||||
|
||||
if (!found) {
|
||||
throw new NotFoundError(`Service "${serviceId}"`);
|
||||
}
|
||||
|
||||
log.info('dependency', 'Dependencies removed', { serviceId });
|
||||
|
||||
success(res, {
|
||||
message: `All dependencies removed for "${serviceId}"`,
|
||||
serviceId,
|
||||
});
|
||||
}, 'dep-delete'));
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// POST /dependencies/:serviceId/restart — Restart with dependency chain
|
||||
// -------------------------------------------------------------------------
|
||||
router.post('/:serviceId/restart', asyncHandler(async (req, res) => {
|
||||
const { serviceId } = req.params;
|
||||
|
||||
// Verify the service exists
|
||||
const services = await servicesStateManager.read();
|
||||
const allServices = Array.isArray(services) ? services : (services.services || []);
|
||||
if (!allServices.find(s => s.id === serviceId)) {
|
||||
throw new NotFoundError(`Service "${serviceId}"`);
|
||||
}
|
||||
|
||||
// Get the chain first for the response (before async restart begins)
|
||||
let chain;
|
||||
try {
|
||||
chain = await dependencyManager.getOrderedRestartChain(serviceId);
|
||||
} catch (err) {
|
||||
return errorResponse(res, err.message, 400);
|
||||
}
|
||||
|
||||
// Respond immediately with the chain order
|
||||
success(res, {
|
||||
message: `Dependency restart initiated for "${serviceId}"`,
|
||||
serviceId,
|
||||
chain,
|
||||
});
|
||||
|
||||
// Run the restart chain asynchronously so the client doesn't block
|
||||
dependencyManager.restartWithDependencies(serviceId).catch(err => {
|
||||
if (log) {
|
||||
log.error('dependency', 'Async dependency restart failed', {
|
||||
serviceId,
|
||||
error: err.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
}, 'dep-restart'));
|
||||
|
||||
return router;
|
||||
};
|
||||
+236
-17
@@ -2,10 +2,10 @@ const express = require('express');
|
||||
const fs = require('fs');
|
||||
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 { ValidationError, AuthenticationError, NotFoundError } = require('../errors');
|
||||
const { APP, TIMEOUTS, CADDY, DNS_RECORD_TYPES, REGEX, SESSION_TTL } = require('../src/utilities/constants');
|
||||
const { exists } = require('../src/utilities/fs-helpers');
|
||||
const { success, error: errorResponse } = require('../src/utils/responses');
|
||||
const { ValidationError, AuthenticationError, NotFoundError } = require('../src/utilities/errors');
|
||||
|
||||
/**
|
||||
* DNS routes factory
|
||||
@@ -26,7 +26,8 @@ module.exports = function({
|
||||
log,
|
||||
safeErrorMessage,
|
||||
fetchT,
|
||||
credentialManager
|
||||
credentialManager,
|
||||
dnsPropagationChecker
|
||||
}) {
|
||||
const router = express.Router();
|
||||
|
||||
@@ -41,7 +42,137 @@ module.exports = function({
|
||||
return serverIp;
|
||||
}
|
||||
|
||||
// DELETE /record — Delete a DNS record from Technitium
|
||||
// ===== DNS PROVIDER ENDPOINTS =====
|
||||
|
||||
// GET /providers — List all available DNS providers
|
||||
router.get('/providers', asyncHandler(async (req, res) => {
|
||||
const providers = dns.getAvailableProviders ? dns.getAvailableProviders() : [];
|
||||
const activeProvider = dns.getProviderId ? dns.getProviderId() : 'technitium';
|
||||
success(res, { providers, activeProvider });
|
||||
}, 'dns-providers-list'));
|
||||
|
||||
// GET /provider/status — Get active provider status
|
||||
router.get('/provider/status', asyncHandler(async (req, res) => {
|
||||
if (!dns.getActiveProvider) {
|
||||
return success(res, { providerId: 'technitium', capabilities: ['create-record', 'delete-record', 'resolve', 'list-records', 'logs', 'restart', 'update-check', 'credentials', 'zones'] });
|
||||
}
|
||||
try {
|
||||
const provider = dns.getActiveProvider();
|
||||
const status = await provider.getStatus();
|
||||
success(res, status);
|
||||
} catch (err) {
|
||||
errorResponse(res, safeErrorMessage(err), 500);
|
||||
}
|
||||
}, 'dns-provider-status'));
|
||||
|
||||
// ===== UNIVERSAL RECORD ENDPOINTS (work with any provider) =====
|
||||
|
||||
// POST /universal/record — Create a DNS record via any provider
|
||||
router.post('/universal/record', asyncHandler(async (req, res) => {
|
||||
if (!dns.getActiveProvider) {
|
||||
// Fallback to legacy Technitium route
|
||||
return res.redirect(307, '/api/dns/record');
|
||||
}
|
||||
const { domain, ip, ttl, type, server } = req.body;
|
||||
if (!domain || !ip) throw new ValidationError('domain and ip are required');
|
||||
if (!REGEX.DOMAIN.test(domain)) throw new ValidationError('[DC-301] Invalid domain format');
|
||||
if (!validatorLib.isIP(ip)) throw new ValidationError('[DC-210] Invalid IP address');
|
||||
|
||||
try {
|
||||
const provider = dns.getActiveProvider();
|
||||
if (!provider.supportsCapability('create-record')) {
|
||||
const result = await provider.createRecord({
|
||||
domain, zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||
type: type || 'A', value: ip, ttl: ttl || 300, overwrite: true
|
||||
});
|
||||
return success(res, {
|
||||
message: result.message || `DNS record instructions provided`,
|
||||
manual: true,
|
||||
instructions: result.instructions
|
||||
});
|
||||
}
|
||||
|
||||
const result = await provider.createRecord({
|
||||
domain, zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||
type: type || 'A', value: ip, ttl: ttl || 300, overwrite: true
|
||||
});
|
||||
|
||||
// Start propagation check in background
|
||||
if (dnsPropagationChecker && ip) {
|
||||
dnsPropagationChecker.startVerification(domain, ip).catch(err => {
|
||||
log('DNS propagation check start failed:', err.message);
|
||||
});
|
||||
}
|
||||
|
||||
success(res, {
|
||||
message: result.status === 'manual' ? result.message : `DNS record ${domain} -> ${ip} created`,
|
||||
provider: dns.getProviderId(),
|
||||
...(result.instructions ? { manual: true, instructions: result.instructions } : {})
|
||||
});
|
||||
} catch (error) {
|
||||
log.error('dns', 'Universal DNS record creation error', { error: error.message });
|
||||
errorResponse(res, safeErrorMessage(error), 500);
|
||||
}
|
||||
}, 'dns-universal-create'));
|
||||
|
||||
// DELETE /universal/record — Delete a DNS record via any provider
|
||||
router.delete('/universal/record', asyncHandler(async (req, res) => {
|
||||
if (!dns.getActiveProvider) {
|
||||
return res.redirect(307, '/api/dns/record');
|
||||
}
|
||||
const { domain, type, value } = req.query;
|
||||
if (!domain) throw new ValidationError('domain is required');
|
||||
if (!REGEX.DOMAIN.test(domain)) throw new ValidationError('[DC-301] Invalid domain format');
|
||||
|
||||
try {
|
||||
const provider = dns.getActiveProvider();
|
||||
const result = await provider.deleteRecord({
|
||||
domain, type: type || 'A', value
|
||||
});
|
||||
|
||||
success(res, {
|
||||
message: result.status === 'manual' ? result.message : `DNS record ${domain} deleted`,
|
||||
provider: dns.getProviderId(),
|
||||
...(result.instructions ? { manual: true, instructions: result.instructions } : {})
|
||||
});
|
||||
} catch (error) {
|
||||
log.error('dns', 'Universal DNS record deletion error', { error: error.message });
|
||||
errorResponse(res, safeErrorMessage(error), 500);
|
||||
}
|
||||
}, 'dns-universal-delete'));
|
||||
|
||||
// GET /universal/resolve — Resolve a domain via any provider
|
||||
router.get('/universal/resolve', asyncHandler(async (req, res) => {
|
||||
if (!dns.getActiveProvider) {
|
||||
return res.redirect(307, '/api/dns/resolve');
|
||||
}
|
||||
const { domain, type } = req.query;
|
||||
if (!domain) throw new ValidationError('domain is required');
|
||||
if (!REGEX.DOMAIN.test(domain)) throw new ValidationError('[DC-301] Invalid domain format');
|
||||
|
||||
try {
|
||||
const provider = dns.getActiveProvider();
|
||||
const result = await provider.resolveRecords({
|
||||
domain, zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||
type: type || 'A'
|
||||
});
|
||||
|
||||
if (result.response?.records?.length > 0) {
|
||||
const ipAddresses = result.response.records
|
||||
.filter(r => r.type === (type || 'A'))
|
||||
.map(r => r.rData?.ipAddress || r.content || r.rData?.address)
|
||||
.filter(Boolean);
|
||||
success(res, { answer: ipAddresses });
|
||||
} else {
|
||||
throw new NotFoundError('No records found for domain');
|
||||
}
|
||||
} catch (error) {
|
||||
log.error('dns', 'Universal DNS resolve error', { error: error.message });
|
||||
errorResponse(res, safeErrorMessage(error), error.statusCode || 500);
|
||||
}
|
||||
}, 'dns-universal-resolve'));
|
||||
|
||||
// ===== LEGACY TECHNITIUM-SPECIFIC ROUTES (unchanged) =====
|
||||
router.delete('/record', asyncHandler(async (req, res) => {
|
||||
const { domain, type, token, server, ipAddress } = req.query;
|
||||
|
||||
@@ -139,6 +270,14 @@ module.exports = function({
|
||||
});
|
||||
|
||||
if (result.status === 'ok') {
|
||||
// Start DNS propagation verification in background
|
||||
if (dnsPropagationChecker && ip) {
|
||||
const fullDomain = domain;
|
||||
dnsPropagationChecker.startVerification(fullDomain, ip).catch(err => {
|
||||
log('DNS propagation check start failed:', err.message);
|
||||
});
|
||||
}
|
||||
|
||||
success(res, { message: `DNS record ${domain} -> ${ip} created` });
|
||||
} else {
|
||||
// Error handled by middleware
|
||||
@@ -194,8 +333,13 @@ module.exports = function({
|
||||
}
|
||||
}, 'dns-resolve'));
|
||||
|
||||
// GET /logs — Fetch DNS query logs from Technitium
|
||||
// GET /logs — Fetch DNS query logs (Technitium only)
|
||||
router.get('/logs', asyncHandler(async (req, res) => {
|
||||
// Capability gate: logs are provider-specific
|
||||
if (dns.supportsCapability && !dns.supportsCapability('logs')) {
|
||||
return success(res, { server: 'N/A', count: 0, logs: [], message: 'DNS logs not supported by current provider' });
|
||||
}
|
||||
|
||||
const { server, limit } = req.query;
|
||||
|
||||
if (!server) {
|
||||
@@ -239,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();
|
||||
@@ -409,7 +552,7 @@ module.exports = function({
|
||||
}
|
||||
}
|
||||
|
||||
return success(res, {
|
||||
return ok(res, {
|
||||
message: anySuccess ? 'Credentials saved for one or more servers' : 'All server credential tests failed',
|
||||
results
|
||||
});
|
||||
@@ -474,8 +617,13 @@ module.exports = function({
|
||||
success(res, { message: 'DNS credentials removed' });
|
||||
}, 'dns-credentials-delete'));
|
||||
|
||||
// POST /restart/:dnsId — Restart a DNS server (proxied through backend for auth)
|
||||
// POST /restart/:dnsId — Restart a DNS server (Technitium only)
|
||||
router.post('/restart/:dnsId', asyncHandler(async (req, res) => {
|
||||
// Capability gate
|
||||
if (dns.supportsCapability && !dns.supportsCapability('restart')) {
|
||||
return errorResponse(res, 'Server restart not supported by current DNS provider', 501);
|
||||
}
|
||||
|
||||
const { dnsId } = req.params;
|
||||
const serverInfo = siteConfig.dnsServers?.[dnsId];
|
||||
if (!serverInfo?.ip) {
|
||||
@@ -490,7 +638,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' });
|
||||
@@ -517,8 +665,13 @@ module.exports = function({
|
||||
}
|
||||
}, 'dns-refresh-token'));
|
||||
|
||||
// GET /check-update — Check for Technitium DNS server updates
|
||||
// GET /check-update — Check for DNS server updates (Technitium only)
|
||||
router.get('/check-update', asyncHandler(async (req, res) => {
|
||||
// Capability gate
|
||||
if (dns.supportsCapability && !dns.supportsCapability('update-check')) {
|
||||
return success(res, { updateAvailable: false, message: 'Update check not supported by current DNS provider' });
|
||||
}
|
||||
|
||||
try {
|
||||
const { server } = req.query;
|
||||
if (!server) {
|
||||
@@ -575,10 +728,13 @@ module.exports = function({
|
||||
}
|
||||
}, 'dns-check-update'));
|
||||
|
||||
// POST /update — Update Technitium DNS server
|
||||
// Note: Technitium v14+ has no installUpdate API. This endpoint checks for updates
|
||||
// and returns download info. The frontend handles showing update instructions.
|
||||
// POST /update — Update DNS server (Technitium only)
|
||||
router.post('/update', asyncHandler(async (req, res) => {
|
||||
// Capability gate
|
||||
if (dns.supportsCapability && !dns.supportsCapability('update-check')) {
|
||||
return errorResponse(res, 'Server update not supported by current DNS provider', 501);
|
||||
}
|
||||
|
||||
try {
|
||||
const { server } = req.query;
|
||||
if (!server) {
|
||||
@@ -640,5 +796,68 @@ module.exports = function({
|
||||
}
|
||||
}, 'dns-update'));
|
||||
|
||||
// ===== DNS PROPAGATION =====
|
||||
|
||||
// GET /propagation — Get all recent DNS propagation checks
|
||||
router.get('/propagation', asyncHandler(async (req, res) => {
|
||||
if (!dnsPropagationChecker) {
|
||||
return success(res, { verifications: [], message: 'DNS propagation checker not available' });
|
||||
}
|
||||
|
||||
// Cleanup old entries
|
||||
dnsPropagationChecker.cleanup();
|
||||
|
||||
const verifications = dnsPropagationChecker.getAllVerifications();
|
||||
success(res, { verifications });
|
||||
}, 'dns-propagation-all'));
|
||||
|
||||
// POST /propagation/verify — Manually trigger DNS propagation verification
|
||||
router.post('/propagation/verify', asyncHandler(async (req, res) => {
|
||||
if (!dnsPropagationChecker) {
|
||||
return errorResponse(res, 'DNS propagation checker not available', 503);
|
||||
}
|
||||
|
||||
const { domain, expectedIp } = req.body;
|
||||
|
||||
if (!domain || !expectedIp) {
|
||||
throw new ValidationError('domain and expectedIp are required');
|
||||
}
|
||||
|
||||
// Validate domain format
|
||||
if (!REGEX.DOMAIN.test(domain)) {
|
||||
throw new ValidationError('[DC-301] Invalid domain format');
|
||||
}
|
||||
|
||||
// Validate IP address
|
||||
const validatorLib = require('validator');
|
||||
if (!validatorLib.isIP(expectedIp)) {
|
||||
throw new ValidationError('[DC-210] Invalid IP address');
|
||||
}
|
||||
|
||||
const job = dnsPropagationChecker.startVerification(domain, expectedIp);
|
||||
success(res, {
|
||||
message: 'DNS propagation verification started',
|
||||
domain,
|
||||
expectedIp,
|
||||
status: job.status
|
||||
});
|
||||
}, 'dns-propagation-verify'));
|
||||
|
||||
// GET /propagation/:domain — Get propagation status for a specific domain
|
||||
router.get('/propagation/:domain', asyncHandler(async (req, res) => {
|
||||
if (!dnsPropagationChecker) {
|
||||
return success(res, { verification: null, message: 'DNS propagation checker not available' });
|
||||
}
|
||||
|
||||
const { domain } = req.params;
|
||||
const status = dnsPropagationChecker.getVerificationStatus(domain);
|
||||
|
||||
if (!status) {
|
||||
throw new NotFoundError(`No propagation check found for domain: ${domain}`);
|
||||
}
|
||||
|
||||
success(res, { verification: status });
|
||||
}, 'dns-propagation-domain'));
|
||||
|
||||
return router;
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const express = require('express');
|
||||
const { success } = require('../response-helpers');
|
||||
const { ValidationError } = require('../errors');
|
||||
const { success } = require('../src/utils/responses');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
|
||||
/**
|
||||
* Docker resources route factory (volumes, networks, disk usage)
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
const express = require('express');
|
||||
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 { exists } = require('../src/utilities/fs-helpers');
|
||||
const { paginate, parsePaginationParams } = require('../src/utilities/pagination');
|
||||
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
|
||||
@@ -8,10 +9,14 @@ const express = require('express');
|
||||
* @param {Object} deps.healthChecker - Health checker
|
||||
* @param {Object} deps.updateManager - Update manager
|
||||
* @param {Function} deps.logError - Error logging function
|
||||
* @param {Function} deps.ok - Success response helper
|
||||
* @param {Object} deps.dependencyManager - Dependency manager for restart chain events
|
||||
* @param {Object} deps.autoRestartManager - Auto-restart manager
|
||||
* @param {Object} deps.driftDetector - Config drift detector
|
||||
* @param {Object} deps.sslMonitor - SSL cert expiration monitor
|
||||
* @param {Object} deps.dnsPropagationChecker - DNS propagation checker
|
||||
* @returns {express.Router}
|
||||
*/
|
||||
module.exports = function({ resourceMonitor, healthChecker, updateManager, logError, ok }) {
|
||||
module.exports = function({ resourceMonitor, healthChecker, updateManager, logError, dependencyManager, autoRestartManager, driftDetector, sslMonitor, dnsPropagationChecker }) {
|
||||
const router = express.Router();
|
||||
const clients = new Set();
|
||||
|
||||
@@ -75,6 +80,48 @@ module.exports = function({ resourceMonitor, healthChecker, updateManager, logEr
|
||||
});
|
||||
}
|
||||
|
||||
// Dependency manager events
|
||||
if (dependencyManager) {
|
||||
dependencyManager.on('dependency-restart-start', (data) => {
|
||||
broadcast('dependency-restart-start', data);
|
||||
});
|
||||
dependencyManager.on('dependency-restart-progress', (data) => {
|
||||
broadcast('dependency-restart-progress', data);
|
||||
});
|
||||
dependencyManager.on('dependency-restart-complete', (data) => {
|
||||
broadcast('dependency-restart-complete', data);
|
||||
});
|
||||
dependencyManager.on('dependency-restart-failed', (data) => {
|
||||
broadcast('dependency-restart-failed', data);
|
||||
});
|
||||
}
|
||||
|
||||
// Auto-restart manager events
|
||||
if (autoRestartManager) {
|
||||
autoRestartManager.on('auto-restart-attempt', (data) => broadcast('auto-restart-attempt', data));
|
||||
autoRestartManager.on('auto-restart-success', (data) => broadcast('auto-restart-success', data));
|
||||
autoRestartManager.on('auto-restart-failed', (data) => broadcast('auto-restart-failed', data));
|
||||
autoRestartManager.on('auto-restart-max-reached', (data) => broadcast('auto-restart-max-reached', data));
|
||||
}
|
||||
|
||||
// Config drift detector events
|
||||
if (driftDetector) {
|
||||
driftDetector.on('drift-detected', (data) => broadcast('drift-detected', data));
|
||||
}
|
||||
|
||||
// SSL monitor events
|
||||
if (sslMonitor) {
|
||||
sslMonitor.on('cert-expiring', (data) => broadcast('cert-expiring', data));
|
||||
sslMonitor.on('cert-critical', (data) => broadcast('cert-critical', data));
|
||||
}
|
||||
|
||||
// DNS propagation checker events
|
||||
if (dnsPropagationChecker) {
|
||||
dnsPropagationChecker.on('propagation-check', (data) => broadcast('dns-propagation-check', data));
|
||||
dnsPropagationChecker.on('propagation-complete', (data) => broadcast('dns-propagation-complete', data));
|
||||
dnsPropagationChecker.on('propagation-timeout', (data) => broadcast('dns-propagation-timeout', data));
|
||||
}
|
||||
|
||||
// SSE endpoint
|
||||
router.get('/stream', (req, res) => {
|
||||
res.writeHead(200, {
|
||||
|
||||
@@ -2,13 +2,13 @@ const express = require('express');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { execSync } = require('child_process');
|
||||
const { TIMEOUTS } = require('../constants');
|
||||
const { exists } = require('../fs-helpers');
|
||||
const { paginate, parsePaginationParams } = require('../pagination');
|
||||
const { TIMEOUTS } = require('../src/utilities/constants');
|
||||
const { exists } = require('../src/utilities/fs-helpers');
|
||||
const { paginate, parsePaginationParams } = require('../src/utilities/pagination');
|
||||
const platformPaths = require('../platform-paths');
|
||||
const { resolveServiceUrl } = require('../url-resolver');
|
||||
const { success, error: errorResponse } = require('../response-helpers');
|
||||
const { ValidationError } = require('../errors');
|
||||
const { resolveServiceUrl } = require('../src/utilities/url-resolver');
|
||||
const { success, error: errorResponse, errorResponse: sendError, ok, notFound } = require('../src/utils/responses');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
|
||||
/**
|
||||
* Health routes factory
|
||||
@@ -190,7 +190,7 @@ module.exports = function({
|
||||
|
||||
// Load service config
|
||||
if (!await exists(SERVICES_FILE)) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError('Services file');
|
||||
}
|
||||
|
||||
@@ -199,7 +199,7 @@ module.exports = function({
|
||||
const service = services.find(s => (s.id || s.name?.toLowerCase()) === serviceId);
|
||||
|
||||
if (!service) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError('Service');
|
||||
}
|
||||
|
||||
@@ -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,36 +282,32 @@ 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'));
|
||||
|
||||
@@ -349,7 +341,7 @@ module.exports = function({
|
||||
const hours = parseInt(req.query.hours) || 24;
|
||||
const stats = healthChecker.getServiceStats(req.params.serviceId, hours);
|
||||
if (!stats) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError('Service');
|
||||
}
|
||||
success(res, { stats });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const express = require('express');
|
||||
const { success, error: errorResponse } = require('../response-helpers');
|
||||
const { ValidationError } = require('../errors');
|
||||
const { success, error: errorResponse } = require('../src/utils/responses');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
|
||||
/**
|
||||
* License routes factory
|
||||
|
||||
@@ -2,9 +2,10 @@ const express = require('express');
|
||||
const fs = require('fs');
|
||||
const fsp = require('fs').promises;
|
||||
const path = require('path');
|
||||
const { exists } = require('../fs-helpers');
|
||||
const { paginate, parsePaginationParams } = require('../pagination');
|
||||
const { NotFoundError, ValidationError, ForbiddenError } = require('../errors');
|
||||
const { exists } = require('../src/utilities/fs-helpers');
|
||||
const { paginate, parsePaginationParams } = require('../src/utilities/pagination');
|
||||
const { NotFoundError, ValidationError, ForbiddenError } = require('../src/utilities/errors');
|
||||
const { ok } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Logs route factory
|
||||
@@ -47,7 +48,7 @@ module.exports = function({ asyncHandler, ok, docker, logDigest, dockerMaintenan
|
||||
info = await container.inspect();
|
||||
} catch (err) {
|
||||
if (err.statusCode === 404 || (err.message && err.message.includes('no such container'))) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError(`Container ${containerId}`);
|
||||
}
|
||||
throw err;
|
||||
@@ -96,7 +97,7 @@ module.exports = function({ asyncHandler, ok, docker, logDigest, dockerMaintenan
|
||||
await container.inspect();
|
||||
} catch (err) {
|
||||
if (err.statusCode === 404 || (err.message && err.message.includes('no such container'))) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError(`Container ${containerId}`);
|
||||
}
|
||||
throw err;
|
||||
@@ -231,7 +232,7 @@ module.exports = function({ asyncHandler, ok, docker, logDigest, dockerMaintenan
|
||||
try {
|
||||
resolvedPath = await fsp.realpath(normalizedPath);
|
||||
} catch {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError('Log file');
|
||||
}
|
||||
|
||||
@@ -246,7 +247,7 @@ module.exports = function({ asyncHandler, ok, docker, logDigest, dockerMaintenan
|
||||
}
|
||||
|
||||
if (!await exists(resolvedPath)) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError('Log file');
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const express = require('express');
|
||||
const { success } = require('../response-helpers');
|
||||
const { success } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Monitoring routes factory
|
||||
@@ -38,7 +38,7 @@ module.exports = function({ resourceMonitor, docker, asyncHandler, log, notifica
|
||||
router.get('/monitoring/stats/:containerId', asyncHandler(async (req, res) => {
|
||||
const stats = resourceMonitor.getCurrentStats(req.params.containerId);
|
||||
if (!stats) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError('Container');
|
||||
}
|
||||
success(res, { stats });
|
||||
@@ -54,7 +54,7 @@ module.exports = function({ resourceMonitor, docker, asyncHandler, log, notifica
|
||||
const startTime = parseInt(req.query.startTime, 10);
|
||||
const endTime = parseInt(req.query.endTime, 10);
|
||||
if (Number.isNaN(startTime) || Number.isNaN(endTime) || startTime >= endTime) {
|
||||
const { ValidationError } = require('../errors');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
throw new ValidationError('Invalid startTime/endTime');
|
||||
}
|
||||
const result = resourceMonitor.getHistoryByRange(containerId, startTime, endTime);
|
||||
@@ -73,7 +73,7 @@ module.exports = function({ resourceMonitor, docker, asyncHandler, log, notifica
|
||||
const hours = parseInt(req.query.hours) || 24;
|
||||
const aggregated = resourceMonitor.getAggregatedStats(req.params.containerId, hours);
|
||||
if (!aggregated) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError('Monitoring data');
|
||||
}
|
||||
success(res, { aggregated, hours });
|
||||
@@ -91,7 +91,7 @@ module.exports = function({ resourceMonitor, docker, asyncHandler, log, notifica
|
||||
router.post('/monitoring/alerts/config', asyncHandler(async (req, res) => {
|
||||
const { configs } = req.body;
|
||||
if (!configs || typeof configs !== 'object') {
|
||||
const { ValidationError } = require('../errors');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
throw new ValidationError('configs object required');
|
||||
}
|
||||
for (const [containerId, config] of Object.entries(configs)) {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
const express = require('express');
|
||||
const { validateURL, validateToken } = require('../input-validator');
|
||||
const { validateURL, validateToken } = require('../src/security/input-validator');
|
||||
const validatorLib = require('validator');
|
||||
const { paginate, parsePaginationParams } = require('../pagination');
|
||||
const { ValidationError } = require('../errors');
|
||||
const { paginate, parsePaginationParams } = require('../src/utilities/pagination');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
const { ok, successMessage } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Notifications route factory
|
||||
@@ -151,7 +152,7 @@ module.exports = function({ notification, asyncHandler, ok }) {
|
||||
}
|
||||
|
||||
await notification.saveConfig();
|
||||
ok(res, { message: 'Notification config updated' });
|
||||
successMessage(res, 'Notification config updated');
|
||||
}, 'notifications-config-update'));
|
||||
|
||||
// POST /test — Test notification delivery
|
||||
@@ -206,7 +207,7 @@ module.exports = function({ notification, asyncHandler, ok }) {
|
||||
// DELETE /history — Clear notification history
|
||||
router.delete('/history', asyncHandler(async (req, res) => {
|
||||
notification.clearHistory();
|
||||
ok(res, { message: 'Notification history cleared' });
|
||||
successMessage(res, 'Notification history cleared');
|
||||
}, 'notifications-history-clear'));
|
||||
|
||||
// POST /health-check — Manually trigger health check
|
||||
@@ -223,7 +224,7 @@ module.exports = function({ notification, asyncHandler, ok }) {
|
||||
router.get('/status', asyncHandler(async (req, res) => {
|
||||
const notificationConfig = notification.getConfig();
|
||||
const providers = notificationConfig.providers || {};
|
||||
|
||||
|
||||
ok(res, {
|
||||
enabled: notificationConfig.enabled,
|
||||
providers: {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const express = require('express');
|
||||
const http = require('http');
|
||||
const { ok, errorResponse, notFound, conflict } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* OpenClaw management routes
|
||||
@@ -94,8 +95,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 {
|
||||
@@ -105,8 +106,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'); });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,7 +150,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 +171,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
|
||||
@@ -206,7 +207,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);
|
||||
}
|
||||
}));
|
||||
|
||||
@@ -214,7 +215,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);
|
||||
@@ -228,7 +229,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);
|
||||
@@ -242,7 +243,7 @@ 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);
|
||||
@@ -252,7 +253,7 @@ module.exports = function openClawRoutes(ctx) {
|
||||
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);
|
||||
}
|
||||
}));
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
const express = require('express');
|
||||
const { ValidationError } = require('../../errors');
|
||||
const { ValidationError } = require('../../../src/utilities/errors');
|
||||
const crypto = require('crypto');
|
||||
const { DOCKER } = require('../../constants');
|
||||
const { DOCKER } = require('../../../src/utilities/constants');
|
||||
const { ok } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Recipes deployment routes factory
|
||||
@@ -27,7 +28,7 @@ module.exports = function({ docker, credentialManager: _credentialManager, servi
|
||||
// eslint-disable-next-line complexity
|
||||
router.post('/deploy', asyncHandler(async (req, res) => {
|
||||
const { recipeId, config } = req.body;
|
||||
const { RECIPE_TEMPLATES } = require('../../recipe-templates');
|
||||
const { RECIPE_TEMPLATES } = require('../../../src/recipes/recipe-templates');
|
||||
|
||||
const recipe = RECIPE_TEMPLATES[recipeId];
|
||||
if (!recipe) throw new ValidationError('Invalid recipe template', 'recipeId');
|
||||
@@ -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 });
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
const express = require('express');
|
||||
const deployRoutes = require('./deploy');
|
||||
const manageRoutes = require('./manage');
|
||||
const { NotFoundError } = require('../../errors');
|
||||
const { NotFoundError } = require('../../../src/utilities/errors');
|
||||
const { ok } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Recipes routes aggregator
|
||||
@@ -31,7 +32,7 @@ module.exports = function(ctx) {
|
||||
|
||||
// GET /api/recipes/templates — list all recipe templates
|
||||
router.get('/templates', deps.asyncHandler(async (req, res) => {
|
||||
const { RECIPE_TEMPLATES, RECIPE_CATEGORIES } = require('../../recipe-templates');
|
||||
const { RECIPE_TEMPLATES, RECIPE_CATEGORIES } = require('../../../src/recipes/recipe-templates');
|
||||
const templates = Object.entries(RECIPE_TEMPLATES).map(([id, recipe]) => ({
|
||||
id,
|
||||
name: recipe.name,
|
||||
@@ -55,16 +56,16 @@ 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
|
||||
router.get('/templates/:recipeId', deps.asyncHandler(async (req, res) => {
|
||||
const { RECIPE_TEMPLATES } = require('../../recipe-templates');
|
||||
const { RECIPE_TEMPLATES } = require('../../../src/recipes/recipe-templates');
|
||||
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 { DOCKER } = require('../../../src/utilities/constants');
|
||||
const { NotFoundError } = require('../../../src/utilities/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 ===
|
||||
@@ -268,7 +269,7 @@ module.exports = function({ servicesStateManager, asyncHandler, log, docker, not
|
||||
* Find all Docker containers belonging to a recipe by label
|
||||
*/
|
||||
async function findRecipeContainers(recipeId) {
|
||||
const { RECIPE_TEMPLATES } = require('../../recipe-templates');
|
||||
const { RECIPE_TEMPLATES } = require('../../../src/recipes/recipe-templates');
|
||||
const recipe = RECIPE_TEMPLATES[recipeId];
|
||||
const recipeLabel = recipe
|
||||
? recipe.name.toLowerCase().replace(/\s+/g, '-')
|
||||
@@ -292,7 +293,7 @@ module.exports = function({ servicesStateManager, asyncHandler, log, docker, not
|
||||
* Find recipe ID by its label (name slug)
|
||||
*/
|
||||
function findRecipeIdByLabel(label) {
|
||||
const { RECIPE_TEMPLATES } = require('../../recipe-templates');
|
||||
const { RECIPE_TEMPLATES } = require('../../../src/recipes/recipe-templates');
|
||||
for (const [id, recipe] of Object.entries(RECIPE_TEMPLATES)) {
|
||||
if (recipe.name.toLowerCase().replace(/\s+/g, '-') === label) {
|
||||
return id;
|
||||
|
||||
@@ -4,13 +4,14 @@ const http = require('http');
|
||||
const https = require('https');
|
||||
const tls = require('tls');
|
||||
const validatorLib = require('validator');
|
||||
const { APP, REGEX, TIMEOUTS } = require('../constants');
|
||||
const { validateServiceConfig, isValidPort } = require('../input-validator');
|
||||
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 { APP, REGEX, TIMEOUTS } = require('../src/utilities/constants');
|
||||
const { validateServiceConfig, isValidPort } = require('../src/security/input-validator');
|
||||
const { exists } = require('../src/utilities/fs-helpers');
|
||||
const { paginate, parsePaginationParams } = require('../src/utilities/pagination');
|
||||
const { ValidationError, NotFoundError, ConflictError } = require('../src/utilities/errors');
|
||||
const { resolveServiceUrl } = require('../src/utilities/url-resolver');
|
||||
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,14 +368,14 @@ 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'));
|
||||
|
||||
// Add a new service
|
||||
router.post('/services', asyncHandler(async (req, res) => {
|
||||
try {
|
||||
const { id, name, logo } = req.body;
|
||||
const { id, name, logo, category, containerId, port, ip, tailscaleOnly } = req.body;
|
||||
|
||||
if (!id || !name) {
|
||||
throw new ValidationError('id and name are required');
|
||||
@@ -391,7 +394,14 @@ module.exports = function({
|
||||
throw new ConflictError(`Service "${id}" already exists`, id);
|
||||
}
|
||||
|
||||
services.push({ id, name, logo: logo || `/assets/${id}.png` });
|
||||
const newService = { id, name, logo: logo || `/assets/${id}.png` };
|
||||
// Persist optional metadata fields if provided
|
||||
if (category) newService.category = category;
|
||||
if (containerId) newService.containerId = containerId;
|
||||
if (port) newService.port = port;
|
||||
if (ip) newService.ip = ip;
|
||||
if (typeof tailscaleOnly === 'boolean') newService.tailscaleOnly = tailscaleOnly;
|
||||
services.push(newService);
|
||||
return services;
|
||||
});
|
||||
|
||||
@@ -513,9 +523,8 @@ module.exports = function({
|
||||
|
||||
if (oldSubdomain !== newSubdomain) {
|
||||
try {
|
||||
const dnsToken = dns.getToken();
|
||||
await dns.call(siteConfig.dnsServerIp, '/api/zones/records/delete', { token: dnsToken, domain: oldDomain, type: 'A' });
|
||||
await dns.createRecord(newSubdomain, ip || 'localhost');
|
||||
await dns.universalDeleteRecord(oldDomain);
|
||||
await dns.universalCreateRecord(newSubdomain, ip || 'localhost');
|
||||
results.dns = 'updated';
|
||||
} catch (e) {
|
||||
results.dns = `failed: ${e.message}`;
|
||||
@@ -542,6 +551,8 @@ module.exports = function({
|
||||
};
|
||||
if (name) services[serviceIndex].name = name;
|
||||
if (logo) services[serviceIndex].logo = logo;
|
||||
// Allow category update via update endpoint too (optional body field)
|
||||
if (req.body.category !== undefined) services[serviceIndex].category = req.body.category || undefined;
|
||||
results.services = 'updated';
|
||||
} else {
|
||||
results.services = 'not found';
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
const express = require('express');
|
||||
const fs = require('fs');
|
||||
const { CADDY, REGEX, LIMITS } = require('../constants');
|
||||
const { ValidationError, ConflictError, NotFoundError } = require('../errors');
|
||||
const { validateURL } = require('../input-validator');
|
||||
const { CADDY, REGEX, LIMITS } = require('../src/utilities/constants');
|
||||
const { ValidationError, ConflictError, NotFoundError } = require('../src/utilities/errors');
|
||||
const { validateURL } = require('../src/security/input-validator');
|
||||
const { ok, successMessage } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Sites route factory
|
||||
@@ -49,7 +50,7 @@ module.exports = function({ asyncHandler, ok, caddy, dns, fetchT, buildDomain, a
|
||||
throw new Error('Caddy reload failed. Check server logs for details.');
|
||||
}
|
||||
|
||||
ok(res, { 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, ok, caddy, dns, fetchT, buildDomain, a
|
||||
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, ok, caddy, dns, fetchT, buildDomain, a
|
||||
throw new NotFoundError(`Site block for "" in Caddyfile`);
|
||||
}
|
||||
|
||||
ok(res, { 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, ok, caddy, dns, fetchT, buildDomain, a
|
||||
result.rolledBack ? { note: 'Caddyfile was rolled back to previous state' } : {});
|
||||
}
|
||||
|
||||
ok(res, { 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
|
||||
@@ -205,7 +206,7 @@ module.exports = function({ asyncHandler, ok, caddy, dns, fetchT, buildDomain, a
|
||||
|
||||
if (createDns) {
|
||||
try {
|
||||
await dns.createRecord(subdomain, siteConfig.dnsServerIp);
|
||||
await dns.universalCreateRecord(subdomain, siteConfig.dnsServerIp);
|
||||
log.info('dns', 'DNS record created for external proxy', { domain, ip: siteConfig.dnsServerIp });
|
||||
} catch (dnsError) {
|
||||
dnsWarning = `DNS creation failed: ${dnsError.message}. You may need to create the DNS record manually.`;
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* SSL Monitor Routes
|
||||
* REST API endpoints for SSL certificate monitoring.
|
||||
*
|
||||
* @module routes/ssl-monitor
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const { success, error: errorResponse, notFound } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* SSL Monitor route factory
|
||||
* @param {Object} deps - Explicit dependencies
|
||||
* @param {Object} deps.sslMonitor - SSLMonitor instance
|
||||
* @param {Function} deps.asyncHandler - Async route handler wrapper
|
||||
* @param {Function} deps.logError - Error logging function
|
||||
* @returns {express.Router}
|
||||
*/
|
||||
module.exports = function({ sslMonitor, asyncHandler, logError }) {
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* GET /ssl/certificates
|
||||
* Get all SSL certificate statuses
|
||||
*/
|
||||
router.get('/certificates', asyncHandler(async (req, res) => {
|
||||
const status = sslMonitor.getStatus();
|
||||
success(res, { certificates: status });
|
||||
}, 'ssl-certificates'));
|
||||
|
||||
/**
|
||||
* GET /ssl/certificates/:serviceId
|
||||
* Get SSL certificate status for a specific service
|
||||
*/
|
||||
router.get('/certificates/:serviceId', asyncHandler(async (req, res) => {
|
||||
const { serviceId } = req.params;
|
||||
const certStatus = sslMonitor.getServiceCertStatus(serviceId);
|
||||
|
||||
if (!certStatus) {
|
||||
return notFound(res, `No SSL certificate status found for service: ${serviceId}`);
|
||||
}
|
||||
|
||||
success(res, { certificate: certStatus });
|
||||
}, 'ssl-certificate-service'));
|
||||
|
||||
/**
|
||||
* POST /ssl/check
|
||||
* Trigger an on-demand check of all SSL certificates
|
||||
*/
|
||||
router.post('/check', asyncHandler(async (req, res) => {
|
||||
const results = await sslMonitor.checkAll();
|
||||
success(res, { certificates: results, message: 'SSL check completed' });
|
||||
}, 'ssl-check-all'));
|
||||
|
||||
/**
|
||||
* POST /ssl/check/:serviceId
|
||||
* Check the SSL certificate for a specific service
|
||||
*/
|
||||
router.post('/check/:serviceId', asyncHandler(async (req, res) => {
|
||||
const { serviceId } = req.params;
|
||||
|
||||
// Look up the existing cert status to find the hostname
|
||||
const existingCert = sslMonitor.getServiceCertStatus(serviceId);
|
||||
if (!existingCert) {
|
||||
return notFound(res, `No HTTPS URL found for service: ${serviceId}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await sslMonitor.checkCert(existingCert.hostname, existingCert.port);
|
||||
success(res, { certificate: { ...result, serviceId } });
|
||||
} catch (err) {
|
||||
errorResponse(res, `Failed to check SSL certificate: ${err.message}`, 500);
|
||||
}
|
||||
}, 'ssl-check-service'));
|
||||
|
||||
/**
|
||||
* GET /ssl/config
|
||||
* Get current SSL monitoring configuration
|
||||
*/
|
||||
router.get('/config', asyncHandler(async (req, res) => {
|
||||
const config = sslMonitor.getConfig();
|
||||
success(res, { config });
|
||||
}, 'ssl-config-get'));
|
||||
|
||||
/**
|
||||
* POST /ssl/config
|
||||
* Update SSL monitoring configuration
|
||||
* Body: { enabled: boolean, intervalMs: number }
|
||||
*/
|
||||
router.post('/config', asyncHandler(async (req, res) => {
|
||||
const { enabled, intervalMs } = req.body;
|
||||
|
||||
// Validate inputs
|
||||
if (enabled !== undefined && typeof enabled !== 'boolean') {
|
||||
return errorResponse(res, 'enabled must be a boolean', 400);
|
||||
}
|
||||
if (intervalMs !== undefined) {
|
||||
if (typeof intervalMs !== 'number' || intervalMs < 60000) {
|
||||
return errorResponse(res, 'intervalMs must be a number >= 60000 (1 minute)', 400);
|
||||
}
|
||||
}
|
||||
|
||||
const updates = {};
|
||||
if (enabled !== undefined) updates.enabled = enabled;
|
||||
if (intervalMs !== undefined) updates.intervalMs = intervalMs;
|
||||
|
||||
sslMonitor.updateConfig(updates);
|
||||
const config = sslMonitor.getConfig();
|
||||
success(res, { config, message: 'SSL monitoring config updated' });
|
||||
}, 'ssl-config-update'));
|
||||
|
||||
return router;
|
||||
};
|
||||
@@ -1,7 +1,9 @@
|
||||
const express = require('express');
|
||||
const { TAILSCALE } = require('../constants');
|
||||
const { exists } = require('../fs-helpers');
|
||||
const { ValidationError, NotFoundError: _NotFoundError } = require('../errors');
|
||||
const fs = require('fs');
|
||||
const { TAILSCALE } = require('../src/utilities/constants');
|
||||
const { exists } = require('../src/utilities/fs-helpers');
|
||||
const { ValidationError, NotFoundError } = require('../src/utilities/errors');
|
||||
const { ok, successMessage, unauthorized } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Tailscale route factory
|
||||
@@ -156,7 +158,7 @@ module.exports = function({
|
||||
const match = content.match(blockRegex);
|
||||
|
||||
if (!match) {
|
||||
const { NotFoundError } = require('../errors');
|
||||
const { NotFoundError } = require('../src/utilities/errors');
|
||||
throw new NotFoundError(`Service ${domain} in Caddyfile`);
|
||||
}
|
||||
|
||||
@@ -265,7 +267,7 @@ module.exports = function({
|
||||
|
||||
tailscale.stopSync();
|
||||
|
||||
ok(res, { message: 'Tailscale OAuth credentials removed' });
|
||||
successMessage(res, 'Tailscale OAuth credentials removed');
|
||||
}, 'tailscale-oauth-delete'));
|
||||
|
||||
// Get enriched device list from Tailscale API
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
const express = require('express');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { success } = require('../response-helpers');
|
||||
const { ValidationError, NotFoundError } = require('../errors');
|
||||
const { success } = require('../src/utils/responses');
|
||||
const { ValidationError, NotFoundError } = require('../src/utilities/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 { paginate, parsePaginationParams } = require('../src/utilities/pagination');
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
const { ok, successMessage } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Updates route factory
|
||||
@@ -41,7 +42,7 @@ module.exports = function({ updateManager, selfUpdater, asyncHandler, logError,
|
||||
// Rollback update
|
||||
router.post('/updates/rollback/:containerId', asyncHandler(async (req, res) => {
|
||||
await updateManager.rollbackUpdate(req.params.containerId);
|
||||
ok(res, { message: 'Rollback completed' });
|
||||
successMessage(res, 'Rollback completed');
|
||||
}, 'updates-rollback'));
|
||||
|
||||
// Get update history
|
||||
@@ -57,7 +58,7 @@ module.exports = function({ updateManager, selfUpdater, asyncHandler, logError,
|
||||
// Configure auto-update
|
||||
router.post('/updates/auto-update/:containerId', asyncHandler(async (req, res) => {
|
||||
updateManager.configureAutoUpdate(req.params.containerId, req.body);
|
||||
ok(res, { message: 'Auto-update configured' });
|
||||
successMessage(res, 'Auto-update configured');
|
||||
}, 'updates-auto-update'));
|
||||
|
||||
// Get auto-update configuration
|
||||
@@ -87,14 +88,14 @@ module.exports = function({ updateManager, selfUpdater, asyncHandler, logError,
|
||||
// Check for DashCaddy update
|
||||
router.get('/system/update-check', asyncHandler(async (req, res) => {
|
||||
const result = await selfUpdater.checkForUpdate();
|
||||
ok(res, { ...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 ok(res, { 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
|
||||
@@ -135,7 +136,7 @@ module.exports = function({ updateManager, selfUpdater, asyncHandler, logError,
|
||||
return res.status(401).json({ success: false, error: 'Invalid notify secret' });
|
||||
}
|
||||
const result = selfUpdater.notifyAndApply('http-notify');
|
||||
ok(res, { ...result });
|
||||
ok(res, result);
|
||||
}, 'system-update-notify'));
|
||||
|
||||
// Get update status
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const express = require('express');
|
||||
const { ok } = require('../src/utils/responses');
|
||||
|
||||
/**
|
||||
* Workflows routes factory
|
||||
@@ -27,14 +28,14 @@ module.exports = function({ workflowEngine, licenseManager, asyncHandler, ok })
|
||||
router.post('/workflows/:workflowId/enable', asyncHandler(async (req, res) => {
|
||||
const { workflowId } = req.params;
|
||||
const result = workflowEngine.setWorkflowEnabled(workflowId, true);
|
||||
ok(res, { ...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);
|
||||
ok(res, { ...result });
|
||||
ok(res, result);
|
||||
}, 'workflows-disable'));
|
||||
|
||||
// Manually trigger a workflow
|
||||
|
||||
Reference in New Issue
Block a user