DC-059: Joi validation middleware + schemas for destructive routes
[grade=B] - New src/utilities/validate.js: validateBody(schema) middleware + 9 schemas (backupConfigUpdate, backupScheduleCreate, backupRestore, backupRestoreFile, appDeploy, appRestore, appRevert, assetUpload, logoUpload) - Uses Joi's authoritative CIDR validator (rejects malformed IPv6 like ::::/64 that the previous hex/colon regex would have accepted) - appDeploy.config uses .unknown(true) for forward-compat with template-specific fields (sslType, dnsType, plexClaimToken, etc.) — preserves fields the live frontend posts, prevents a behavioural regression - appRestore uses Joi.any().custom() so the empty-body semantics hold under middleware stripUnknown (default) — body with extra keys now rejected - Wired into 8 destructive routes: backups schedule/restore/config, apps deploy/restore/revert, assets upload/logo - Duplicate legacy POST /backups/schedule handler (line 519) marked LEGACY with TODO removal note (Express only matches first registration; this handler is unreachable under normal routing) - Removed redundant manual appId check in /backups/schedule (Joi schema enforces it) - Removed unused 'mime' destructure in /assets/favicon (decodeImageData validates MIME internally) - 41 unit tests covering every exported schema + middleware integration - 1539/1539 Jest tests pass, zero new ESLint warnings
This commit is contained in:
@@ -140,6 +140,34 @@ describe('schemas.appDeploy', () => {
|
|||||||
expect(error).toBeDefined();
|
expect(error).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('rejects malformed IPv6 CIDR (regression: hex/colon regex was permissive)', () => {
|
||||||
|
// Old regex /^[0-9a-fA-F:]+\/(\d{1,3})$/ accepted these; Joi's authoritative
|
||||||
|
// CIDR validator must reject them.
|
||||||
|
const { error: e1 } = schemas.appDeploy.validate({
|
||||||
|
appId: 'plex',
|
||||||
|
config: { subdomain: 'plex', allowedIPs: ['::::/64'] },
|
||||||
|
});
|
||||||
|
expect(e1).toBeDefined();
|
||||||
|
const { error: e2 } = schemas.appDeploy.validate({
|
||||||
|
appId: 'plex',
|
||||||
|
config: { subdomain: 'plex', allowedIPs: ['zzzz:::/64'] },
|
||||||
|
});
|
||||||
|
expect(e2).toBeDefined();
|
||||||
|
const { error: e3 } = schemas.appDeploy.validate({
|
||||||
|
appId: 'plex',
|
||||||
|
config: { subdomain: 'plex', allowedIPs: ['not-an-ip'] },
|
||||||
|
});
|
||||||
|
expect(e3).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts valid IPv6 CIDR', () => {
|
||||||
|
const { error } = schemas.appDeploy.validate({
|
||||||
|
appId: 'plex',
|
||||||
|
config: { subdomain: 'plex', allowedIPs: ['2001:db8::/32'] },
|
||||||
|
});
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
test('accepts valid customVolumes objects', () => {
|
test('accepts valid customVolumes objects', () => {
|
||||||
const { error } = schemas.appDeploy.validate({
|
const { error } = schemas.appDeploy.validate({
|
||||||
appId: 'plex',
|
appId: 'plex',
|
||||||
@@ -151,13 +179,37 @@ describe('schemas.appDeploy', () => {
|
|||||||
expect(error).toBeUndefined();
|
expect(error).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('strips unknown keys in config', () => {
|
test('preserves unknown template-specific config fields (forward-compat)', () => {
|
||||||
|
// appDeploy.config uses .unknown(true) so future template-specific fields
|
||||||
|
// (e.g. a new app that posts `apiKey`, `databaseType`, ...) survive validation.
|
||||||
const { error, value } = schemas.appDeploy.validate({
|
const { error, value } = schemas.appDeploy.validate({
|
||||||
appId: 'plex',
|
appId: 'plex',
|
||||||
config: { subdomain: 'plex', isAdmin: true },
|
config: {
|
||||||
}, { stripUnknown: true });
|
subdomain: 'plex',
|
||||||
|
aFutureTemplateField: 'xyz',
|
||||||
|
apiKey: 'secret',
|
||||||
|
},
|
||||||
|
});
|
||||||
expect(error).toBeUndefined();
|
expect(error).toBeUndefined();
|
||||||
expect(value.config).not.toHaveProperty('isAdmin');
|
expect(value.config).toHaveProperty('aFutureTemplateField', 'xyz');
|
||||||
|
expect(value.config).toHaveProperty('apiKey', 'secret');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('preserves template-specific config fields (sslType, dnsType, plexClaimToken)', () => {
|
||||||
|
// The frontend posts these — they must survive validation or deployments break.
|
||||||
|
const { error, value } = schemas.appDeploy.validate({
|
||||||
|
appId: 'plex',
|
||||||
|
config: {
|
||||||
|
subdomain: 'plex',
|
||||||
|
sslType: 'self-signed',
|
||||||
|
dnsType: 'private',
|
||||||
|
plexClaimToken: 'claim-abc-123',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
expect(value.config).toHaveProperty('sslType', 'self-signed');
|
||||||
|
expect(value.config).toHaveProperty('dnsType', 'private');
|
||||||
|
expect(value.config).toHaveProperty('plexClaimToken', 'claim-abc-123');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -201,3 +253,118 @@ describe('schemas.backupRestoreFile', () => {
|
|||||||
expect(value).not.toHaveProperty('malicious');
|
expect(value).not.toHaveProperty('malicious');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('schemas.backupRestore', () => {
|
||||||
|
test('accepts empty body (all fields optional)', () => {
|
||||||
|
const { error, value } = schemas.backupRestore.validate({});
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
expect(value).toEqual({});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts known control flags', () => {
|
||||||
|
const { error } = schemas.backupRestore.validate({
|
||||||
|
encryptionKey: 'secret',
|
||||||
|
restartContainers: true,
|
||||||
|
services: true,
|
||||||
|
config: true,
|
||||||
|
credentials: true,
|
||||||
|
volumes: true,
|
||||||
|
});
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('strips unknown keys', () => {
|
||||||
|
const { error, value } = schemas.backupRestore.validate({
|
||||||
|
services: true,
|
||||||
|
shellCommand: 'rm -rf /',
|
||||||
|
}, { stripUnknown: true });
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
expect(value).not.toHaveProperty('shellCommand');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('schemas.appRestore', () => {
|
||||||
|
test('accepts empty body via middleware', () => {
|
||||||
|
const req = mockReq({});
|
||||||
|
const next = jest.fn();
|
||||||
|
validateBody(schemas.appRestore)(req, {}, next);
|
||||||
|
expect(next).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects body with any key via middleware', () => {
|
||||||
|
const req = mockReq({ filename: 'backup.tar' });
|
||||||
|
expect(() => validateBody(schemas.appRestore)(req, {}, jest.fn())).toThrow(/empty/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects non-object body via middleware', () => {
|
||||||
|
const req = mockReq('just a string');
|
||||||
|
expect(() => validateBody(schemas.appRestore)(req, {}, jest.fn())).toThrow(/empty/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('schemas.appRevert', () => {
|
||||||
|
test('accepts empty body', () => {
|
||||||
|
const { error } = schemas.appRevert.validate({});
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts optional encryption key + restart flag', () => {
|
||||||
|
const { error } = schemas.appRevert.validate({
|
||||||
|
encryptionKey: 'secret',
|
||||||
|
restartContainers: true,
|
||||||
|
});
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('strips unknown keys (no shell injection vector)', () => {
|
||||||
|
const { error, value } = schemas.appRevert.validate({
|
||||||
|
encryptionKey: 'secret',
|
||||||
|
path: '/etc/passwd',
|
||||||
|
shellCommand: 'rm -rf /',
|
||||||
|
}, { stripUnknown: true });
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
expect(value).not.toHaveProperty('path');
|
||||||
|
expect(value).not.toHaveProperty('shellCommand');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('schemas.logoUpload', () => {
|
||||||
|
test('requires at least one field', () => {
|
||||||
|
const { error } = schemas.logoUpload.validate({});
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts single data field', () => {
|
||||||
|
const { error } = schemas.logoUpload.validate({ data: 'data:image/png;base64,abc' });
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts dataDark + dataLight pair', () => {
|
||||||
|
const { error } = schemas.logoUpload.validate({
|
||||||
|
dataDark: 'data:image/png;base64,dark',
|
||||||
|
dataLight: 'data:image/png;base64,light',
|
||||||
|
});
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts position enum', () => {
|
||||||
|
const { error } = schemas.logoUpload.validate({
|
||||||
|
data: 'data:image/png;base64,abc',
|
||||||
|
position: 'center',
|
||||||
|
});
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects invalid position', () => {
|
||||||
|
const { error } = schemas.logoUpload.validate({
|
||||||
|
data: 'data:image/png;base64,abc',
|
||||||
|
position: 'diagonal',
|
||||||
|
});
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects empty-string data fields', () => {
|
||||||
|
const { error } = schemas.logoUpload.validate({ data: '' });
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
Generated
+73
@@ -15,6 +15,7 @@
|
|||||||
"express": "^4.22.1",
|
"express": "^4.22.1",
|
||||||
"express-rate-limit": "^7.5.1",
|
"express-rate-limit": "^7.5.1",
|
||||||
"helmet": "^8.1.0",
|
"helmet": "^8.1.0",
|
||||||
|
"joi": "^18.2.3",
|
||||||
"js-yaml": "^4.1.1",
|
"js-yaml": "^4.1.1",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
"lru-cache": "^10.4.3",
|
"lru-cache": "^10.4.3",
|
||||||
@@ -679,6 +680,54 @@
|
|||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@hapi/address": {
|
||||||
|
"version": "5.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@hapi/address/-/address-5.1.1.tgz",
|
||||||
|
"integrity": "sha512-A+po2d/dVoY7cYajycYI43ZbYMXukuopIsqCjh5QzsBCipDtdofHntljDlpccMjIfTy6UOkg+5KPriwYch2bXA==",
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"dependencies": {
|
||||||
|
"@hapi/hoek": "^11.0.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@hapi/formula": {
|
||||||
|
"version": "3.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@hapi/formula/-/formula-3.0.2.tgz",
|
||||||
|
"integrity": "sha512-hY5YPNXzw1He7s0iqkRQi+uMGh383CGdyyIGYtB+W5N3KHPXoqychklvHhKCC9M3Xtv0OCs/IHw+r4dcHtBYWw==",
|
||||||
|
"license": "BSD-3-Clause"
|
||||||
|
},
|
||||||
|
"node_modules/@hapi/hoek": {
|
||||||
|
"version": "11.0.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-11.0.7.tgz",
|
||||||
|
"integrity": "sha512-HV5undWkKzcB4RZUusqOpcgxOaq6VOAH7zhhIr2g3G8NF/MlFO75SjOr2NfuSx0Mh40+1FqCkagKLJRykUWoFQ==",
|
||||||
|
"license": "BSD-3-Clause"
|
||||||
|
},
|
||||||
|
"node_modules/@hapi/pinpoint": {
|
||||||
|
"version": "2.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@hapi/pinpoint/-/pinpoint-2.0.1.tgz",
|
||||||
|
"integrity": "sha512-EKQmr16tM8s16vTT3cA5L0kZZcTMU5DUOZTuvpnY738m+jyP3JIUj+Mm1xc1rsLkGBQ/gVnfKYPwOmPg1tUR4Q==",
|
||||||
|
"license": "BSD-3-Clause"
|
||||||
|
},
|
||||||
|
"node_modules/@hapi/tlds": {
|
||||||
|
"version": "1.1.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@hapi/tlds/-/tlds-1.1.7.tgz",
|
||||||
|
"integrity": "sha512-MgNjRwy9Ti92yVAixLmDc8dd1bJIKwO9qlWCfFQRwRmUEDPQHYn4G6hwPFvFGUTzAa0FsS+inMjLin7GnyBRhA==",
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@hapi/topo": {
|
||||||
|
"version": "6.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@hapi/topo/-/topo-6.0.2.tgz",
|
||||||
|
"integrity": "sha512-KR3rD5inZbGMrHmgPxsJ9dbi6zEK+C3ZwUwTa+eMwWLz7oijWUTWD2pMSNNYJAU6Qq+65NkxXjqHr/7LM2Xkqg==",
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"dependencies": {
|
||||||
|
"@hapi/hoek": "^11.0.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@humanwhocodes/config-array": {
|
"node_modules/@humanwhocodes/config-array": {
|
||||||
"version": "0.13.0",
|
"version": "0.13.0",
|
||||||
"resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz",
|
"resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz",
|
||||||
@@ -1688,6 +1737,12 @@
|
|||||||
"@sinonjs/commons": "^3.0.0"
|
"@sinonjs/commons": "^3.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@standard-schema/spec": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@types/babel__core": {
|
"node_modules/@types/babel__core": {
|
||||||
"version": "7.20.5",
|
"version": "7.20.5",
|
||||||
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
|
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
|
||||||
@@ -4979,6 +5034,24 @@
|
|||||||
"url": "https://github.com/chalk/supports-color?sponsor=1"
|
"url": "https://github.com/chalk/supports-color?sponsor=1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/joi": {
|
||||||
|
"version": "18.2.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/joi/-/joi-18.2.3.tgz",
|
||||||
|
"integrity": "sha512-N5A3KTWQpPWT4ExxxPlUx7WmykGXRzhNidWhV41d6Abu9YfI2NyWCJuxdPnslJCPWtbRpSVOWSnSS6GakLM/Rg==",
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"dependencies": {
|
||||||
|
"@hapi/address": "^5.1.1",
|
||||||
|
"@hapi/formula": "^3.0.2",
|
||||||
|
"@hapi/hoek": "^11.0.7",
|
||||||
|
"@hapi/pinpoint": "^2.0.1",
|
||||||
|
"@hapi/tlds": "^1.1.1",
|
||||||
|
"@hapi/topo": "^6.0.2",
|
||||||
|
"@standard-schema/spec": "^1.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 20"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/js-tokens": {
|
"node_modules/js-tokens": {
|
||||||
"version": "4.0.0",
|
"version": "4.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||||
|
|||||||
@@ -26,6 +26,7 @@
|
|||||||
"express": "^4.22.1",
|
"express": "^4.22.1",
|
||||||
"express-rate-limit": "^7.5.1",
|
"express-rate-limit": "^7.5.1",
|
||||||
"helmet": "^8.1.0",
|
"helmet": "^8.1.0",
|
||||||
|
"joi": "^18.2.3",
|
||||||
"js-yaml": "^4.1.1",
|
"js-yaml": "^4.1.1",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
"lru-cache": "^10.4.3",
|
"lru-cache": "^10.4.3",
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ const platformPaths = require('../../platform-paths');
|
|||||||
const { ValidationError } = require('../../src/utilities/errors');
|
const { ValidationError } = require('../../src/utilities/errors');
|
||||||
const { logError } = require('../../src/utils/logging');
|
const { logError } = require('../../src/utils/logging');
|
||||||
const { ok } = require('../../src/utils/responses');
|
const { ok } = require('../../src/utils/responses');
|
||||||
|
const { validateBody, schemas: valSchemas } = require('../../src/utilities/validate');
|
||||||
/**
|
/**
|
||||||
* Apps deployment routes factory
|
* Apps deployment routes factory
|
||||||
* @param {Object} deps - Explicit dependencies
|
* @param {Object} deps - Explicit dependencies
|
||||||
@@ -251,17 +252,8 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
|||||||
}, 'check-existing'));
|
}, 'check-existing'));
|
||||||
|
|
||||||
// Deploy new app
|
// Deploy new app
|
||||||
router.post('/deploy', asyncHandler(async (req, res) => {
|
router.post('/deploy', validateBody(valSchemas.appDeploy), asyncHandler(async (req, res) => {
|
||||||
const { appId, config } = req.body;
|
const { appId, config } = req.body;
|
||||||
if (!appId || typeof appId !== 'string') {
|
|
||||||
throw new ValidationError('appId is required');
|
|
||||||
}
|
|
||||||
if (!config || typeof config !== 'object') {
|
|
||||||
throw new ValidationError('config object is required');
|
|
||||||
}
|
|
||||||
if (!config.subdomain || typeof config.subdomain !== 'string') {
|
|
||||||
throw new ValidationError('config.subdomain is required');
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
log.info('deploy', 'Deploying app', { appId, subdomain: config.subdomain });
|
log.info('deploy', 'Deploying app', { appId, subdomain: config.subdomain });
|
||||||
const template = ctx.APP_TEMPLATES[appId];
|
const template = ctx.APP_TEMPLATES[appId];
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ const path = require('path');
|
|||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const { DOCKER } = require('../../src/utilities/constants');
|
const { DOCKER } = require('../../src/utilities/constants');
|
||||||
const { ok, validationError, notFound, errorResponse } = require('../../src/utils/responses');
|
const { ok, validationError, notFound, errorResponse } = require('../../src/utils/responses');
|
||||||
|
const { validateBody, schemas: valSchemas } = require('../../src/utilities/validate');
|
||||||
|
|
||||||
const DEFAULT_BACKUP_DIR = process.env.BACKUP_DIR || path.join(__dirname, '..', 'backups');
|
const DEFAULT_BACKUP_DIR = process.env.BACKUP_DIR || path.join(__dirname, '..', 'backups');
|
||||||
|
|
||||||
@@ -36,7 +37,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
|||||||
* Pulls image, creates container, starts it, recreates Caddy config.
|
* Pulls image, creates container, starts it, recreates Caddy config.
|
||||||
* Skips if container is already running.
|
* Skips if container is already running.
|
||||||
*/
|
*/
|
||||||
router.post('/:appId/restore', asyncHandler(async (req, res) => {
|
router.post('/:appId/restore', validateBody(valSchemas.appRestore), asyncHandler(async (req, res) => {
|
||||||
const { appId } = req.params;
|
const { appId } = req.params;
|
||||||
const services = await servicesStateManager.read();
|
const services = await servicesStateManager.read();
|
||||||
const service = services.find(s => s.id === appId);
|
const service = services.find(s => s.id === appId);
|
||||||
@@ -183,9 +184,9 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
|||||||
}, 'apps-backup-points'));
|
}, 'apps-backup-points'));
|
||||||
|
|
||||||
// Revert a specific app to a backup file (point-in-time restore)
|
// Revert a specific app to a backup file (point-in-time restore)
|
||||||
router.post('/:appId/revert/:filename', asyncHandler(async (req, res) => {
|
router.post('/:appId/revert/:filename', validateBody(valSchemas.appRevert), asyncHandler(async (req, res) => {
|
||||||
const { appId, filename } = req.params;
|
const { appId, filename } = req.params;
|
||||||
const { encryptionKey, restartContainers } = req.body || {};
|
const { encryptionKey, restartContainers } = req.body;
|
||||||
|
|
||||||
// Security: prevent path traversal
|
// Security: prevent path traversal
|
||||||
if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
|
if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ const fsp = require('fs').promises;
|
|||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const { success } = require('../src/utils/responses');
|
const { success } = require('../src/utils/responses');
|
||||||
|
const { validateBody, schemas } = require('../src/utilities/validate');
|
||||||
|
|
||||||
const DEFAULT_BACKUP_DIR = process.env.BACKUP_DIR || path.join(__dirname, '..', 'backups');
|
const DEFAULT_BACKUP_DIR = process.env.BACKUP_DIR || path.join(__dirname, '..', 'backups');
|
||||||
const DEFAULT_MAX_STORAGE_BYTES = process.env.BACKUP_MAX_STORAGE_BYTES
|
const DEFAULT_MAX_STORAGE_BYTES = process.env.BACKUP_MAX_STORAGE_BYTES
|
||||||
@@ -56,14 +57,10 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
|||||||
}, 'backups-schedule-list'));
|
}, 'backups-schedule-list'));
|
||||||
|
|
||||||
// Create or update a scheduled backup for an app
|
// Create or update a scheduled backup for an app
|
||||||
router.post('/backups/schedule', premiumGating, asyncHandler(async (req, res) => {
|
router.post('/backups/schedule', premiumGating, validateBody(schemas.backupScheduleCreate), asyncHandler(async (req, res) => {
|
||||||
|
// appId is guaranteed present by the Joi schema (backupScheduleCreate requires it)
|
||||||
const { appId, enabled, schedule, retention, runImmediately, destination, destinationPath, maxStorageBytes } = req.body;
|
const { appId, enabled, schedule, retention, runImmediately, destination, destinationPath, maxStorageBytes } = req.body;
|
||||||
|
|
||||||
if (!appId) {
|
|
||||||
const { ValidationError } = require('../src/utilities/errors');
|
|
||||||
throw new ValidationError('appId is required');
|
|
||||||
}
|
|
||||||
|
|
||||||
const config = backupManager.getConfig();
|
const config = backupManager.getConfig();
|
||||||
if (!config.backups) config.backups = {};
|
if (!config.backups) config.backups = {};
|
||||||
|
|
||||||
@@ -234,7 +231,7 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
|||||||
}, 'backups-files-app'));
|
}, 'backups-files-app'));
|
||||||
|
|
||||||
// Restore from a specific backup file on disk
|
// Restore from a specific backup file on disk
|
||||||
router.post('/backups/restore-file/:filename', asyncHandler(async (req, res) => {
|
router.post('/backups/restore-file/:filename', validateBody(schemas.backupRestoreFile), asyncHandler(async (req, res) => {
|
||||||
const { filename } = req.params;
|
const { filename } = req.params;
|
||||||
const { encryptionKey, restartContainers } = req.body || {};
|
const { encryptionKey, restartContainers } = req.body || {};
|
||||||
|
|
||||||
@@ -483,7 +480,7 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
|||||||
}, 'backups-config-get'));
|
}, 'backups-config-get'));
|
||||||
|
|
||||||
// Update backup configuration
|
// Update backup configuration
|
||||||
router.post('/backups/config', asyncHandler(async (req, res) => {
|
router.post('/backups/config', validateBody(schemas.backupConfigUpdate), asyncHandler(async (req, res) => {
|
||||||
// P0-3 fix: was `backupManager.updateConfig(req.body)` which allowed
|
// P0-3 fix: was `backupManager.updateConfig(req.body)` which allowed
|
||||||
// arbitrary keys from HTTP request body to be merged into persisted config.
|
// arbitrary keys from HTTP request body to be merged into persisted config.
|
||||||
// Now destructure only the two known top-level fields.
|
// Now destructure only the two known top-level fields.
|
||||||
@@ -515,6 +512,11 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
|||||||
}, 'backups-storage-info'));
|
}, 'backups-storage-info'));
|
||||||
|
|
||||||
// Schedule a backup
|
// Schedule a backup
|
||||||
|
// LEGACY: this is a duplicate registration of POST /backups/schedule (see also line 60,
|
||||||
|
// which uses the appId-keyed schema and is the route the frontend actually calls).
|
||||||
|
// Express only matches the first registered handler per METHOD+PATH, so this handler
|
||||||
|
// is unreachable. It is preserved for now to avoid removing a route any unknown
|
||||||
|
// integration might still POST to. TODO: audit + remove in a dedicated cleanup PR.
|
||||||
router.post('/backups/schedule', asyncHandler(async (req, res) => {
|
router.post('/backups/schedule', asyncHandler(async (req, res) => {
|
||||||
const { name, schedule, maxStorageBytes, ...backupConfig } = req.body;
|
const { name, schedule, maxStorageBytes, ...backupConfig } = req.body;
|
||||||
|
|
||||||
@@ -539,10 +541,10 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
|||||||
|
|
||||||
backupManager.updateConfig(config);
|
backupManager.updateConfig(config);
|
||||||
success(res, { message: `Backup '${name}' scheduled`, maxStorageBytes: maxBytes });
|
success(res, { message: `Backup '${name}' scheduled`, maxStorageBytes: maxBytes });
|
||||||
}, 'backups-schedule'));
|
}, 'backups-schedule-legacy'));
|
||||||
|
|
||||||
// Restore from backup
|
// Restore from backup
|
||||||
router.post('/backups/restore/:backupId', asyncHandler(async (req, res) => {
|
router.post('/backups/restore/:backupId', validateBody(schemas.backupRestore), asyncHandler(async (req, res) => {
|
||||||
const result = await backupManager.restoreBackup(req.params.backupId, req.body);
|
const result = await backupManager.restoreBackup(req.params.backupId, req.body);
|
||||||
success(res, { result });
|
success(res, { result });
|
||||||
}, 'backups-restore'));
|
}, 'backups-restore'));
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ const { exists } = require('../../src/utilities/fs-helpers');
|
|||||||
const { ValidationError } = require('../../src/utilities/errors');
|
const { ValidationError } = require('../../src/utilities/errors');
|
||||||
const platformPaths = require('../../platform-paths');
|
const platformPaths = require('../../platform-paths');
|
||||||
const { ok, successMessage } = require('../../src/utils/responses');
|
const { ok, successMessage } = require('../../src/utils/responses');
|
||||||
|
const { validateBody, schemas: valSchemas } = require('../../src/utilities/validate');
|
||||||
/**
|
/**
|
||||||
* Config assets routes factory
|
* Config assets routes factory
|
||||||
* @param {Object} deps - Explicit dependencies
|
* @param {Object} deps - Explicit dependencies
|
||||||
@@ -54,13 +55,9 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
|||||||
|
|
||||||
// ===== ASSET UPLOAD =====
|
// ===== ASSET UPLOAD =====
|
||||||
|
|
||||||
router.post('/assets/upload', express.json({ limit: LIMITS.BODY_UPLOAD }), asyncHandler(async (req, res) => {
|
router.post('/assets/upload', express.json({ limit: LIMITS.BODY_UPLOAD }), validateBody(valSchemas.assetUpload), asyncHandler(async (req, res) => {
|
||||||
const { filename, data } = req.body;
|
const { filename, data } = req.body;
|
||||||
|
|
||||||
if (!filename || !data) {
|
|
||||||
throw new ValidationError('filename and data are required');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate filename to prevent directory traversal
|
// Validate filename to prevent directory traversal
|
||||||
const safeFilename = path.basename(filename);
|
const safeFilename = path.basename(filename);
|
||||||
if (safeFilename !== filename || filename.includes('..')) {
|
if (safeFilename !== filename || filename.includes('..')) {
|
||||||
@@ -129,13 +126,9 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
|||||||
// Upload custom logo(s) and/or update position and title
|
// Upload custom logo(s) and/or update position and title
|
||||||
// Supports: dataDark/dataLight (separate variants) or data (single logo for both)
|
// Supports: dataDark/dataLight (separate variants) or data (single logo for both)
|
||||||
// eslint-disable-next-line complexity
|
// eslint-disable-next-line complexity
|
||||||
router.post('/logo', express.json({ limit: LIMITS.BODY_UPLOAD }), asyncHandler(async (req, res) => {
|
router.post('/logo', express.json({ limit: LIMITS.BODY_UPLOAD }), validateBody(valSchemas.logoUpload), asyncHandler(async (req, res) => {
|
||||||
const { data, dataDark, dataLight, position, dashboardTitle } = req.body;
|
const { data, dataDark, dataLight, position, dashboardTitle } = req.body;
|
||||||
|
|
||||||
if (!data && !dataDark && !dataLight && !position && !dashboardTitle) {
|
|
||||||
throw new ValidationError('Image data, position, or title is required');
|
|
||||||
}
|
|
||||||
|
|
||||||
const config = await ctx.readConfig();
|
const config = await ctx.readConfig();
|
||||||
let pathDark = null, pathLight = null;
|
let pathDark = null, pathLight = null;
|
||||||
|
|
||||||
@@ -240,15 +233,10 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
|||||||
return ctx.errorResponse(res, 500, 'Image processing not available');
|
return ctx.errorResponse(res, 500, 'Image processing not available');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extract base64 data
|
// P0-4: validate MIME type + enforce 5MB buffer size cap (mime validated inside decodeImageData)
|
||||||
const matches = data.match(/^data:image\/([a-zA-Z+]+);base64,(.+)$/);
|
const { buffer } = decodeImageData(data);
|
||||||
if (!matches) {
|
|
||||||
throw new ValidationError('Invalid image data format');
|
|
||||||
}
|
|
||||||
|
|
||||||
const base64Data = matches[2];
|
|
||||||
const buffer = Buffer.from(base64Data, 'base64');
|
|
||||||
|
|
||||||
|
// Determine assets path (mounted volume)
|
||||||
const assetsPath = platformPaths.resolveAssetsPath(process.env.ASSETS_PATH);
|
const assetsPath = platformPaths.resolveAssetsPath(process.env.ASSETS_PATH);
|
||||||
if (!await exists(assetsPath)) {
|
if (!await exists(assetsPath)) {
|
||||||
await fsp.mkdir(assetsPath, { recursive: true });
|
await fsp.mkdir(assetsPath, { recursive: true });
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
* Usage:
|
* Usage:
|
||||||
* const { validateBody, schemas } = require('../utilities/validate');
|
* const { validateBody, schemas } = require('../utilities/validate');
|
||||||
*
|
*
|
||||||
* router.post('/schedule', validateBody(schemas.backupSchedule), handler);
|
* router.post('/schedule', validateBody(schemas.backupScheduleCreate), handler);
|
||||||
*
|
*
|
||||||
* The middleware validates req.body against the provided Joi schema.
|
* The middleware validates req.body against the provided Joi schema.
|
||||||
* On success it replaces req.body with the validated/stripped value.
|
* On success it replaces req.body with the validated/stripped value.
|
||||||
@@ -46,22 +46,11 @@ const scheduleSchema = Joi.alternatives().try(
|
|||||||
).optional();
|
).optional();
|
||||||
|
|
||||||
const ipOrCidr = Joi.alternatives().try(
|
const ipOrCidr = Joi.alternatives().try(
|
||||||
|
// Authoritative single-IP validation (Joi's built-in strict IPv4/IPv6 check)
|
||||||
Joi.string().ip({ version: ['ipv4', 'ipv6'] }),
|
Joi.string().ip({ version: ['ipv4', 'ipv6'] }),
|
||||||
Joi.string().regex(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\/(\d{1,2})$/)
|
// Authoritative CIDR validation (Joi's built-in strict CIDR check rejects malformed
|
||||||
.custom((value, helpers) => {
|
// addresses like "::::/64" that a permissive hex/colon regex would otherwise accept)
|
||||||
const [, a, b, c, d, prefix] = value.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\/(\d{1,2})$/);
|
Joi.string().ip({ version: ['ipv4', 'ipv6'], cidr: 'required' }),
|
||||||
for (const octet of [a, b, c, d]) {
|
|
||||||
if (parseInt(octet) > 255) return helpers.error('string.pattern.base', { name: 'IPv4 CIDR' });
|
|
||||||
}
|
|
||||||
if (parseInt(prefix) > 32) return helpers.error('string.pattern.base', { name: 'IPv4 CIDR' });
|
|
||||||
return value;
|
|
||||||
}, 'IPv4 CIDR with valid octets/prefix'),
|
|
||||||
Joi.string().regex(/^[0-9a-fA-F:]+\/(\d{1,3})$/)
|
|
||||||
.custom((value, helpers) => {
|
|
||||||
const prefix = parseInt(value.split('/')[1]);
|
|
||||||
if (prefix > 128) return helpers.error('string.pattern.base', { name: 'IPv6 CIDR' });
|
|
||||||
return value;
|
|
||||||
}, 'IPv6 CIDR with valid prefix'),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
// ─── Schemas for destructive routes ───────────────────────────
|
// ─── Schemas for destructive routes ───────────────────────────
|
||||||
@@ -147,15 +136,26 @@ const schemas = {
|
|||||||
containerPath: Joi.string().max(500).required(),
|
containerPath: Joi.string().max(500).required(),
|
||||||
}).unknown(false)).optional(),
|
}).unknown(false)).optional(),
|
||||||
mediaPath: Joi.string().max(500).optional(),
|
mediaPath: Joi.string().max(500).optional(),
|
||||||
|
// Template-specific config fields preserved from the live frontend
|
||||||
|
sslType: Joi.string().valid('self-signed', 'tailscale', 'letsencrypt', 'none').optional(),
|
||||||
|
dnsType: Joi.string().valid('private', 'public', 'none').optional(),
|
||||||
|
plexClaimToken: Joi.string().max(500).optional(),
|
||||||
resources: Joi.object({
|
resources: Joi.object({
|
||||||
memory: Joi.number().min(32).max(65536).optional(),
|
memory: Joi.number().min(32).max(65536).optional(),
|
||||||
cpus: Joi.number().min(0.1).max(64).optional(),
|
cpus: Joi.number().min(0.1).max(64).optional(),
|
||||||
}).optional(),
|
}).optional(),
|
||||||
}).required(),
|
}).unknown(true), // Forward-compat: templates may accept additional fields
|
||||||
}),
|
}),
|
||||||
|
|
||||||
/** POST /apps/:appId/restore */
|
/** POST /apps/:appId/restore — empty body, reject any input fields */
|
||||||
appRestore: Joi.object({}).max(0),
|
appRestore: Joi.any().custom((value, helpers) => {
|
||||||
|
if (value !== undefined && value !== null && (typeof value !== 'object' || Object.keys(value).length > 0)) {
|
||||||
|
return helpers.error('object.empty');
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}, 'empty-body-guard').messages({
|
||||||
|
'object.empty': '"body" must be empty (this endpoint accepts no input)',
|
||||||
|
}),
|
||||||
|
|
||||||
/** POST /apps/:appId/revert/:filename */
|
/** POST /apps/:appId/revert/:filename */
|
||||||
appRevert: Joi.object({
|
appRevert: Joi.object({
|
||||||
@@ -171,9 +171,9 @@ const schemas = {
|
|||||||
|
|
||||||
/** POST /assets/logo */
|
/** POST /assets/logo */
|
||||||
logoUpload: Joi.object({
|
logoUpload: Joi.object({
|
||||||
data: Joi.string().max(10 * 1024 * 1024).optional(),
|
data: Joi.string().min(1).max(10 * 1024 * 1024).optional(),
|
||||||
dataDark: Joi.string().max(10 * 1024 * 1024).optional(),
|
dataDark: Joi.string().min(1).max(10 * 1024 * 1024).optional(),
|
||||||
dataLight: Joi.string().max(10 * 1024 * 1024).optional(),
|
dataLight: Joi.string().min(1).max(10 * 1024 * 1024).optional(),
|
||||||
position: Joi.string().valid('left', 'center', 'right').optional(),
|
position: Joi.string().valid('left', 'center', 'right').optional(),
|
||||||
dashboardTitle: Joi.string().max(50).allow('').optional(),
|
dashboardTitle: Joi.string().max(50).allow('').optional(),
|
||||||
}).min(1),
|
}).min(1),
|
||||||
|
|||||||
Reference in New Issue
Block a user