fix(app-store): harden App Store with auth, validation, bug fixes, and design compliance (#523)

* fix(app-store): harden App Store with auth, validation, bug fixes, and design compliance

Add authMiddleware to GET /api/templates and POST /api/templates/deploy
endpoints. Add isValidStackName and isPathWithinBase checks to the deploy
endpoint. Replace fs.existsSync with async fsPromises.access. Extract
FileSystemService to local variable to avoid repeated getInstance calls.

Fix template mutation bug where PUID/PGID/TZ duplicated on re-open by
working on a copy instead of mutating state. Make env_file conditional
in generated compose YAML (only when env vars exist). Add port validation
(range 1-65535) with visual feedback and deploy blocking. Add env key
collision warning toast for custom variables.

Replace any types with proper LSIO API interfaces. Change catch types
from any to unknown with getErrorMessage. Add structured logging with
[Templates] prefix and diagnostic logging gated behind Developer Mode.

Align with design system: remove hardcoded bg-white and text-red-500,
use ScrollArea, fix destructive button variant, add tabular-nums and
strokeWidth 1.5, use cn() for conditional classes. Add empty-registry
state distinct from no-search-results.

Add 16 unit tests for TemplateService covering compose generation,
conditional env_file, env string generation, and cache clearing.
Update App Store docs with port validation and env collision details.

* refactor(app-store): remove unused interface exports

Remove export keyword from interfaces that are only used within their
own file: TemplateEnv, TemplateVolume, and TemplatesResponse in
TemplateService.ts; TemplateEnv and Template in AppStoreView.tsx.
No external consumers import these types.

* fix(app-store): remove unused fs default import

The fs.existsSync call was replaced with fsPromises.access in the
deploy endpoint, leaving the fs default import unused. Remove it
to fix the ESLint no-unused-vars error in CI.
This commit is contained in:
Anso
2026-04-12 14:31:00 -04:00
committed by GitHub
parent 8e91f91622
commit d4882d32d9
5 changed files with 368 additions and 64 deletions
@@ -0,0 +1,222 @@
/**
* Unit tests for TemplateService: compose YAML generation,
* env string generation, conditional env_file, and cache clearing.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { TemplateService, Template } from '../services/TemplateService';
describe('TemplateService', () => {
let service: TemplateService;
beforeEach(() => {
service = new TemplateService();
});
// ─── generateComposeFromTemplate ─────────────────────────────────────
describe('generateComposeFromTemplate', () => {
it('generates minimal compose with just image and restart policy', () => {
const template: Template = {
title: 'nginx',
description: 'Web server',
image: 'nginx:latest',
};
const yaml = service.generateComposeFromTemplate(template);
expect(yaml).toContain('image: nginx:latest');
expect(yaml).toContain('restart: unless-stopped');
expect(yaml).not.toContain('ports:');
expect(yaml).not.toContain('volumes:');
expect(yaml).not.toContain('env_file:');
});
it('includes ports when template has port mappings', () => {
const template: Template = {
title: 'nginx',
description: 'Web server',
image: 'nginx:latest',
ports: ['80:80', '443:443/tcp'],
};
const yaml = service.generateComposeFromTemplate(template);
expect(yaml).toContain('ports:');
expect(yaml).toContain('"80:80"');
expect(yaml).toContain('"443:443/tcp"');
});
it('handles string volumes with host:container format', () => {
const template: Template = {
title: 'app',
description: 'Test',
image: 'test:latest',
volumes: ['/host/data:/container/data'],
};
const yaml = service.generateComposeFromTemplate(template);
expect(yaml).toContain('volumes:');
expect(yaml).toContain('/host/data:/container/data');
});
it('handles string volumes with single path (named volume)', () => {
const template: Template = {
title: 'app',
description: 'Test',
image: 'test:latest',
volumes: ['/data'],
};
const yaml = service.generateComposeFromTemplate(template);
expect(yaml).toContain('- /data');
});
it('handles object volumes with container and bind', () => {
const template: Template = {
title: 'app',
description: 'Test',
image: 'test:latest',
volumes: [{ container: '/config', bind: './config' }],
};
const yaml = service.generateComposeFromTemplate(template);
expect(yaml).toContain('./config:/config');
});
it('generates bind path from container folder when bind is not specified', () => {
const template: Template = {
title: 'app',
description: 'Test',
image: 'test:latest',
volumes: [{ container: '/app/data' }],
};
const yaml = service.generateComposeFromTemplate(template);
expect(yaml).toContain('./data:/app/data');
});
it('adds :ro suffix for readonly volumes', () => {
const template: Template = {
title: 'app',
description: 'Test',
image: 'test:latest',
volumes: [{ container: '/config', bind: './config', readonly: true }],
};
const yaml = service.generateComposeFromTemplate(template);
expect(yaml).toContain('./config:/config:ro');
});
it('includes env_file only when env vars are present', () => {
const withEnv: Template = {
title: 'app',
description: 'Test',
image: 'test:latest',
env: [{ name: 'TZ', default: 'UTC' }],
};
const withoutEnv: Template = {
title: 'app',
description: 'Test',
image: 'test:latest',
env: [],
};
expect(service.generateComposeFromTemplate(withEnv)).toContain('env_file:');
expect(service.generateComposeFromTemplate(withoutEnv)).not.toContain('env_file:');
});
it('does not include env_file when env is undefined', () => {
const template: Template = {
title: 'app',
description: 'Test',
image: 'test:latest',
};
expect(service.generateComposeFromTemplate(template)).not.toContain('env_file:');
});
it('handles string volumes with options (e.g., host:container:ro)', () => {
const template: Template = {
title: 'app',
description: 'Test',
image: 'test:latest',
volumes: ['/host/config:/config:ro'],
};
const yaml = service.generateComposeFromTemplate(template);
expect(yaml).toContain('/host/config:/config:ro');
});
it('skips object volumes without container path', () => {
const template: Template = {
title: 'app',
description: 'Test',
image: 'test:latest',
volumes: [{ container: '' }],
};
const yaml = service.generateComposeFromTemplate(template);
// Empty container means `continue` is hit, no volume line emitted
expect(yaml).toContain('volumes:');
// The volume header is added but no actual volume entry
const volumeLines = yaml.split('\n').filter(l => l.trim().startsWith('- '));
expect(volumeLines).toHaveLength(0);
});
it('produces valid YAML structure starting with services key', () => {
const template: Template = {
title: 'full',
description: 'Full template',
image: 'app:v1',
ports: ['8080:80'],
volumes: [{ container: '/data', bind: './data' }],
env: [{ name: 'KEY', default: 'val' }],
};
const yaml = service.generateComposeFromTemplate(template);
expect(yaml).toMatch(/^services:\n/);
expect(yaml).toContain(' app:');
});
});
// ─── generateEnvString ───────────────────────────────────────────────
describe('generateEnvString', () => {
it('converts key-value pairs to env file format', () => {
const result = service.generateEnvString({
TZ: 'America/New_York',
PUID: '1000',
PGID: '1000',
});
expect(result).toBe('TZ=America/New_York\nPUID=1000\nPGID=1000');
});
it('returns empty string for empty object', () => {
expect(service.generateEnvString({})).toBe('');
});
it('handles values with special characters', () => {
const result = service.generateEnvString({
PASSWORD: 'p@ss=word!',
URL: 'http://localhost:3000',
});
expect(result).toContain('PASSWORD=p@ss=word!');
expect(result).toContain('URL=http://localhost:3000');
});
});
// ─── clearCache ──────────────────────────────────────────────────────
describe('clearCache', () => {
it('calls CacheService.invalidate with the correct key', () => {
const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
// clearCache should not throw even when cache is empty
expect(() => service.clearCache()).not.toThrow();
expect(consoleSpy).toHaveBeenCalledWith('[Templates] Cache invalidated');
consoleSpy.mockRestore();
});
});
});