Skip to content

A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.

refactor: migrate from keychain usage for desktop installations

towfiqifb1da3bfaaab
diff --git a/backend/__tests__/controllers/SetupController.test.ts b/backend/__tests__/controllers/SetupController.test.ts
index eb3dc39..b6b0381 100644
--- a/backend/__tests__/controllers/SetupController.test.ts
+++ b/backend/__tests__/controllers/SetupController.test.ts
@@ -1,23 +1,21 @@
import { Request, Response } from 'express';
import { SetupController } from '../../src/controllers/SetupController';
-jest.mock('../../src/services/KeyringService', () => ({
- keyringService: {
- isPlatformSupported: jest.fn(),
- waitForInitialization: jest.fn(),
- setAllCredentials: jest.fn(),
- },
+jest.mock('../../src/utils/envFileHelpers', () => ({
+ writeEncryptionKeyToEnvFile: jest.fn(),
+ encEnvFileExists: jest.fn(),
}));
jest.mock('../../src/services/ConfigService', () => ({
configService: {
isSetupPending: jest.fn(),
completeSetup: jest.fn(),
+ markSetupPending: jest.fn(),
},
}));
jest.mock('../../src/utils/installHelpers', () => ({
- requiresKeyringSetup: jest.fn(),
+ requiresDesktopSetup: jest.fn(),
isBinaryMode: jest.fn(),
}));
@@ -29,10 +27,23 @@ jest.mock('../../src/db', () => ({
db: {},
}));
-import { keyringService } from '../../src/services/KeyringService';
+jest.mock('../../src/utils/AppPaths', () => ({
+ appPaths: {
+ getDataDir: jest.fn().mockReturnValue('/mock/data'),
+ },
+}));
+
+jest.mock('fs', () => ({
+ ...jest.requireActual('fs'),
+ accessSync: jest.fn(),
+ constants: { W_OK: 2 },
+}));
+
import { configService } from '../../src/services/ConfigService';
-import { requiresKeyringSetup, isBinaryMode } from '../../src/utils/installHelpers';
+import { requiresDesktopSetup, isBinaryMode } from '../../src/utils/installHelpers';
+import { writeEncryptionKeyToEnvFile, encEnvFileExists } from '../../src/utils/envFileHelpers';
import { initSetup } from '../../src/utils/initSetup';
+import fs from 'fs';
describe('SetupController', () => {
let controller: SetupController;
@@ -63,7 +74,8 @@ describe('SetupController', () => {
it('should return setup status successfully', async () => {
(configService.isSetupPending as jest.Mock).mockReturnValue(true);
(isBinaryMode as jest.Mock).mockReturnValue(false);
- (requiresKeyringSetup as jest.Mock).mockReturnValue(true);
+ (requiresDesktopSetup as jest.Mock).mockReturnValue(true);
+ (encEnvFileExists as jest.Mock).mockReturnValue(false);
await controller.getStatus(mockRequest as Request, mockResponse as Response);
@@ -72,7 +84,9 @@ describe('SetupController', () => {
data: {
setupPending: true,
isBinary: false,
+ requiresSetup: true,
requiresKeyringSetup: true,
+ hasEncEnvFile: false,
platform: process.platform,
},
});
@@ -112,22 +126,23 @@ describe('SetupController', () => {
});
});
- it('should return 400 if keyring setup is not supported', async () => {
+ it('should return 400 if desktop setup is not supported', async () => {
(configService.isSetupPending as jest.Mock).mockReturnValue(true);
- (requiresKeyringSetup as jest.Mock).mockReturnValue(false);
+ (requiresDesktopSetup as jest.Mock).mockReturnValue(false);
await controller.completeSetup(mockRequest as Request, mockResponse as Response);
expect(mockStatus).toHaveBeenCalledWith(400);
expect(mockJson).toHaveBeenCalledWith({
success: false,
- error: 'Keyring setup is only available on Windows and macOS binary installations.',
+ error:
+ 'Desktop setup is only available on Windows, macOS and Linux desktop binary installations.',
});
});
it('should return 400 if required fields are missing', async () => {
(configService.isSetupPending as jest.Mock).mockReturnValue(true);
- (requiresKeyringSetup as jest.Mock).mockReturnValue(true);
+ (requiresDesktopSetup as jest.Mock).mockReturnValue(true);
mockRequest.body = { encryptionKey: 'mySecureKey123' };
await controller.completeSetup(mockRequest as Request, mockResponse as Response);
@@ -141,7 +156,7 @@ describe('SetupController', () => {
it('should return 400 if encryptionKey is too short', async () => {
(configService.isSetupPending as jest.Mock).mockReturnValue(true);
- (requiresKeyringSetup as jest.Mock).mockReturnValue(true);
+ (requiresDesktopSetup as jest.Mock).mockReturnValue(true);
mockRequest.body = { encryptionKey: 'short', userName: 'admin', userPassword: 'password123' };
await controller.completeSetup(mockRequest as Request, mockResponse as Response);
@@ -155,7 +170,7 @@ describe('SetupController', () => {
it('should return 400 if userName is empty', async () => {
(configService.isSetupPending as jest.Mock).mockReturnValue(true);
- (requiresKeyringSetup as jest.Mock).mockReturnValue(true);
+ (requiresDesktopSetup as jest.Mock).mockReturnValue(true);
mockRequest.body = {
encryptionKey: 'mySecureKey123',
userName: '',
@@ -173,7 +188,7 @@ describe('SetupController', () => {
it('should return 400 if userPassword is empty', async () => {
(configService.isSetupPending as jest.Mock).mockReturnValue(true);
- (requiresKeyringSetup as jest.Mock).mockReturnValue(true);
+ (requiresDesktopSetup as jest.Mock).mockReturnValue(true);
mockRequest.body = { encryptionKey: 'mySecureKey123', userName: 'admin', userPassword: '' };
await controller.completeSetup(mockRequest as Request, mockResponse as Response);
@@ -185,35 +200,18 @@ describe('SetupController', () => {
});
});
- it('should return 500 if keyring store fails', async () => {
+ it('should complete setup successfully by writing to env file', async () => {
(configService.isSetupPending as jest.Mock).mockReturnValue(true);
- (requiresKeyringSetup as jest.Mock).mockReturnValue(true);
- (keyringService.setAllCredentials as jest.Mock).mockResolvedValue(false);
- mockRequest.body = validBody;
-
- await controller.completeSetup(mockRequest as Request, mockResponse as Response);
-
- expect(mockStatus).toHaveBeenCalledWith(500);
- expect(mockJson).toHaveBeenCalledWith({
- success: false,
- error: 'Failed to store credentials in the system keyring',
- });
- });
-
- it('should complete setup successfully', async () => {
- (configService.isSetupPending as jest.Mock).mockReturnValue(true);
- (requiresKeyringSetup as jest.Mock).mockReturnValue(true);
- (keyringService.setAllCredentials as jest.Mock).mockResolvedValue(true);
+ (requiresDesktopSetup as jest.Mock).mockReturnValue(true);
(initSetup as jest.Mock).mockResolvedValue(undefined);
mockRequest.body = validBody;
await controller.completeSetup(mockRequest as Request, mockResponse as Response);
- expect(keyringService.setAllCredentials).toHaveBeenCalledWith({
- ENCRYPTION_KEY: validBody.encryptionKey,
- USER_NAME: validBody.userName,
- USER_PASSWORD: validBody.userPassword,
- });
+ expect(writeEncryptionKeyToEnvFile).toHaveBeenCalledWith(
+ '/mock/data',
+ validBody.encryptionKey
+ );
expect(configService.completeSetup).toHaveBeenCalledWith({
ENCRYPTION_KEY: validBody.encryptionKey,
USER_NAME: validBody.userName,
@@ -226,6 +224,23 @@ describe('SetupController', () => {
});
});
+ it('should roll back setup pending state if initSetup fails', async () => {
+ (configService.isSetupPending as jest.Mock).mockReturnValue(true);
+ (requiresDesktopSetup as jest.Mock).mockReturnValue(true);
+ (initSetup as jest.Mock).mockRejectedValue(new Error('DB migration failed'));
+ mockRequest.body = validBody;
+
+ await controller.completeSetup(mockRequest as Request, mockResponse as Response);
+
+ expect(configService.completeSetup).toHaveBeenCalled();
+ expect(configService.markSetupPending).toHaveBeenCalled();
+ expect(mockStatus).toHaveBeenCalledWith(500);
+ expect(mockJson).toHaveBeenCalledWith({
+ success: false,
+ error: 'DB migration failed',
+ });
+ });
+
it('should return 500 on unexpected error', async () => {
(configService.isSetupPending as jest.Mock).mockImplementation(() => {
throw new Error('Unexpected failure');
@@ -242,9 +257,9 @@ describe('SetupController', () => {
});
describe('checkKeyringAvailability', () => {
- it('should return keyring availability successfully', async () => {
- (keyringService.isPlatformSupported as jest.Mock).mockReturnValue(true);
- (keyringService.waitForInitialization as jest.Mock).mockResolvedValue(true);
+ it('should return system availability successfully', async () => {
+ (requiresDesktopSetup as jest.Mock).mockReturnValue(true);
+ (fs.accessSync as jest.Mock).mockReturnValue(undefined);
await controller.checkKeyringAvailability(mockRequest as Request, mockResponse as Response);
@@ -253,14 +268,34 @@ describe('SetupController', () => {
data: {
platformSupported: true,
keyringAvailable: true,
+ dataDirWritable: true,
+ platform: process.platform,
+ },
+ });
+ });
+
+ it('should return false when data dir is not writable', async () => {
+ (requiresDesktopSetup as jest.Mock).mockReturnValue(true);
+ (fs.accessSync as jest.Mock).mockImplementation(() => {
+ throw new Error('EACCES');
+ });
+
+ await controller.checkKeyringAvailability(mockRequest as Request, mockResponse as Response);
+
+ expect(mockJson).toHaveBeenCalledWith({
+ success: true,
+ data: {
+ platformSupported: true,
+ keyringAvailable: false,
+ dataDirWritable: false,
platform: process.platform,
},
});
});
it('should return 500 on error', async () => {
- (keyringService.isPlatformSupported as jest.Mock).mockImplementation(() => {
- throw new Error('Keyring check failed');
+ (requiresDesktopSetup as jest.Mock).mockImplementation(() => {
+ throw new Error('Check failed');
});
await controller.checkKeyringAvailability(mockRequest as Request, mockResponse as Response);
@@ -268,7 +303,7 @@ describe('SetupController', () => {
expect(mockStatus).toHaveBeenCalledWith(500);
expect(mockJson).toHaveBeenCalledWith({
success: false,
- error: 'Keyring check failed',
+ error: 'Check failed',
});
});
});
diff --git a/backend/__tests__/services/CredentialManager.test.ts b/backend/__tests__/services/CredentialManager.test.ts
new file mode 100644
index 0000000..813a1dd
--- /dev/null
+++ b/backend/__tests__/services/CredentialManager.test.ts
@@ -0,0 +1,317 @@
+import fs from 'fs';
+import os from 'os';
+import path from 'path';
+import bcrypt from 'bcryptjs';
+
+// Mock AppPaths before importing anything that depends on it
+let mockDataDir: string;
+
+jest.mock('../../src/utils/AppPaths', () => ({
+ appPaths: {
+ getDataDir: () => mockDataDir,
+ },
+}));
+
+// Mock child_process to prevent actual icacls calls
+jest.mock('child_process', () => ({
+ execSync: jest.fn(),
+}));
+
+describe('CredentialManager', () => {
+ let tmpDir: string;
+ let keysPath: string;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'credmgr-'));
+ mockDataDir = tmpDir;
+ keysPath = path.join(tmpDir, 'keys.json');
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ jest.resetModules();
+ });
+
+ function loadModule() {
+ // Fresh import each time to pick up the new mockDataDir
+ return require('../../src/services/CredentialManager') as typeof import('../../src/services/CredentialManager');
+ }
+
+ // ── constructor / getKeysPath ──────────────────────────────────────────────
+
+ describe('constructor and getKeysPath', () => {
+ it('should set keysPath to keys.json in data directory', () => {
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ expect(cm.getKeysPath()).toBe(path.join(tmpDir, 'keys.json'));
+ });
+ });
+
+ // ── readKeysFile ───────────────────────────────────────────────────────────
+
+ describe('readKeysFile', () => {
+ it('should return empty object when file does not exist', () => {
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ expect(cm.readKeysFile()).toEqual({});
+ });
+
+ it('should return parsed JSON when file exists', () => {
+ fs.writeFileSync(keysPath, JSON.stringify({ SECRET: 'abc', APIKEY: 'xyz' }));
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ expect(cm.readKeysFile()).toEqual({ SECRET: 'abc', APIKEY: 'xyz' });
+ });
+
+ it('should return empty object when file contains invalid JSON', () => {
+ fs.writeFileSync(keysPath, 'not valid json!!!');
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ expect(cm.readKeysFile()).toEqual({});
+ });
+ });
+
+ // ── writeKeysFile ──────────────────────────────────────────────────────────
+
+ describe('writeKeysFile', () => {
+ it('should write JSON to keys.json', () => {
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ cm.writeKeysFile({ SECRET: 'test-secret', APIKEY: 'test-api' });
+
+ const content = JSON.parse(fs.readFileSync(keysPath, 'utf-8'));
+ expect(content).toEqual({ SECRET: 'test-secret', APIKEY: 'test-api' });
+ });
+
+ it('should create parent directories if needed', () => {
+ const nested = path.join(tmpDir, 'sub', 'dir');
+ mockDataDir = nested;
+ jest.resetModules();
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ cm.writeKeysFile({ FOO: 'bar' });
+
+ const nestedKeysPath = path.join(nested, 'keys.json');
+ expect(fs.existsSync(nestedKeysPath)).toBe(true);
+ });
+
+ it('should overwrite existing content', () => {
+ fs.writeFileSync(keysPath, JSON.stringify({ OLD: 'data' }));
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ cm.writeKeysFile({ NEW: 'data' });
+
+ const content = JSON.parse(fs.readFileSync(keysPath, 'utf-8'));
+ expect(content).toEqual({ NEW: 'data' });
+ });
+ });
+
+ // ── loadOrGenerateSecrets ──────────────────────────────────────────────────
+
+ describe('loadOrGenerateSecrets', () => {
+ it('should use env-provided secret and apikey', () => {
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ const result = cm.loadOrGenerateSecrets('env-secret', 'env-apikey');
+ expect(result).toEqual({ SECRET: 'env-secret', APIKEY: 'env-apikey' });
+
+ // Should be persisted to keys.json
+ const content = JSON.parse(fs.readFileSync(keysPath, 'utf-8'));
+ expect(content.SECRET).toBe('env-secret');
+ expect(content.APIKEY).toBe('env-apikey');
+ });
+
+ it('should use existing values from keys.json when no env values provided', () => {
+ fs.writeFileSync(keysPath, JSON.stringify({ SECRET: 'file-secret', APIKEY: 'file-apikey' }));
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ const result = cm.loadOrGenerateSecrets();
+ expect(result).toEqual({ SECRET: 'file-secret', APIKEY: 'file-apikey' });
+ });
+
+ it('should generate random secrets when nothing is provided', () => {
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ const result = cm.loadOrGenerateSecrets();
+ expect(result.SECRET).toBeDefined();
+ expect(result.SECRET.length).toBeGreaterThan(0);
+ expect(result.APIKEY).toBeDefined();
+ expect(result.APIKEY.length).toBeGreaterThan(0);
+ });
+
+ it('should prefer env over file values', () => {
+ fs.writeFileSync(keysPath, JSON.stringify({ SECRET: 'file', APIKEY: 'file' }));
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ const result = cm.loadOrGenerateSecrets('env', undefined);
+ expect(result.SECRET).toBe('env');
+ expect(result.APIKEY).toBe('file');
+ });
+
+ it('should not rewrite keys.json if values have not changed', () => {
+ fs.writeFileSync(keysPath, JSON.stringify({ SECRET: 'same', APIKEY: 'same' }));
+ const mtimeBefore = fs.statSync(keysPath).mtimeMs;
+
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ cm.loadOrGenerateSecrets('same', 'same');
+
+ const mtimeAfter = fs.statSync(keysPath).mtimeMs;
+ expect(mtimeAfter).toBe(mtimeBefore);
+ });
+
+ it('should preserve other fields in keys.json when updating', () => {
+ fs.writeFileSync(keysPath, JSON.stringify({ PASSWORD_HASH: 'existing-hash', SECRET: 'old' }));
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ cm.loadOrGenerateSecrets('new-secret', 'new-api');
+
+ const content = JSON.parse(fs.readFileSync(keysPath, 'utf-8'));
+ expect(content.PASSWORD_HASH).toBe('existing-hash');
+ expect(content.SECRET).toBe('new-secret');
+ expect(content.APIKEY).toBe('new-api');
+ });
+ });
+
+ // ── hashPasswordIfNeeded ───────────────────────────────────────────────────
+
+ describe('hashPasswordIfNeeded', () => {
+ it('should return undefined when no password and no stored hash', () => {
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ expect(cm.hashPasswordIfNeeded()).toBeUndefined();
+ });
+
+ it('should return existing hash from keys.json when no password provided', () => {
+ fs.writeFileSync(keysPath, JSON.stringify({ PASSWORD_HASH: '$2a$10$existinghash' }));
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ expect(cm.hashPasswordIfNeeded()).toBe('$2a$10$existinghash');
+ });
+
+ it('should hash and store a new password', () => {
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ const hash = cm.hashPasswordIfNeeded('mypassword');
+
+ expect(hash).toBeDefined();
+ expect(bcrypt.compareSync('mypassword', hash!)).toBe(true);
+
+ // Verify stored in keys.json
+ const content = JSON.parse(fs.readFileSync(keysPath, 'utf-8'));
+ expect(content.PASSWORD_HASH).toBe(hash);
+ });
+
+ it('should return existing hash if password matches (avoids re-hash)', () => {
+ const existingHash = bcrypt.hashSync('samepassword', 10);
+ fs.writeFileSync(keysPath, JSON.stringify({ PASSWORD_HASH: existingHash }));
+
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ const result = cm.hashPasswordIfNeeded('samepassword');
+ expect(result).toBe(existingHash);
+ });
+
+ it('should re-hash if password does not match existing hash', () => {
+ const oldHash = bcrypt.hashSync('oldpassword', 10);
+ fs.writeFileSync(keysPath, JSON.stringify({ PASSWORD_HASH: oldHash }));
+
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ const newHash = cm.hashPasswordIfNeeded('newpassword');
+ expect(newHash).not.toBe(oldHash);
+ expect(bcrypt.compareSync('newpassword', newHash!)).toBe(true);
+ });
+
+ it('should re-hash if stored hash is corrupted', () => {
+ fs.writeFileSync(keysPath, JSON.stringify({ PASSWORD_HASH: 'not-a-valid-bcrypt-hash' }));
+
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ const hash = cm.hashPasswordIfNeeded('somepassword');
+ expect(hash).toBeDefined();
+ expect(bcrypt.compareSync('somepassword', hash!)).toBe(true);
+ });
+ });
+
+ // ── hashAndStorePassword ───────────────────────────────────────────────────
+
+ describe('hashAndStorePassword', () => {
+ it('should hash password and store in keys.json', () => {
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ const hash = cm.hashAndStorePassword('testpass');
+
+ expect(bcrypt.compareSync('testpass', hash)).toBe(true);
+ const content = JSON.parse(fs.readFileSync(keysPath, 'utf-8'));
+ expect(content.PASSWORD_HASH).toBe(hash);
+ });
+
+ it('should store userName when provided', () => {
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ cm.hashAndStorePassword('testpass', 'admin');
+
+ const content = JSON.parse(fs.readFileSync(keysPath, 'utf-8'));
+ expect(content.USER_NAME).toBe('admin');
+ expect(content.PASSWORD_HASH).toBeDefined();
+ });
+
+ it('should not overwrite userName field when not provided', () => {
+ fs.writeFileSync(keysPath, JSON.stringify({ USER_NAME: 'existing-user' }));
+
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ cm.hashAndStorePassword('testpass');
+
+ const content = JSON.parse(fs.readFileSync(keysPath, 'utf-8'));
+ expect(content.USER_NAME).toBe('existing-user');
+ });
+
+ it('should preserve existing keys in keys.json', () => {
+ fs.writeFileSync(keysPath, JSON.stringify({ SECRET: 'keep-me', APIKEY: 'also-keep' }));
+
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ cm.hashAndStorePassword('pass', 'user');
+
+ const content = JSON.parse(fs.readFileSync(keysPath, 'utf-8'));
+ expect(content.SECRET).toBe('keep-me');
+ expect(content.APIKEY).toBe('also-keep');
+ expect(content.USER_NAME).toBe('user');
+ expect(content.PASSWORD_HASH).toBeDefined();
+ });
+ });
+
+ // ── verifyPassword ─────────────────────────────────────────────────────────
+
+ describe('verifyPassword', () => {
+ it('should return true for matching password and hash', () => {
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ const hash = bcrypt.hashSync('correct', 10);
+ expect(cm.verifyPassword('correct', hash)).toBe(true);
+ });
+
+ it('should return false for non-matching password', () => {
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ const hash = bcrypt.hashSync('correct', 10);
+ expect(cm.verifyPassword('wrong', hash)).toBe(false);
+ });
+
+ it('should return false when storedHash is empty', () => {
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ expect(cm.verifyPassword('anything', '')).toBe(false);
+ });
+
+ it('should return false when storedHash is falsy', () => {
+ const { CredentialManager } = loadModule();
+ const cm = new CredentialManager();
+ expect(cm.verifyPassword('anything', undefined as any)).toBe(false);
+ expect(cm.verifyPassword('anything', null as any)).toBe(false);
+ });
+ });
+});
diff --git a/backend/__tests__/utils/envFileHelpers.test.ts b/backend/__tests__/utils/envFileHelpers.test.ts
new file mode 100644
index 0000000..6f059f9
--- /dev/null
+++ b/backend/__tests__/utils/envFileHelpers.test.ts
@@ -0,0 +1,269 @@
+import fs from 'fs';
+import os from 'os';
+import path from 'path';
+import { execSync } from 'child_process';
+
+jest.mock('child_process', () => ({
+ execSync: jest.fn(),
+}));
+
+// We do NOT mock fs entirely — we use a real temp directory for integration-style tests.
+// Only os.platform() and child_process are mocked where needed.
+
+describe('envFileHelpers', () => {
+ let tmpDir: string;
+ const originalPlatform = process.platform;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'envFileHelpers-'));
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
+ });
+
+ // We need to re-import each time because the module caches nothing, but jest mocks may differ.
+ function loadModule() {
+ return require('../../src/utils/envFileHelpers') as typeof import('../../src/utils/envFileHelpers');
+ }
+
+ // ── getEncEnvFilePath ──────────────────────────────────────────────────────
+
+ describe('getEncEnvFilePath', () => {
+ it('should return the path to pluton.enc.env in the given directory', () => {
+ const { getEncEnvFilePath } = loadModule();
+ expect(getEncEnvFilePath('/some/dir')).toBe(path.join('/some/dir', 'pluton.enc.env'));
+ });
+ });
+
+ // ── encEnvFileExists ───────────────────────────────────────────────────────
+
+ describe('encEnvFileExists', () => {
+ it('should return false when file does not exist', () => {
+ const { encEnvFileExists } = loadModule();
+ expect(encEnvFileExists(tmpDir)).toBe(false);
+ });
+
+ it('should return true when file exists', () => {
+ fs.writeFileSync(path.join(tmpDir, 'pluton.enc.env'), 'ENCRYPTION_KEY=abc');
+ const { encEnvFileExists } = loadModule();
+ expect(encEnvFileExists(tmpDir)).toBe(true);
+ });
+ });
+
+ // ── readEncryptionKeyFromEnvFile ───────────────────────────────────────────
+
+ describe('readEncryptionKeyFromEnvFile', () => {
+ it('should return null when file does not exist', () => {
+ const { readEncryptionKeyFromEnvFile } = loadModule();
+ expect(readEncryptionKeyFromEnvFile(tmpDir)).toBeNull();
+ });
+
+ it('should return null for an empty file', () => {
+ fs.writeFileSync(path.join(tmpDir, 'pluton.enc.env'), '');
+ const { readEncryptionKeyFromEnvFile } = loadModule();
+ expect(readEncryptionKeyFromEnvFile(tmpDir)).toBeNull();
+ });
+
+ it('should return null for a file with only comments', () => {
+ fs.writeFileSync(path.join(tmpDir, 'pluton.enc.env'), '# just a comment\n# another\n');
+ const { readEncryptionKeyFromEnvFile } = loadModule();
+ expect(readEncryptionKeyFromEnvFile(tmpDir)).toBeNull();
+ });
+
+ it('should parse ENCRYPTION_KEY', () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'pluton.enc.env'),
+ '# comment\nENCRYPTION_KEY=my-secret-key-123\n'
+ );
+ const { readEncryptionKeyFromEnvFile } = loadModule();
+ expect(readEncryptionKeyFromEnvFile(tmpDir)).toBe('my-secret-key-123');
+ });
+
+ it('should parse PLUTON_ENCRYPTION_KEY (prefixed variant)', () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'pluton.enc.env'),
+ 'PLUTON_ENCRYPTION_KEY=prefixed-key-456\n'
+ );
+ const { readEncryptionKeyFromEnvFile } = loadModule();
+ expect(readEncryptionKeyFromEnvFile(tmpDir)).toBe('prefixed-key-456');
+ });
+
+ it('should return null when key has empty value', () => {
+ fs.writeFileSync(path.join(tmpDir, 'pluton.enc.env'), 'ENCRYPTION_KEY=\n');
+ const { readEncryptionKeyFromEnvFile } = loadModule();
+ expect(readEncryptionKeyFromEnvFile(tmpDir)).toBeNull();
+ });
+
+ it('should ignore unrelated keys', () => {
+ fs.writeFileSync(path.join(tmpDir, 'pluton.enc.env'), 'OTHER_KEY=value\nFOO=bar\n');
+ const { readEncryptionKeyFromEnvFile } = loadModule();
+ expect(readEncryptionKeyFromEnvFile(tmpDir)).toBeNull();
+ });
+
+ it('should handle lines without equals sign', () => {
+ fs.writeFileSync(path.join(tmpDir, 'pluton.enc.env'), 'no-equals\nENCRYPTION_KEY=ok\n');
+ const { readEncryptionKeyFromEnvFile } = loadModule();
+ expect(readEncryptionKeyFromEnvFile(tmpDir)).toBe('ok');
+ });
+
+ it('should handle values containing equals signs', () => {
+ fs.writeFileSync(path.join(tmpDir, 'pluton.enc.env'), 'ENCRYPTION_KEY=base64==value\n');
+ const { readEncryptionKeyFromEnvFile } = loadModule();
+ expect(readEncryptionKeyFromEnvFile(tmpDir)).toBe('base64==value');
+ });
+ });
+
+ // ── writeEncryptionKeyToEnvFile ───────────────────────────────────────────
+
+ describe('writeEncryptionKeyToEnvFile', () => {
+ it('should create the file with the encryption key', () => {
+ const { writeEncryptionKeyToEnvFile, readEncryptionKeyFromEnvFile } = loadModule();
+ writeEncryptionKeyToEnvFile(tmpDir, 'write-test-key');
+
+ const filePath = path.join(tmpDir, 'pluton.enc.env');
+ expect(fs.existsSync(filePath)).toBe(true);
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ expect(content).toContain('ENCRYPTION_KEY=write-test-key');
+ expect(content).toContain('# Pluton Encryption Key');
+
+ // Round-trip: should be readable
+ expect(readEncryptionKeyFromEnvFile(tmpDir)).toBe('write-test-key');
+ });
+
+ it('should create parent directories if they do not exist', () => {
+ const { writeEncryptionKeyToEnvFile } = loadModule();
+ const nested = path.join(tmpDir, 'sub', 'dir');
+ writeEncryptionKeyToEnvFile(nested, 'nested-key');
+ expect(fs.existsSync(path.join(nested, 'pluton.enc.env'))).toBe(true);
+ });
+
+ it('should overwrite an existing file', () => {
+ const { writeEncryptionKeyToEnvFile, readEncryptionKeyFromEnvFile } = loadModule();
+ writeEncryptionKeyToEnvFile(tmpDir, 'first-key');
+ writeEncryptionKeyToEnvFile(tmpDir, 'second-key');
+ expect(readEncryptionKeyFromEnvFile(tmpDir)).toBe('second-key');
+ });
+ });
+
+ // ── applyStrictPermissions ────────────────────────────────────────────────
+
+ describe('applyStrictPermissions', () => {
+ it('should call chmodSync on non-Windows platforms', () => {
+ const platformSpy = jest.spyOn(os, 'platform').mockReturnValue('linux' as any);
+ jest.resetModules();
+ const { applyStrictPermissions } = loadModule();
+
+ const filePath = path.join(tmpDir, 'test-file');
+ fs.writeFileSync(filePath, 'data');
+
+ const chmodSpy = jest.spyOn(fs, 'chmodSync');
+ applyStrictPermissions(filePath);
+ expect(chmodSpy).toHaveBeenCalledWith(filePath, 0o600);
+ chmodSpy.mockRestore();
+ platformSpy.mockRestore();
+ });
+
+ it('should call icacls on Windows', () => {
+ const platformSpy = jest.spyOn(os, 'platform').mockReturnValue('win32' as any);
+ jest.resetModules();
+ const { applyStrictPermissions } = loadModule();
+ // After resetModules the re-loaded module gets a fresh child_process mock;
+ // re-require it so we reference the same instance.
+ const { execSync: freshExecSync } = require('child_process');
+
+ const filePath = path.join(tmpDir, 'test-file');
+ fs.writeFileSync(filePath, 'data');
+
+ applyStrictPermissions(filePath);
+
+ expect(freshExecSync).toHaveBeenCalledTimes(4);
+ expect(freshExecSync).toHaveBeenCalledWith(
+ expect.stringContaining('/inheritance:r'),
+ expect.anything()
+ );
+ expect(freshExecSync).toHaveBeenCalledWith(
+ expect.stringContaining('NT AUTHORITY\\SYSTEM'),
+ expect.anything()
+ );
+ expect(freshExecSync).toHaveBeenCalledWith(
+ expect.stringContaining('BUILTIN\\Administrators'),
+ expect.anything()
+ );
+ platformSpy.mockRestore();
+ });
+
+ it('should not throw if chmod fails', () => {
+ const platformSpy = jest.spyOn(os, 'platform').mockReturnValue('linux' as any);
+ jest.resetModules();
+ const { applyStrictPermissions } = loadModule();
+
+ const chmodSpy = jest.spyOn(fs, 'chmodSync').mockImplementation(() => {
+ throw new Error('Permission denied');
+ });
+ expect(() => applyStrictPermissions('/nonexistent')).not.toThrow();
+ chmodSpy.mockRestore();
+ platformSpy.mockRestore();
+ });
+ });
+
+ // ── verifyFilePermissions ─────────────────────────────────────────────────
+
+ describe('verifyFilePermissions', () => {
+ it('should return true when file does not exist', () => {
+ const { verifyFilePermissions } = loadModule();
+ expect(verifyFilePermissions(path.join(tmpDir, 'nope'))).toBe(true);
+ });
+
+ it('should return true on Windows (no check performed)', () => {
+ const platformSpy = jest.spyOn(os, 'platform').mockReturnValue('win32' as any);
+ jest.resetModules();
+ const { verifyFilePermissions } = loadModule();
+
+ const filePath = path.join(tmpDir, 'win-file');
+ fs.writeFileSync(filePath, 'data');
+ expect(verifyFilePermissions(filePath)).toBe(true);
+ platformSpy.mockRestore();
+ });
+
+ it('should return true when permissions are 600 on Unix', () => {
+ const platformSpy = jest.spyOn(os, 'platform').mockReturnValue('linux' as any);
+ jest.resetModules();
+ const { verifyFilePermissions } = loadModule();
+
+ const filePath = path.join(tmpDir, 'strict-file');
+ fs.writeFileSync(filePath, 'data');
+
+ const statSpy = jest.spyOn(fs, 'statSync').mockReturnValue({
+ mode: 0o100600,
+ } as any);
+
+ expect(verifyFilePermissions(filePath)).toBe(true);
+ statSpy.mockRestore();
+ platformSpy.mockRestore();
+ });
+
+ it('should return false and warn when permissions are too open on Unix', () => {
+ const platformSpy = jest.spyOn(os, 'platform').mockReturnValue('linux' as any);
+ jest.resetModules();
+ const { verifyFilePermissions } = loadModule();
+
+ const filePath = path.join(tmpDir, 'open-file');
+ fs.writeFileSync(filePath, 'data');
+
+ const statSpy = jest.spyOn(fs, 'statSync').mockReturnValue({
+ mode: 0o100644,
+ } as any);
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation();
+
+ expect(verifyFilePermissions(filePath)).toBe(false);
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('644'));
+ statSpy.mockRestore();
+ warnSpy.mockRestore();
+ platformSpy.mockRestore();
+ });
+ });
+});
diff --git a/backend/__tests__/utils/installHelpers.test.ts b/backend/__tests__/utils/installHelpers.test.ts
index be99f3c..4bfa888 100644
--- a/backend/__tests__/utils/installHelpers.test.ts
+++ b/backend/__tests__/utils/installHelpers.test.ts
@@ -6,6 +6,8 @@ import {
isLinuxDesktop,
isKeyringPlatform,
requiresKeyringSetup,
+ isDesktopPlatform,
+ requiresDesktopSetup,
} from '../../src/utils/installHelpers';
describe('installHelpers', () => {
@@ -318,4 +320,23 @@ describe('installHelpers', () => {
expect(requiresKeyringSetup()).toBe(false);
});
});
+
+ describe('isDesktopPlatform (alias)', () => {
+ it('should be an alias for isKeyringPlatform', () => {
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+ expect(isDesktopPlatform()).toBe(isKeyringPlatform());
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ expect(isDesktopPlatform()).toBe(isKeyringPlatform());
+ });
+ });
+
+ describe('requiresDesktopSetup (alias)', () => {
+ it('should be an alias for requiresKeyringSetup', () => {
+ (process as any).pkg = { entrypoint: '/snapshot/app/index.js' };
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+ expect(requiresDesktopSetup()).toBe(requiresKeyringSetup());
+ delete (process as any).pkg;
+ expect(requiresDesktopSetup()).toBe(requiresKeyringSetup());
+ });
+ });
});
diff --git a/backend/src/controllers/SetupController.ts b/backend/src/controllers/SetupController.ts
index ece5445..b7e9925 100644
--- a/backend/src/controllers/SetupController.ts
+++ b/backend/src/controllers/SetupController.ts
@@ -1,7 +1,9 @@
import { Request, Response } from 'express';
-import { keyringService, KeyringCredentials } from '../services/KeyringService';
+import fs from 'fs';
import { configService } from '../services/ConfigService';
-import { requiresKeyringSetup, isBinaryMode } from '../utils/installHelpers';
+import { requiresDesktopSetup, isBinaryMode } from '../utils/installHelpers';
+import { writeEncryptionKeyToEnvFile, encEnvFileExists } from '../utils/envFileHelpers';
+import { appPaths } from '../utils/AppPaths';
import { initSetup } from '../utils/initSetup';
import { db } from '../db';
import { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';
@@ -14,14 +16,17 @@ export class SetupController {
try {
const isSetupPending = configService.isSetupPending();
const isBinary = isBinaryMode();
- const requiresKeyring = requiresKeyringSetup();
+ const requiresSetup = requiresDesktopSetup();
+ const hasEncEnvFile = encEnvFileExists(appPaths.getDataDir());
res.json({
success: true,
data: {
setupPending: isSetupPending,
isBinary,
- requiresKeyringSetup: requiresKeyring,
+ requiresSetup,
+ requiresKeyringSetup: requiresSetup, // backward compat
+ hasEncEnvFile,
platform: process.platform,
},
});
@@ -35,7 +40,8 @@ export class SetupController {
/**
* Complete the initial setup with credentials
- * This endpoint stores credentials in the OS keyring and initializes the app
+ * This endpoint stores the encryption key in pluton.enc.env and
+ * credentials in keys.json, then initializes the app
*/
async completeSetup(req: Request, res: Response) {
try {
@@ -47,11 +53,12 @@ export class SetupController {
});
}
- // Verify we're on a keyring-supported platform
- if (!requiresKeyringSetup()) {
+ // Verify we're on a desktop platform (binary install)
+ if (!requiresDesktopSetup()) {
return res.status(400).json({
success: false,
- error: 'Keyring setup is only available on Windows and macOS binary installations.',
+ error:
+ 'Desktop setup is only available on Windows, macOS and Linux desktop binary installations.',
});
}
@@ -89,23 +96,12 @@ export class SetupController {
});
}
- // Store credentials in the OS keyring
- const credentials: KeyringCredentials = {
- ENCRYPTION_KEY: encryptionKey,
- USER_NAME: userName,
- USER_PASSWORD: userPassword,
- };
-
- const stored = await keyringService.setAllCredentials(credentials);
-
- if (!stored) {
- return res.status(500).json({
- success: false,
- error: 'Failed to store credentials in the system keyring',
- });
- }
+ // Store encryption key in pluton.enc.env (replaces keyring storage)
+ writeEncryptionKeyToEnvFile(appPaths.getDataDir(), encryptionKey);
- // Update ConfigService with the new credentials
+ // Persist credentials to disk first (idempotent — safe to redo on retry).
+ // completeSetup hashes the password, writes keys.json, and updates in-memory
+ // config, but we will roll back the in-memory flag if initSetup fails.
configService.completeSetup({
ENCRYPTION_KEY: encryptionKey,
USER_NAME: userName,
@@ -113,7 +109,14 @@ export class SetupController {
});
// Run the initial setup (creates database tables, default settings, etc.)
- await initSetup(db as unknown as BetterSQLite3Database);
+ // If this fails, re-mark setup as pending so the wizard can be retried
+ // in the same process. The persisted files stay — they're idempotent.
+ try {
+ await initSetup(db as unknown as BetterSQLite3Database);
+ } catch (initError) {
+ configService.markSetupPending();
+ throw initError;
+ }
res.json({
success: true,
@@ -129,25 +132,34 @@ export class SetupController {
}
/**
- * Check if keyring is available on this system
+ * Check if the system is ready for setup (write permissions, etc.)
+ * Previously checked keyring availability; now checks env file writability.
+ * Kept at the same endpoint for backward compatibility.
*/
async checkKeyringAvailability(req: Request, res: Response) {
try {
- const isSupported = keyringService.isPlatformSupported();
- const isAvailable = await keyringService.waitForInitialization();
+ const dataDir = appPaths.getDataDir();
+ let writable = false;
+ try {
+ fs.accessSync(dataDir, fs.constants.W_OK);
+ writable = true;
+ } catch {
+ writable = false;
+ }
res.json({
success: true,
data: {
- platformSupported: isSupported,
- keyringAvailable: isAvailable,
+ platformSupported: requiresDesktopSetup(),
+ keyringAvailable: writable, // backward compat field name
+ dataDirWritable: writable,
platform: process.platform,
},
});
} catch (error: any) {
res.status(500).json({
success: false,
- error: error.message || 'Failed to check keyring availability',
+ error: error.message || 'Failed to check system availability',
});
}
}
diff --git a/backend/src/index.ts b/backend/src/index.ts
index b183bdc..6c826ff 100644
--- a/backend/src/index.ts
+++ b/backend/src/index.ts
@@ -5,7 +5,7 @@ import { createApp } from './createApp';
import { db } from './db';
import { initSetup } from './utils/initSetup';
import { configService, ConfigService } from './services/ConfigService';
-import { requiresKeyringSetup } from './utils/installHelpers';
+import { requiresDesktopSetup } from './utils/installHelpers';
// Export main entry point for use as a library
export { createApp } from './createApp';
@@ -30,14 +30,14 @@ if (isMainModule || isDevelopment) {
return; // handlePasswordReset calls process.exit(), but just in case
}
- // For binary installations on Windows/macOS, try to load credentials from keyring
- if (requiresKeyringSetup() && configService.isSetupPending()) {
- console.log('Attempting to load credentials from system keyring...');
- const loaded = await ConfigService.reinitializeWithKeyringCredentials();
+ // For binary installations on desktop platforms, try to load credentials from env file or keyring
+ if (requiresDesktopSetup() && configService.isSetupPending()) {
+ console.log('Attempting to load credentials from env file or system keyring...');
+ const loaded = await ConfigService.reinitializeFromEnvFileOrKeyring();
if (loaded) {
- console.log('Credentials loaded from keyring successfully.');
+ console.log('Credentials loaded successfully.');
} else {
- console.log('No credentials found in keyring. Waiting for initial setup...');
+ console.log('No credentials found. Waiting for initial setup...');
}
}
@@ -91,26 +91,20 @@ if (isMainModule || isDevelopment) {
}
});
- // Graceful shutdown handling for Docker
- process.on('SIGTERM', async () => {
- console.log('SIGTERM received, shutting down gracefully...');
+ // Handle graceful shutdown
+ const gracefulShutdown = () => {
+ console.log('Shutting down gracefully...');
const forceExit = setTimeout(() => {
process.exit(1);
- }, 30000); // 30 seconds timeout
-
+ }, 30000);
server.close(() => {
+ console.log('HTTP server closed.');
clearTimeout(forceExit);
- console.log('Server closed');
process.exit(0);
});
- });
+ };
- process.on('SIGINT', async () => {
- console.log('SIGINT received, shutting down gracefully...');
- server.close(() => {
- console.log('Server closed');
- process.exit(0);
- });
- });
+ process.on('SIGINT', gracefulShutdown);
+ process.on('SIGTERM', gracefulShutdown);
})();
}
diff --git a/backend/src/services/ConfigService.ts b/backend/src/services/ConfigService.ts
index 3ee49c2..d488067 100644
--- a/backend/src/services/ConfigService.ts
+++ b/backend/src/services/ConfigService.ts
@@ -1,12 +1,10 @@
import { z } from 'zod';
import fs from 'fs';
-import crypto from 'crypto';
-import bcrypt from 'bcryptjs';
import { appPaths } from '../utils/AppPaths';
import path from 'path';
-import { requiresKeyringSetup } from '../utils/installHelpers';
-
-const BCRYPT_SALT_ROUNDS = 10;
+import { requiresDesktopSetup } from '../utils/installHelpers';
+import { readEncryptionKeyFromEnvFile, verifyFilePermissions } from '../utils/envFileHelpers';
+import { credentialManager } from './CredentialManager';
// Schema for the .env config file (with optional sensitive fields for setup mode)
const baseConfigSchema = z.object({
@@ -86,7 +84,6 @@ export type SetupModeConfig = z.infer<typeof setupModeConfigSchema>;
class ConfigService {
private static instance: ConfigService;
private _config!: AppConfig | SetupModeConfig;
- private keysPath: string = '';
private _isSetupPending: boolean = false;
/**
@@ -125,8 +122,22 @@ class ConfigService {
normalizedEnv.USER_PASSWORD = normalizedEnv.PLUTON_USER_PASSWORD;
}
+ // 1b. Load ENCRYPTION_KEY from pluton.enc.env if not already in process env
+ // On server installs, the file lives in /etc/pluton/; on desktop, in the data dir.
+ const dataDir = appPaths.getDataDir();
+ if (!normalizedEnv.ENCRYPTION_KEY) {
+ const serverEncEnvPath = '/etc/pluton/pluton.enc.env';
+ const envFileKey =
+ (process.platform !== 'win32' && fs.existsSync(serverEncEnvPath)
+ ? readEncryptionKeyFromEnvFile('/etc/pluton')
+ : null) ?? readEncryptionKeyFromEnvFile(dataDir);
+ if (envFileKey) {
+ normalizedEnv.ENCRYPTION_KEY = envFileKey;
+ console.log('[ConfigService] Loaded ENCRYPTION_KEY from pluton.enc.env');
+ }
+ }
+
const envConfig = configSchema.partial().parse(normalizedEnv);
- // Initialize or load SECRET and APIKEY
// 2. Layer user's config.json file
let fileConfig: Record<string, any> = {};
@@ -163,12 +174,11 @@ class ConfigService {
);
}
- // 3. Load or Generate System Secrets (New logic)
- this.keysPath = path.join(appPaths.getDataDir(), 'keys.json');
- const secrets = this.loadOrGenerateSecrets(envConfig.SECRET, envConfig.APIKEY);
+ // 3. Load or Generate System Secrets
+ const secrets = credentialManager.loadOrGenerateSecrets(envConfig.SECRET, envConfig.APIKEY);
// 4. Hash the password if provided via env var
- const passwordHash = this.hashPasswordIfNeeded(envConfig.USER_PASSWORD);
+ const passwordHash = credentialManager.hashPasswordIfNeeded(envConfig.USER_PASSWORD);
// 5. Merge all sources (file overrides env, which overrides defaults)
const mergedConfig = {
@@ -185,9 +195,9 @@ class ConfigService {
const parsedConfig = finalConfigSchema.safeParse(mergedConfig);
if (!parsedConfig.success) {
- // Check if we're in binary mode on a keyring-supported platform
+ // Check if we're in binary mode on a desktop platform
// In this case, we can start in "setup pending" mode
- if (requiresKeyringSetup()) {
+ if (requiresDesktopSetup()) {
console.log('⏳ [ConfigService] Binary mode detected without credentials.');
console.log('⏳ [ConfigService] Starting in setup pending mode...');
console.log('⏳ [ConfigService] Please complete the initial setup via the web interface.');
@@ -222,81 +232,17 @@ class ConfigService {
}
this._config = parsedConfig.data;
- console.log('✅ Environment configuration loaded and validated successfully.');
- }
- private loadOrGenerateSecrets(envSecret?: string, envApiKey?: string) {
- let keysFileContent: Record<string, any> = {};
+ // Verify permissions on sensitive files
+ verifyFilePermissions(credentialManager.getKeysPath());
+ const serverEncEnvPath = '/etc/pluton/pluton.enc.env';
+ const encEnvPath =
+ process.platform !== 'win32' && fs.existsSync(serverEncEnvPath)
+ ? serverEncEnvPath
+ : path.join(dataDir, 'pluton.enc.env');
+ verifyFilePermissions(encEnvPath);
- // Read existing keys.json
- try {
- if (fs.existsSync(this.keysPath)) {
- keysFileContent = JSON.parse(fs.readFileSync(this.keysPath, 'utf-8'));
- }
- } catch (error) {
- // Ignore read errors, we will overwrite/create
- }
-
- // Priority: Env > Existing File > Generate
- const finalSecret =
- envSecret || keysFileContent.SECRET || crypto.randomBytes(32).toString('hex');
- const finalApiKey =
- envApiKey || keysFileContent.APIKEY || crypto.randomBytes(24).toString('hex');
-
- // Save if something changed or didn't exist
- if (finalSecret !== keysFileContent.SECRET || finalApiKey !== keysFileContent.APIKEY) {
- try {
- const newContent = {
- ...keysFileContent,
- SECRET: finalSecret,
- APIKEY: finalApiKey,
- };
-
- // Ensure dir exists (synchronously, as ConfigService is sync)
- const dir = path.dirname(this.keysPath);
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
-
- fs.writeFileSync(this.keysPath, JSON.stringify(newContent, null, 2), { mode: 0o600 });
- console.log(`[ConfigService] Secrets updated in ${this.keysPath}`);
- } catch (error) {
- console.error(`[ConfigService] Failed to save secrets to keys.json: ${error}`);
- }
- }
-
- return { SECRET: finalSecret, APIKEY: finalApiKey };
- }
-
- /**
- * Hash a plaintext password and store the hash in keys.json.
- * If no plaintext password is provided, returns the existing hash from keys.json (if any).
- */
- private hashPasswordIfNeeded(plaintextPassword?: string): string | undefined {
- let keysFileContent: Record<string, any> = {};
- try {
- if (fs.existsSync(this.keysPath)) {
- keysFileContent = JSON.parse(fs.readFileSync(this.keysPath, 'utf-8'));
- }
- } catch (error) {
- // Ignore read errors
- }
-
- // If a plaintext password is provided (from env var), hash it and store
- if (plaintextPassword) {
- const hash = bcrypt.hashSync(plaintextPassword, BCRYPT_SALT_ROUNDS);
- try {
- const newContent = { ...keysFileContent, PASSWORD_HASH: hash };
- const dir = path.dirname(this.keysPath);
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(this.keysPath, JSON.stringify(newContent, null, 2), { mode: 0o600 });
- console.log('[ConfigService] Password hash stored in keys.json');
- } catch (error) {
- console.error(`[ConfigService] Failed to save password hash to keys.json: ${error}`);
- }
- return hash;
- }
-
- // Otherwise, return the existing hash from keys.json (for keyring/setup flow)
- return keysFileContent.PASSWORD_HASH || undefined;
+ console.log('✅ Environment configuration loaded and validated successfully.');
}
/**
@@ -304,33 +250,8 @@ class ConfigService {
* Used by SetupController and password change endpoints.
*/
public hashAndStorePassword(plaintextPassword: string, userName?: string): string {
- const hash = bcrypt.hashSync(plaintextPassword, BCRYPT_SALT_ROUNDS);
-
- let keysFileContent: Record<string, any> = {};
- try {
- if (fs.existsSync(this.keysPath)) {
- keysFileContent = JSON.parse(fs.readFileSync(this.keysPath, 'utf-8'));
- }
- } catch (error) {
- // Ignore read errors
- }
-
- try {
- const newContent: Record<string, any> = { ...keysFileContent, PASSWORD_HASH: hash };
- if (userName) {
- newContent.USER_NAME = userName;
- }
- const dir = path.dirname(this.keysPath);
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(this.keysPath, JSON.stringify(newContent, null, 2), { mode: 0o600 });
- console.log('[ConfigService] Password hash updated in keys.json');
- } catch (error) {
- console.error(`[ConfigService] Failed to save password hash to keys.json: ${error}`);
- }
-
- // Update in-memory config
+ const hash = credentialManager.hashAndStorePassword(plaintextPassword, userName);
(this._config as any).PASSWORD_HASH = hash;
-
return hash;
}
@@ -339,8 +260,7 @@ class ConfigService {
*/
public verifyPassword(plaintextPassword: string): boolean {
const hash = (this._config as any).PASSWORD_HASH;
- if (!hash) return false;
- return bcrypt.compareSync(plaintextPassword, hash);
+ return credentialManager.verifyPassword(plaintextPassword, hash);
}
/**
@@ -363,7 +283,7 @@ class ConfigService {
/**
* Complete the initial setup by updating config with credentials.
- * This is called after credentials are stored in the keyring.
+ * This is called after credentials are stored in the env file.
*/
public completeSetup(credentials: {
ENCRYPTION_KEY: string;
@@ -375,7 +295,7 @@ class ConfigService {
}
// Hash the password and store both USER_NAME and PASSWORD_HASH in keys.json
- const passwordHash = this.hashAndStorePassword(
+ const passwordHash = credentialManager.hashAndStorePassword(
credentials.USER_PASSWORD,
credentials.USER_NAME
);
@@ -389,104 +309,54 @@ class ConfigService {
} as AppConfig;
this._isSetupPending = false;
- console.log('✅ [ConfigService] Setup completed. Credentials loaded from keyring.');
+ console.log('✅ [ConfigService] Setup completed. Credentials stored securely.');
+ }
+
+ /**
+ * Roll back in-memory state to setup-pending after a post-setup failure
+ * (e.g. initSetup threw). The persisted files (pluton.enc.env, keys.json) are
+ * left in place — they are idempotent and will be picked up on next restart.
+ */
+ public markSetupPending(): void {
+ this._isSetupPending = true;
+ (this._config as any).SETUP_PENDING = true;
+ console.log('⚠️ [ConfigService] Setup rolled back to pending state.');
}
/**
- * Reinitialize ConfigService with credentials from keyring.
- * Used after initial setup to reload config with actual credentials.
+ * Reinitialize ConfigService by loading ENCRYPTION_KEY from pluton.enc.env (preferred)
+ * or by migrating from the OS keyring (legacy desktop installs).
*
* On subsequent startups (keys.json already has USER_NAME + PASSWORD_HASH),
- * only ENCRYPTION_KEY is loaded from the keyring. USER_NAME and PASSWORD_HASH
- * are read from keys.json to avoid overwriting CLI password resets.
+ * only ENCRYPTION_KEY is needed from the env file (or keyring for migration).
+ * USER_NAME and PASSWORD_HASH are read from keys.json to avoid overwriting CLI password resets.
*/
- public static async reinitializeWithKeyringCredentials(): Promise<boolean> {
+ public static async reinitializeFromEnvFileOrKeyring(): Promise<boolean> {
if (!ConfigService.instance || !ConfigService.instance._isSetupPending) {
return false;
}
- try {
- // Dynamically import keyring service to avoid circular dependencies
- const { keyringService } = await import('./KeyringService');
- const credentials = await keyringService.getAllCredentials();
-
- if (!credentials.ENCRYPTION_KEY) {
- return false;
- }
-
- // Check if keys.json already has USER_NAME and PASSWORD_HASH from a previous setup
- // or CLI password reset. If so, use those instead of re-hashing from keyring.
- let keysFileContent: Record<string, any> = {};
- try {
- if (fs.existsSync(ConfigService.instance.keysPath)) {
- keysFileContent = JSON.parse(fs.readFileSync(ConfigService.instance.keysPath, 'utf-8'));
- }
- } catch {
- // Ignore read errors
- }
-
- const existingPasswordHash = keysFileContent.PASSWORD_HASH;
- const existingUserName = keysFileContent.USER_NAME;
-
- if (existingPasswordHash && existingUserName) {
- // Subsequent startup: keys.json is authoritative for auth credentials.
- // Only ENCRYPTION_KEY comes from the keyring.
- ConfigService.instance._config = {
- ...ConfigService.instance._config,
- ENCRYPTION_KEY: credentials.ENCRYPTION_KEY,
- USER_NAME: existingUserName,
- USER_PASSWORD: credentials.USER_PASSWORD || '',
- PASSWORD_HASH: existingPasswordHash,
- SETUP_PENDING: false,
- } as AppConfig;
- ConfigService.instance._isSetupPending = false;
- console.log(
- '✅ [ConfigService] Credentials loaded (ENCRYPTION_KEY from keyring, auth from keys.json).'
- );
- return true;
- }
-
- if (existingPasswordHash && !existingUserName && credentials.USER_NAME) {
- // Migration: keys.json has PASSWORD_HASH from prior version but no USER_NAME.
- // Copy USER_NAME from keyring to keys.json without re-hashing the password.
- try {
- const newContent = { ...keysFileContent, USER_NAME: credentials.USER_NAME };
- fs.writeFileSync(ConfigService.instance.keysPath, JSON.stringify(newContent, null, 2), {
- mode: 0o600,
- });
- console.log('[ConfigService] Migrated USER_NAME from keyring to keys.json');
- } catch (error) {
- console.error(`[ConfigService] Failed to migrate USER_NAME to keys.json: ${error}`);
- }
-
- ConfigService.instance._config = {
- ...ConfigService.instance._config,
- ENCRYPTION_KEY: credentials.ENCRYPTION_KEY,
- USER_NAME: credentials.USER_NAME,
- USER_PASSWORD: credentials.USER_PASSWORD || '',
- PASSWORD_HASH: existingPasswordHash,
- SETUP_PENDING: false,
- } as AppConfig;
- ConfigService.instance._isSetupPending = false;
- console.log(
- '✅ [ConfigService] Credentials loaded (migrated USER_NAME from keyring to keys.json).'
- );
- return true;
- }
+ const result = await credentialManager.loadCredentialsFromEnvFileOrKeyring();
- // If keys.json has no PASSWORD_HASH, this is a fresh install (or data was wiped).
- // Even if the keyring has credentials from a previous installation, do NOT
- // auto-configure — let the user go through the setup wizard instead.
- // The ENCRYPTION_KEY remains in the keyring and can be reused during setup.
- console.log(
- '[ConfigService] Keyring has credentials but keys.json has no PASSWORD_HASH. Awaiting setup wizard.'
- );
- } catch (error) {
- console.error('[ConfigService] Failed to reinitialize with keyring credentials:', error);
+ if (result.loaded && result.config) {
+ ConfigService.instance._config = {
+ ...ConfigService.instance._config,
+ ...result.config,
+ } as AppConfig;
+ ConfigService.instance._isSetupPending = false;
+ return true;
}
return false;
}
+
+ /**
+ * @deprecated Use reinitializeFromEnvFileOrKeyring() instead.
+ * Kept for backward compatibility during migration period.
+ */
+ public static async reinitializeWithKeyringCredentials(): Promise<boolean> {
+ return ConfigService.reinitializeFromEnvFileOrKeyring();
+ }
}
// Export a single, ready-to-use instance (the singleton)
diff --git a/backend/src/services/CredentialManager.ts b/backend/src/services/CredentialManager.ts
new file mode 100644
index 0000000..005503f
--- /dev/null
+++ b/backend/src/services/CredentialManager.ts
@@ -0,0 +1,242 @@
+import fs from 'fs';
+import crypto from 'crypto';
+import bcrypt from 'bcryptjs';
+import path from 'path';
+import { appPaths } from '../utils/AppPaths';
+import {
+ readEncryptionKeyFromEnvFile,
+ writeEncryptionKeyToEnvFile,
+ applyStrictPermissions,
+} from '../utils/envFileHelpers';
+
+const BCRYPT_SALT_ROUNDS = 10;
+
+class CredentialManager {
+ private keysPath: string;
+ private dataDir: string;
+
+ constructor() {
+ this.dataDir = appPaths.getDataDir();
+ this.keysPath = path.join(this.dataDir, 'keys.json');
+ }
+
+ // ---------------------------------------------------------------------------
+ // keys.json I/O helpers
+ // ---------------------------------------------------------------------------
+
+ public getKeysPath(): string {
+ return this.keysPath;
+ }
+
+ public readKeysFile(): Record<string, any> {
+ try {
+ if (fs.existsSync(this.keysPath)) {
+ return JSON.parse(fs.readFileSync(this.keysPath, 'utf-8'));
+ }
+ } catch {
+ // Ignore read errors
+ }
+ return {};
+ }
+
+ public writeKeysFile(content: Record<string, any>): void {
+ const dir = path.dirname(this.keysPath);
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(this.keysPath, JSON.stringify(content, null, 2), { mode: 0o600 });
+ applyStrictPermissions(this.keysPath);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Secrets (SECRET + APIKEY)
+ // ---------------------------------------------------------------------------
+
+ public loadOrGenerateSecrets(
+ envSecret?: string,
+ envApiKey?: string
+ ): { SECRET: string; APIKEY: string } {
+ const keysFileContent = this.readKeysFile();
+
+ const finalSecret =
+ envSecret || keysFileContent.SECRET || crypto.randomBytes(32).toString('hex');
+ const finalApiKey =
+ envApiKey || keysFileContent.APIKEY || crypto.randomBytes(24).toString('hex');
+
+ if (finalSecret !== keysFileContent.SECRET || finalApiKey !== keysFileContent.APIKEY) {
+ try {
+ this.writeKeysFile({
+ ...keysFileContent,
+ SECRET: finalSecret,
+ APIKEY: finalApiKey,
+ });
+ console.log(`[CredentialManager] Secrets updated in ${this.keysPath}`);
+ } catch (error) {
+ console.error(`[CredentialManager] Failed to save secrets to keys.json: ${error}`);
+ }
+ }
+
+ return { SECRET: finalSecret, APIKEY: finalApiKey };
+ }
+
+ // ---------------------------------------------------------------------------
+ // Password hashing
+ // ---------------------------------------------------------------------------
+
+ /**
+ * Hash a plaintext password and store the hash in keys.json.
+ * If no plaintext password is provided, returns the existing hash from keys.json (if any).
+ */
+ public hashPasswordIfNeeded(plaintextPassword?: string): string | undefined {
+ const keysFileContent = this.readKeysFile();
+
+ if (plaintextPassword) {
+ // If a hash already exists, check if the password still matches.
+ // This avoids rewriting keys.json with a new hash on every restart.
+ if (keysFileContent.PASSWORD_HASH) {
+ try {
+ if (bcrypt.compareSync(plaintextPassword, keysFileContent.PASSWORD_HASH)) {
+ return keysFileContent.PASSWORD_HASH;
+ }
+ } catch {
+ // Corrupted hash — fall through and re-hash
+ }
+ }
+
+ const hash = bcrypt.hashSync(plaintextPassword, BCRYPT_SALT_ROUNDS);
+ try {
+ this.writeKeysFile({ ...keysFileContent, PASSWORD_HASH: hash });
+ console.log('[CredentialManager] Password hash stored in keys.json');
+ } catch (error) {
+ console.error(
+ `[CredentialManager] Failed to save password hash to keys.json: ${error}`
+ );
+ }
+ return hash;
+ }
+
+ return keysFileContent.PASSWORD_HASH || undefined;
+ }
+
+ /**
+ * Hash a password and store the hash (and optionally username) in keys.json.
+ * Used by SetupController and password change endpoints.
+ */
+ public hashAndStorePassword(plaintextPassword: string, userName?: string): string {
+ const hash = bcrypt.hashSync(plaintextPassword, BCRYPT_SALT_ROUNDS);
+ const keysFileContent = this.readKeysFile();
+
+ try {
+ const newContent: Record<string, any> = { ...keysFileContent, PASSWORD_HASH: hash };
+ if (userName) {
+ newContent.USER_NAME = userName;
+ }
+ this.writeKeysFile(newContent);
+ console.log('[CredentialManager] Password hash updated in keys.json');
+ } catch (error) {
+ console.error(
+ `[CredentialManager] Failed to save password hash to keys.json: ${error}`
+ );
+ }
+
+ return hash;
+ }
+
+ /**
+ * Verify a plaintext password against a stored bcrypt hash.
+ */
+ public verifyPassword(plaintextPassword: string, storedHash: string): boolean {
+ if (!storedHash) return false;
+ return bcrypt.compareSync(plaintextPassword, storedHash);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Credential loading (env file + keyring migration)
+ // ---------------------------------------------------------------------------
+
+ /**
+ * Load credentials from pluton.enc.env (preferred) or migrate from OS keyring (legacy).
+ * Returns the config values to apply if credentials were found.
+ */
+ public async loadCredentialsFromEnvFileOrKeyring(): Promise<{
+ loaded: boolean;
+ config?: Record<string, any>;
+ }> {
+ // --- Step 1: Try loading ENCRYPTION_KEY from pluton.enc.env ---
+ let encryptionKey = readEncryptionKeyFromEnvFile(this.dataDir);
+
+ // --- Step 2: If no env file, try migrating from keyring (legacy) ---
+ if (!encryptionKey) {
+ try {
+ const { keyringService } = await import('./KeyringService');
+ const isAvailable = await keyringService.waitForInitialization();
+
+ if (isAvailable) {
+ const credentials = await keyringService.getAllCredentials();
+
+ if (credentials.ENCRYPTION_KEY) {
+ // Migrate ENCRYPTION_KEY from keyring to pluton.enc.env
+ writeEncryptionKeyToEnvFile(this.dataDir, credentials.ENCRYPTION_KEY);
+ encryptionKey = credentials.ENCRYPTION_KEY;
+ console.log(
+ '✅ [CredentialManager] Migrated ENCRYPTION_KEY from keyring to pluton.enc.env'
+ );
+
+ // Also migrate USER_NAME from keyring to keys.json if missing
+ const keysFileContent = this.readKeysFile();
+ if (!keysFileContent.USER_NAME && credentials.USER_NAME) {
+ try {
+ this.writeKeysFile({
+ ...keysFileContent,
+ USER_NAME: credentials.USER_NAME,
+ });
+ console.log(
+ '[CredentialManager] Migrated USER_NAME from keyring to keys.json'
+ );
+ } catch (error) {
+ console.error(
+ `[CredentialManager] Failed to migrate USER_NAME to keys.json: ${error}`
+ );
+ }
+ }
+ }
+ }
+ } catch (error) {
+ console.error('[CredentialManager] Keyring migration attempt failed:', error);
+ }
+ }
+
+ if (!encryptionKey) {
+ console.log(
+ '[CredentialManager] No ENCRYPTION_KEY found in env file or keyring. Awaiting setup wizard.'
+ );
+ return { loaded: false };
+ }
+
+ // --- Step 3: Load auth credentials from keys.json ---
+ const keysFileContent = this.readKeysFile();
+ const existingPasswordHash = keysFileContent.PASSWORD_HASH;
+ const existingUserName = keysFileContent.USER_NAME;
+
+ if (existingPasswordHash && existingUserName) {
+ console.log(
+ '✅ [CredentialManager] Credentials loaded (ENCRYPTION_KEY from env file, auth from keys.json).'
+ );
+ return {
+ loaded: true,
+ config: {
+ ENCRYPTION_KEY: encryptionKey,
+ USER_NAME: existingUserName,
+ USER_PASSWORD: '', // Not needed at runtime
+ PASSWORD_HASH: existingPasswordHash,
+ SETUP_PENDING: false,
+ },
+ };
+ }
+
+ // If keys.json has no PASSWORD_HASH, this is a fresh install (or data was wiped).
+ console.log('[CredentialManager] keys.json has no PASSWORD_HASH. Awaiting setup wizard.');
+ return { loaded: false };
+ }
+}
+
+export const credentialManager = new CredentialManager();
+export { CredentialManager };
diff --git a/backend/src/services/KeyringService.ts b/backend/src/services/KeyringService.ts
index 391fc0f..51363fb 100644
--- a/backend/src/services/KeyringService.ts
+++ b/backend/src/services/KeyringService.ts
@@ -209,6 +209,22 @@ class KeyringService {
}
}
+ /**
+ * Read an arbitrary key from the keyring under the Pluton service.
+ * Used for one-time migration of keys not in the standard credential set (e.g. LICENSE_KEY).
+ */
+ public async getCredentialByName(key: string): Promise<string | null> {
+ if (!(await this.waitForInitialization())) {
+ return null;
+ }
+ try {
+ const entry = new this.Entry(SERVICE_NAME, key);
+ return entry.getPassword() || null;
+ } catch {
+ return null;
+ }
+ }
+
/**
* Deletes a credential from the OS keyring
*/
diff --git a/backend/src/services/PlanService.ts b/backend/src/services/PlanService.ts
index 10af83a..8576273 100644
--- a/backend/src/services/PlanService.ts
+++ b/backend/src/services/PlanService.ts
@@ -117,7 +117,12 @@ export class PlanService {
if (storagePath) {
try {
const isRemote = sourceId !== 'main';
- const targetOS = isRemote ? (device.os ?? undefined) : undefined;
+ const targetOS = isRemote
+ ? device.platform
+ ? device.platform.toLowerCase()
+ : undefined
+ : undefined;
+ console.log('platform: ', sourceId, targetOS);
theStoragePath = sanitizeStoragePath(storagePath, planStorage.type, targetOS);
} catch (error) {
if (error instanceof AppError) {
diff --git a/backend/src/utils/AppPaths.ts b/backend/src/utils/AppPaths.ts
index ecbb4bc..0ca1a43 100644
--- a/backend/src/utils/AppPaths.ts
+++ b/backend/src/utils/AppPaths.ts
@@ -234,6 +234,11 @@ class AppPaths {
this.checkInitialized();
return this.paths.rescue;
}
+
+ public getEncEnvFilePath(): string {
+ this.checkInitialized();
+ return path.join(this.paths.base, 'pluton.enc.env');
+ }
}
// Export the singleton instance. The first time this is imported and used,
diff --git a/backend/src/utils/cliPasswordReset.ts b/backend/src/utils/cliPasswordReset.ts
index 1b039ac..ba314bb 100644
--- a/backend/src/utils/cliPasswordReset.ts
+++ b/backend/src/utils/cliPasswordReset.ts
@@ -3,6 +3,7 @@ import fs from 'fs';
import path from 'path';
import bcrypt from 'bcryptjs';
import { appPaths } from './AppPaths';
+import { applyStrictPermissions } from './envFileHelpers';
const BCRYPT_SALT_ROUNDS = 10;
@@ -44,7 +45,7 @@ function prompt(question: string, hidden = false): Promise<string> {
}
/**
- * Stores the new password hash in keys.json and updates the keyring credentials.
+ * Stores the new password hash in keys.json.
*/
async function storeNewPassword(userName: string, password: string): Promise<void> {
// Hash the password
@@ -66,20 +67,7 @@ async function storeNewPassword(userName: string, password: string): Promise<voi
const dir = path.dirname(keysPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(keysPath, JSON.stringify(keysFileContent, null, 2), { mode: 0o600 });
-
- // Update keyring credentials (if available)
- try {
- const { keyringService } = await import('../services/KeyringService');
- const isAvailable = await keyringService.waitForInitialization();
- if (isAvailable) {
- const { KEYRING_KEYS } = await import('../services/KeyringService');
- await keyringService.setCredential(KEYRING_KEYS.USER_NAME, userName);
- await keyringService.setCredential(KEYRING_KEYS.USER_PASSWORD, password);
- console.log('✅ Credentials updated in system keyring.');
- }
- } catch {
- // Keyring not available - that's fine, hash is stored in keys.json
- }
+ applyStrictPermissions(keysPath);
console.log('✅ Password hash updated in keys.json.');
}
@@ -118,7 +106,7 @@ export async function handlePasswordReset(): Promise<void> {
await storeNewPassword(userName, password1);
console.log(
- '\n✅ Password reset successful. You can now start Pluton and log in with your new credentials.\n'
+ '\n✅ Password reset successful. Restart the Pluton service and log in with your new credentials.\n'
);
process.exit(0);
}
diff --git a/backend/src/utils/envFileHelpers.ts b/backend/src/utils/envFileHelpers.ts
new file mode 100644
index 0000000..9057144
--- /dev/null
+++ b/backend/src/utils/envFileHelpers.ts
@@ -0,0 +1,138 @@
+import fs from 'fs';
+import path from 'path';
+import os from 'os';
+import { execSync } from 'child_process';
+
+const ENV_FILE_NAME = 'pluton.enc.env';
+
+/**
+ * Get the full path to the pluton.enc.env file in the given data directory.
+ */
+export function getEncEnvFilePath(dataDir: string): string {
+ return path.join(dataDir, ENV_FILE_NAME);
+}
+
+/**
+ * Check whether the pluton.enc.env file exists in the given data directory.
+ */
+export function encEnvFileExists(dataDir: string): boolean {
+ return fs.existsSync(getEncEnvFilePath(dataDir));
+}
+
+/**
+ * Read the ENCRYPTION_KEY from pluton.enc.env.
+ * Returns null if the file doesn't exist, is empty, or can't be parsed.
+ */
+export function readEncryptionKeyFromEnvFile(dataDir: string): string | null {
+ const filePath = getEncEnvFilePath(dataDir);
+ try {
+ if (!fs.existsSync(filePath)) {
+ return null;
+ }
+ const content = fs.readFileSync(filePath, 'utf-8');
+ for (const line of content.split('\n')) {
+ const trimmed = line.trim();
+ if (trimmed.startsWith('#') || !trimmed) continue;
+ const eqIndex = trimmed.indexOf('=');
+ if (eqIndex === -1) continue;
+ const key = trimmed.slice(0, eqIndex).trim();
+ const value = trimmed.slice(eqIndex + 1).trim();
+ if ((key === 'ENCRYPTION_KEY' || key === 'PLUTON_ENCRYPTION_KEY') && value.length > 0) {
+ return value;
+ }
+ }
+ return null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Write the ENCRYPTION_KEY to pluton.enc.env with strict file permissions.
+ * Creates the file if it doesn't exist; overwrites if it does.
+ */
+export function writeEncryptionKeyToEnvFile(dataDir: string, encryptionKey: string): void {
+ const filePath = getEncEnvFilePath(dataDir);
+ const dir = path.dirname(filePath);
+ if (!fs.existsSync(dir)) {
+ fs.mkdirSync(dir, { recursive: true });
+ }
+
+ const content = [
+ '# Pluton Encryption Key — DO NOT SHARE',
+ `# Written on ${new Date().toISOString()}`,
+ `ENCRYPTION_KEY=${encryptionKey}`,
+ '',
+ ].join('\n');
+
+ fs.writeFileSync(filePath, content, { mode: 0o600 });
+ applyStrictPermissions(filePath);
+ console.log(`[envFileHelpers] Encryption key written to ${filePath}`);
+}
+
+/**
+ * Apply strict OS-level permissions to a sensitive file.
+ * - Unix (macOS/Linux): chmod 600 (owner read/write only)
+ * - Windows: icacls to remove inheritance, grant SYSTEM + Administrators only
+ */
+export function applyStrictPermissions(filePath: string): void {
+ if (os.platform() === 'win32') {
+ applyWindowsAcl(filePath);
+ } else {
+ try {
+ fs.chmodSync(filePath, 0o600);
+ } catch (error) {
+ console.warn(`[envFileHelpers] Could not set permissions on ${filePath}: ${error}`);
+ }
+ }
+}
+
+/**
+ * Apply restrictive NTFS ACL to a file on Windows.
+ * Removes inherited permissions, grants full control to SYSTEM, Administrators,
+ * and the current user (so the process that created the file can still access it).
+ */
+function applyWindowsAcl(filePath: string): void {
+ try {
+ // Remove inherited permissions
+ execSync(`icacls "${filePath}" /inheritance:r`, { stdio: 'ignore' });
+ // Grant SYSTEM full control
+ execSync(`icacls "${filePath}" /grant:r "NT AUTHORITY\\SYSTEM:(F)"`, { stdio: 'ignore' });
+ // Grant Administrators full control
+ execSync(`icacls "${filePath}" /grant:r "BUILTIN\\Administrators:(F)"`, { stdio: 'ignore' });
+ // Grant the current user full control (needed for dev and non-admin service accounts)
+ const currentUser = os.userInfo().username;
+ execSync(`icacls "${filePath}" /grant:r "${currentUser}:(F)"`, { stdio: 'ignore' });
+ } catch (error) {
+ console.warn(`[envFileHelpers] Could not apply Windows ACL to ${filePath}: ${error}`);
+ }
+}
+
+/**
+ * Verify that a sensitive file has correct permissions.
+ * Logs a warning if permissions are too open. Does not fix them automatically.
+ */
+export function verifyFilePermissions(filePath: string): boolean {
+ if (!fs.existsSync(filePath)) return true; // Nothing to check
+
+ if (os.platform() === 'win32') {
+ // On Windows, we trust the ACL applied at creation time.
+ // A full ACL audit would require parsing icacls output, which is fragile.
+ return true;
+ }
+
+ try {
+ const stats = fs.statSync(filePath);
+ const mode = stats.mode & 0o777;
+ if (mode !== 0o600) {
+ console.warn(
+ `⚠️ [envFileHelpers] ${filePath} has permissions ${mode.toString(8)} (expected 600). ` +
+ 'This file contains sensitive data and should only be readable by the owner.'
+ );
+ return false;
+ }
+ return true;
+ } catch {
+ return true; // Can't check, don't warn
+ }
+}
diff --git a/backend/src/utils/installHelpers.ts b/backend/src/utils/installHelpers.ts
index ec143c3..dd801ed 100644
--- a/backend/src/utils/installHelpers.ts
+++ b/backend/src/utils/installHelpers.ts
@@ -71,8 +71,16 @@ export function isLinuxDesktop(): boolean {
/**
* Check if running on a platform that supports keyring (Windows/macOS/Linux Desktop)
+ * @deprecated Use isDesktopPlatform() instead
*/
export function isKeyringPlatform(): boolean {
+ return isDesktopPlatform();
+}
+
+/**
+ * Check if running on a desktop platform (Windows/macOS/Linux Desktop)
+ */
+export function isDesktopPlatform(): boolean {
const platform = process.platform;
return (
platform === 'win32' || platform === 'darwin' || (platform === 'linux' && isLinuxDesktop())
@@ -81,8 +89,16 @@ export function isKeyringPlatform(): boolean {
/**
* Check if the app requires keyring-based initial setup
- * This is true when: running as binary + on a keyring-supported platform
+ * @deprecated Use requiresDesktopSetup() instead
*/
export function requiresKeyringSetup(): boolean {
- return isBinaryMode() && isKeyringPlatform();
+ return requiresDesktopSetup();
+}
+
+/**
+ * Check if the app requires desktop-based initial setup (via web UI).
+ * This is true when: running as binary + on a desktop platform.
+ */
+export function requiresDesktopSetup(): boolean {
+ return isBinaryMode() && isDesktopPlatform();
}
diff --git a/frontend/src/services/settings.ts b/frontend/src/services/settings.ts
index 1e17136..a483876 100644
--- a/frontend/src/services/settings.ts
+++ b/frontend/src/services/settings.ts
@@ -171,7 +171,10 @@ export function useValidateIntegration() {
export interface SetupStatus {
setupPending: boolean;
isBinary: boolean;
+ requiresSetup: boolean;
+ /** @deprecated Use requiresSetup instead */
requiresKeyringSetup: boolean;
+ hasEncEnvFile: boolean;
platform: string;
}
diff --git a/installers/linux-server/install.sh b/installers/linux-server/install.sh
index 41c649b..7fa6479 100644
--- a/installers/linux-server/install.sh
+++ b/installers/linux-server/install.sh
@@ -171,8 +171,8 @@ detect_architecture() {
echo "arm64"
;;
*)
- echo -e "${RED}Error: Unsupported architecture: $arch${NC}"
- echo "${PRODUCT_NAME} supports x86_64 (amd64) and aarch64 (arm64) architectures."
+ echo -e "${RED}Error: Unsupported architecture: $arch${NC}" >&2
+ echo "${PRODUCT_NAME} supports x86_64 (amd64) and aarch64 (arm64) architectures." >&2
exit 1
;;
esac
@@ -219,15 +219,31 @@ load_config_file() {
# Load existing credentials (for upgrade)
load_existing_credentials() {
+ # Read pluton.env line-by-line without shell expansion (safe for metacharacters)
if [ -f "${ENV_FILE}" ]; then
echo -e "${GREEN}Loading existing credentials from: ${ENV_FILE}${NC}"
- set -a
- source "${ENV_FILE}"
- set +a
-
- [ -n "${PLUTON_ENCRYPTION_KEY:-}" ] && CLI_ENCRYPTION_KEY="$PLUTON_ENCRYPTION_KEY"
- [ -n "${PLUTON_USER_NAME:-}" ] && CLI_USER_NAME="$PLUTON_USER_NAME"
- [ -n "${PLUTON_USER_PASSWORD:-}" ] && CLI_USER_PASSWORD="$PLUTON_USER_PASSWORD"
+ while IFS='=' read -r key value; do
+ # Skip comments and blank lines
+ case "$key" in '#'*|'') continue;; esac
+ # Trim leading/trailing whitespace from key
+ key=$(echo "$key" | xargs)
+ case "$key" in
+ PLUTON_ENCRYPTION_KEY) CLI_ENCRYPTION_KEY="$value" ;;
+ PLUTON_USER_NAME) CLI_USER_NAME="$value" ;;
+ PLUTON_USER_PASSWORD) CLI_USER_PASSWORD="$value" ;;
+ esac
+ done < "${ENV_FILE}"
+ fi
+
+ # Read encryption key from /etc/pluton/pluton.enc.env (current location)
+ local enc_env_file="${CONFIG_DIR}/pluton.enc.env"
+ if [ -f "${enc_env_file}" ]; then
+ echo -e "${GREEN}Loading encryption key from: ${enc_env_file}${NC}"
+ while IFS='=' read -r key value; do
+ case "$key" in '#'*|'') continue;; esac
+ key=$(echo "$key" | xargs)
+ [ "$key" = "PLUTON_ENCRYPTION_KEY" ] && CLI_ENCRYPTION_KEY="$value"
+ done < "${enc_env_file}"
fi
if [ -f "${DATA_DIR}/config/config.json" ]; then
@@ -479,16 +495,37 @@ install_files() {
# Write configuration files
write_configuration() {
echo " Writing credentials to ${ENV_FILE}..."
- cat > "${ENV_FILE}" << EOF
-# ${PRODUCT_NAME} Server Credentials
-# Generated by installer on $(date)
-# WARNING: This file contains sensitive credentials. Keep it secure.
-
-PLUTON_ENCRYPTION_KEY=${CLI_ENCRYPTION_KEY}
-PLUTON_USER_NAME=${CLI_USER_NAME}
-PLUTON_USER_PASSWORD=${CLI_USER_PASSWORD}
-EOF
+ # Use quoted heredoc delimiter to prevent shell expansion of values,
+ # then write variable values via printf to avoid injection.
+ {
+ printf '# %s Server Credentials\n' "${PRODUCT_NAME}"
+ printf '# Generated by installer on %s\n' "$(date)"
+ printf '# WARNING: This file contains sensitive credentials. Keep it secure.\n\n'
+ printf 'PLUTON_USER_NAME=%s\n' "${CLI_USER_NAME}"
+ printf 'PLUTON_USER_PASSWORD=%s\n' "${CLI_USER_PASSWORD}"
+ } > "${ENV_FILE}"
chmod 600 "${ENV_FILE}"
+
+ # Write encryption key to config directory (created once, never overwritten)
+ local enc_env_file="${CONFIG_DIR}/pluton.enc.env"
+ if [ ! -f "${enc_env_file}" ]; then
+ echo " Writing encryption key to ${enc_env_file}..."
+ {
+ printf '# %s Encryption Key — DO NOT SHARE\n' "${PRODUCT_NAME}"
+ printf '# This file is created once and never overwritten by the installer.\n'
+ printf '# Generated by installer on %s\n' "$(date)"
+ printf 'PLUTON_ENCRYPTION_KEY=%s\n' "${CLI_ENCRYPTION_KEY}"
+ } > "${enc_env_file}"
+ chmod 600 "${enc_env_file}"
+ else
+ echo " Encryption key file already exists at ${enc_env_file} (preserved)"
+ fi
+
+ # Clean up legacy encryption key file from data directory
+ if [ -f "${DATA_DIR}/pluton.enc.env" ]; then
+ rm -f "${DATA_DIR}/pluton.enc.env"
+ echo " Removed legacy encryption key file from ${DATA_DIR}/pluton.enc.env"
+ fi
local config_json="${DATA_DIR}/config/config.json"
if [ ! -f "$config_json" ] || [ "$CLI_UPGRADE" = false ]; then
@@ -523,8 +560,9 @@ RestartSec=5
StandardOutput=append:${DATA_DIR}/logs/stdout.log
StandardError=append:${DATA_DIR}/logs/stderr.log
-# Load sensitive credentials from environment file
+# Load sensitive credentials from environment files
EnvironmentFile=${ENV_FILE}
+EnvironmentFile=${CONFIG_DIR}/pluton.enc.env
# Non-sensitive environment variables
Environment="PLUTON_DATA_DIR=${DATA_DIR}"
diff --git a/installers/linux-server/pluton.env.template b/installers/linux-server/pluton.env.template
index 0327c64..1f80414 100644
--- a/installers/linux-server/pluton.env.template
+++ b/installers/linux-server/pluton.env.template
@@ -1,17 +1,16 @@
# Pluton Server Environment Configuration
-# This file contains sensitive credentials for the Pluton service.
+# This file contains user credentials for the Pluton service.
# It should be stored at /etc/pluton/pluton.env with permissions 600.
#
+# NOTE: The encryption key is stored separately in /var/lib/pluton/pluton.enc.env
+#
# Usage:
# Interactive install: sudo ./pluton-server-installer.sh
# Non-interactive: sudo ./pluton-server-installer.sh --config /path/to/pluton.env
#
# All PLUTON_* prefixed variables are automatically mapped by the application.
-# ===== REQUIRED: Security & Authentication =====
-# Encryption key for restic/rclone snapshot encryption (min 12 characters)
-PLUTON_ENCRYPTION_KEY=your-encryption-key-here-min-12-chars
-
+# ===== REQUIRED: Authentication =====
# Admin username for web interface login
PLUTON_USER_NAME=admin
diff --git a/installers/linux-server/pluton.service.template b/installers/linux-server/pluton.service.template
index 73e2ee2..3bd5486 100644
--- a/installers/linux-server/pluton.service.template
+++ b/installers/linux-server/pluton.service.template
@@ -12,8 +12,9 @@ RestartSec=5
StandardOutput=append:/var/lib/pluton/logs/stdout.log
StandardError=append:/var/lib/pluton/logs/stderr.log
-# Load sensitive credentials from environment file
+# Load sensitive credentials from environment files
EnvironmentFile=/etc/pluton/pluton.env
+EnvironmentFile=/etc/pluton/pluton.enc.env
# Non-sensitive environment variables
Environment="PLUTON_DATA_DIR=/var/lib/pluton"
diff --git a/installers/linux/AppDir/pluton.desktop b/installers/linux/AppDir/pluton.desktop
index 041e37a..d0bb38e 100644
--- a/installers/linux/AppDir/pluton.desktop
+++ b/installers/linux/AppDir/pluton.desktop
@@ -7,4 +7,4 @@ Type=Application
Categories=Utility;
Terminal=false
StartupNotify=true
-X-AppImage-Version=0.0.1
+X-AppImage-Version=0.13.0
diff --git a/installers/macos/install.sh b/installers/macos/install.sh
index 3a68c64..429448a 100644
--- a/installers/macos/install.sh
+++ b/installers/macos/install.sh
@@ -20,6 +20,7 @@ NC='\033[0m' # No Color
# Installation paths
INSTALL_DIR="/opt/pluton"
DATA_DIR="/var/lib/pluton"
+CONFIG_DIR="/etc/pluton"
PLIST_FILE="/Library/LaunchDaemons/com.plutonhq.pluton.plist"
PLIST_LABEL="com.plutonhq.pluton"
@@ -122,7 +123,9 @@ mkdir -p "${INSTALL_DIR}/binaries"
mkdir -p "${INSTALL_DIR}/node_modules"
mkdir -p "${INSTALL_DIR}/drizzle"
-# Create data directory with subdirectories
+# Create config and data directories
+echo " Creating config directory: ${CONFIG_DIR}"
+mkdir -p "${CONFIG_DIR}"
echo " Creating data directory: ${DATA_DIR}"
mkdir -p "${DATA_DIR}/config"
mkdir -p "${DATA_DIR}/db"
@@ -166,32 +169,20 @@ if [ -f "${SCRIPT_DIR}/uninstall.sh" ]; then
chmod +x "${INSTALL_DIR}/uninstall.sh"
fi
-# Copy service wrapper script (sets up keychain for LaunchDaemon)
+# Copy service wrapper script
echo " Installing service wrapper..."
if [ -f "${SCRIPT_DIR}/pluton-service.sh" ]; then
cp "${SCRIPT_DIR}/pluton-service.sh" "${INSTALL_DIR}/pluton-service.sh"
chmod +x "${INSTALL_DIR}/pluton-service.sh"
fi
-# Set up macOS keychain for LaunchDaemon (root) context
-# LaunchDaemons run as root without a default keychain, which causes
-# @napi-rs/keyring to fail. We create a dedicated Pluton keychain.
-echo " Setting up system keychain for service..."
-export HOME=/var/root
-KEYCHAIN_DIR="/var/root/Library/Keychains"
-KEYCHAIN_PATH="${KEYCHAIN_DIR}/pluton.keychain-db"
-KEYCHAIN_PASSWORD="pluton-service-keychain"
-mkdir -p "${KEYCHAIN_DIR}"
-if [ ! -f "${KEYCHAIN_PATH}" ]; then
- security create-keychain -p "${KEYCHAIN_PASSWORD}" "${KEYCHAIN_PATH}"
- echo " Created Pluton keychain at ${KEYCHAIN_PATH}"
-else
- echo " Pluton keychain already exists"
-fi
-security unlock-keychain -p "${KEYCHAIN_PASSWORD}" "${KEYCHAIN_PATH}"
-security set-keychain-settings "${KEYCHAIN_PATH}"
-security list-keychains -d system -s "${KEYCHAIN_PATH}"
-security default-keychain -s "${KEYCHAIN_PATH}"
+# Ensure config directory has restrictive permissions for sensitive env files
+echo " Setting config directory permissions..."
+chmod 700 "${CONFIG_DIR}"
+
+# Ensure data directory has restrictive permissions for sensitive files
+echo " Setting data directory permissions..."
+chmod 700 "${DATA_DIR}"
# Write configuration file (only on fresh install — preserve on upgrade)
if [ "$IS_UPGRADE" = false ] || [ ! -f "${DATA_DIR}/config/config.json" ]; then
diff --git a/installers/macos/pluton-service.sh b/installers/macos/pluton-service.sh
index 9b3b293..563e8f3 100644
--- a/installers/macos/pluton-service.sh
+++ b/installers/macos/pluton-service.sh
@@ -1,39 +1,40 @@
#!/bin/bash
# Pluton macOS Service Wrapper
-# Ensures the system keychain is available before starting the Pluton daemon.
+# Loads credentials from env files before starting the Pluton daemon.
#
-# When running as a LaunchDaemon (system-level), macOS does not provide a default
-# keychain for the root user. This wrapper creates and unlocks a dedicated keychain
-# so that @napi-rs/keyring can store and retrieve credentials.
+# macOS plists do not support EnvironmentFile like systemd. This wrapper reads
+# /etc/pluton/pluton.env and /etc/pluton/pluton.enc.env so that installer-provided
+# admin credentials and the encryption key are available to the daemon.
set -e
# Ensure HOME points to root's actual home directory.
-# When invoked via sudo, HOME may still reference the calling user's home,
-# causing `security default-keychain` to fail with a permissions error.
export HOME=/var/root
-KEYCHAIN_DIR="/var/root/Library/Keychains"
-KEYCHAIN_PATH="${KEYCHAIN_DIR}/pluton.keychain-db"
-KEYCHAIN_PASSWORD="pluton-service-keychain"
+# ── Load environment from credentials files ──────────────────────────────────
-# Create keychain directory if needed
-mkdir -p "${KEYCHAIN_DIR}"
+ENV_FILE="/etc/pluton/pluton.env"
+ENC_ENV_FILE="/etc/pluton/pluton.enc.env"
-# Create the Pluton keychain if it doesn't exist
-if [ ! -f "${KEYCHAIN_PATH}" ]; then
- security create-keychain -p "${KEYCHAIN_PASSWORD}" "${KEYCHAIN_PATH}"
+if [ -f "${ENV_FILE}" ]; then
+ while IFS='=' read -r key value; do
+ case "$key" in '#'*|'') continue;; esac
+ key=$(echo "$key" | xargs)
+ case "$key" in
+ PLUTON_USER_NAME) export PLUTON_USER_NAME="$value" ;;
+ PLUTON_USER_PASSWORD) export PLUTON_USER_PASSWORD="$value" ;;
+ esac
+ done < "${ENV_FILE}"
fi
-# Unlock the keychain (required after every reboot)
-security unlock-keychain -p "${KEYCHAIN_PASSWORD}" "${KEYCHAIN_PATH}"
-
-# Disable auto-lock (timeout=0 means no auto-lock)
-security set-keychain-settings "${KEYCHAIN_PATH}"
+if [ -f "${ENC_ENV_FILE}" ]; then
+ while IFS='=' read -r key value; do
+ case "$key" in '#'*|'') continue;; esac
+ key=$(echo "$key" | xargs)
+ [ "$key" = "PLUTON_ENCRYPTION_KEY" ] && export PLUTON_ENCRYPTION_KEY="$value"
+ done < "${ENC_ENV_FILE}"
+fi
-# Set as the default keychain and add to the search list
-security list-keychains -d system -s "${KEYCHAIN_PATH}"
-security default-keychain -s "${KEYCHAIN_PATH}"
+# ── Execute the Pluton binary (replaces this process) ────────────────────────
-# Execute the Pluton binary (replaces this process)
exec /opt/pluton/pluton
diff --git a/installers/windows/pluton-setup.iss b/installers/windows/pluton-setup.iss
index 224e20a..4426e78 100644
--- a/installers/windows/pluton-setup.iss
+++ b/installers/windows/pluton-setup.iss
@@ -41,13 +41,14 @@ Name: "english"; MessagesFile: "compiler:Default.isl"
[Dirs]
; Create the data directory structure in ProgramData
-Name: "{commonappdata}\{#MyAppName}"; Permissions: users-modify
-Name: "{commonappdata}\{#MyAppName}\config"; Permissions: users-modify
-Name: "{commonappdata}\{#MyAppName}\db"; Permissions: users-modify
-Name: "{commonappdata}\{#MyAppName}\logs"; Permissions: users-modify
-Name: "{commonappdata}\{#MyAppName}\backups"; Permissions: users-modify
-Name: "{commonappdata}\{#MyAppName}\restores"; Permissions: users-modify
-Name: "{commonappdata}\{#MyAppName}\temp"; Permissions: users-modify
+; Restrict access to SYSTEM and Administrators only for sensitive data
+Name: "{commonappdata}\{#MyAppName}"; Permissions: admins-full
+Name: "{commonappdata}\{#MyAppName}\config"; Permissions: admins-full
+Name: "{commonappdata}\{#MyAppName}\db"; Permissions: admins-full
+Name: "{commonappdata}\{#MyAppName}\logs"; Permissions: admins-full
+Name: "{commonappdata}\{#MyAppName}\backups"; Permissions: admins-full
+Name: "{commonappdata}\{#MyAppName}\restores"; Permissions: admins-full
+Name: "{commonappdata}\{#MyAppName}\temp"; Permissions: admins-full
[Files]
; Main executable
@@ -69,7 +70,7 @@ Source: "..\..\dist\executables\pluton-win-x64\drizzle\*"; DestDir: "{app}\drizz
; NSSM for service management (Assumes you have downloaded nssm.exe to installers/windows/tools/)
Source: "tools\nssm.exe"; DestDir: "{app}"; Flags: ignoreversion
-; Visual C++ Redistributable (required for native Node.js modules like @napi-rs/keyring)
+; Visual C++ Redistributable (required for native Node.js modules like better-sqlite3)
; Download from: https://aka.ms/vs/17/release/vc_redist.x64.exe
Source: "tools\vc_redist.x64.exe"; DestDir: "{tmp}"; Flags: ignoreversion deleteafterinstall; Check: not IsVCRedistInstalled
@@ -87,8 +88,6 @@ Name: "{group}\Uninstall Pluton"; Filename: "{uninstallexe}"
; Set the data directory environment variable
Root: HKLM; Subkey: "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"; ValueType: string; ValueName: "PLUTON_DATA_DIR"; ValueData: "{commonappdata}\{#MyAppName}"; Flags: uninsdeletevalue
-; NOTE: PLUTON_ENCRYPTION_KEY, PLUTON_USER_NAME, PLUTON_USER_PASSWORD are no longer set here.
-; They will be configured via the web interface and stored securely in Windows Credential Manager.
[Run]
; Install Visual C++ Redistributable if not already installed (required for native Node.js modules)
@@ -104,13 +103,13 @@ Filename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} Start SERVICE_A
Filename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} AppDirectory ""{app}"""; Flags: runhidden
; Set environment variables for data directory on the service
Filename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} AppEnvironmentExtra PLUTON_DATA_DIR=""{commonappdata}\{#MyAppName}"""; Flags: runhidden
-; NOTE: Credentials (ENCRYPTION_KEY, USER_NAME, USER_PASSWORD) are now stored in Windows Credential Manager
-; and will be configured via the web interface on first launch.
; Set stdout and stderr logging
Filename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} AppStdout ""{commonappdata}\{#MyAppName}\logs\service-out.log"""; Flags: runhidden
Filename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} AppStderr ""{commonappdata}\{#MyAppName}\logs\service-err.log"""; Flags: runhidden
-; Start the service
-Filename: "{app}\nssm.exe"; Parameters: "start {#MyAppServiceName}"; Flags: runhidden; StatusMsg: "Starting service..."
+; Harden data directory ACL: remove inherited permissions, grant SYSTEM and Administrators only
+Filename: "icacls.exe"; Parameters: """{commonappdata}\{#MyAppName}"" /inheritance:r /grant:r *S-1-5-18:(OI)(CI)F /grant:r *S-1-5-32-544:(OI)(CI)F"; Flags: runhidden; StatusMsg: "Setting data directory permissions..."
+; Start the service (BeforeInstall writes config.json + URL shortcut before the service launches)
+Filename: "{app}\nssm.exe"; Parameters: "start {#MyAppServiceName}"; BeforeInstall: WriteConfigAndUrlFiles; Flags: runhidden; StatusMsg: "Starting service..."
[UninstallRun]
; Stop the service
@@ -303,8 +302,8 @@ begin
FinishNoteLabel.Visible := False;
// --- General Settings Page ---
- // NOTE: Security credentials (Encryption Key, Username, Password) are now configured
- // via the web interface after installation and stored in Windows Credential Manager.
+ // NOTE: Security credentials (Encryption Key, Username, Password) are configured
+ // via the web interface after installation and stored in pluton.enc.env and keys.json.
SettingsPage := CreateInputQueryPage(wpLicense,
'General Settings', 'Configure the application defaults.',
'You can change these settings later in the config file.' + #13#10 + #13#10 +
@@ -337,7 +336,9 @@ begin
end;
end;
-procedure CurStepChanged(CurStep: TSetupStep);
+// Called via BeforeInstall on the 'nssm start' [Run] entry so that
+// config.json exists BEFORE the service launches for the first time.
+procedure WriteConfigAndUrlFiles;
var
ConfigPath: String;
ConfigContent: String;
@@ -345,38 +346,35 @@ var
UrlFilePath: String;
UrlFileContent: String;
begin
- if CurStep = ssPostInstall then
+ DashboardUrl := GetDashboardUrl();
+
+ // Create URL shortcut file with dynamic port
+ UrlFilePath := ExpandConstant('{app}\pluton-open.url');
+ UrlFileContent := '[InternetShortcut]' + #13#10 +
+ 'URL=' + DashboardUrl + #13#10 +
+ 'IconIndex=0' + #13#10 +
+ 'IconFile=' + ExpandConstant('{app}\pluton.ico');
+ SaveStringToFile(UrlFilePath, UrlFileContent, False);
+
+ // Only write config.json if it doesn't exist (preserve user settings on upgrade)
+ ConfigPath := ExpandConstant('{commonappdata}\{#MyAppName}\config\config.json');
+
+ if not FileExists(ConfigPath) then
begin
- DashboardUrl := GetDashboardUrl();
+ // Construct JSON content manually
+ ConfigContent := '{' + #13#10 +
+ ' "SERVER_PORT": ' + ServerPort + ',' + #13#10 +
+ ' "MAX_CONCURRENT_BACKUPS": ' + MaxConcurrentBackups + #13#10 +
+ '}';
- // Create URL shortcut file with dynamic port
- UrlFilePath := ExpandConstant('{app}\pluton-open.url');
- UrlFileContent := '[InternetShortcut]' + #13#10 +
- 'URL=' + DashboardUrl + #13#10 +
- 'IconIndex=0' + #13#10 +
- 'IconFile=' + ExpandConstant('{app}\pluton.ico');
- SaveStringToFile(UrlFilePath, UrlFileContent, False);
-
- // Only write config.json if it doesn't exist (preserve user settings on upgrade)
- ConfigPath := ExpandConstant('{commonappdata}\{#MyAppName}\config\config.json');
-
- if not FileExists(ConfigPath) then
+ if not SaveStringToFile(ConfigPath, ConfigContent, False) then
begin
- // Construct JSON content manually
- ConfigContent := '{' + #13#10 +
- ' "SERVER_PORT": ' + ServerPort + ',' + #13#10 +
- ' "MAX_CONCURRENT_BACKUPS": ' + MaxConcurrentBackups + #13#10 +
- '}';
-
- if not SaveStringToFile(ConfigPath, ConfigContent, False) then
- begin
- MsgBox('Failed to write configuration file.', mbError, MB_OK);
- end;
- end
- else
- begin
- Log('Config file already exists - preserving user settings');
+ MsgBox('Failed to write configuration file.', mbError, MB_OK);
end;
+ end
+ else
+ begin
+ Log('Config file already exists - preserving user settings');
end;
end;