A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.
feat: add OS specific built-in key manager for sensitive values on binary installations.
towfiqiba05abbab759
diff --git a/backend/package.json b/backend/package.jsonindex df58c10..6e06235 100644--- a/backend/package.json+++ b/backend/package.json@@ -14,6 +14,7 @@"LICENSE"],"dependencies": {+ "@napi-rs/keyring": "^1.2.0","aedes": "^0.51.3","better-sqlite3": "12.2.0","cookies": "^0.9.1",diff --git a/backend/pkg-entry.cjs b/backend/pkg-entry.cjsindex 25f2545..9815834 100644--- a/backend/pkg-entry.cjs+++ b/backend/pkg-entry.cjs@@ -4,18 +4,18 @@ const path = require('path');const { pathToFileURL } = require('url');(async () => {- try {- // Resolve the path to the ESM entry point- // In pkg snapshot, __dirname points to the virtual directory containing this file- // We need to use a relative path that works within the snapshot filesystem- // The error suggests it wants a file URL, but pkg's virtual FS is tricky with ESM-- // Try importing using a relative path first (standard for pkg)- // This often works better than absolute paths in the virtual FS- await import('./dist/index.js');- } catch (err) {- console.error('Failed to start application:', err);- console.error(err.stack);- process.exit(1);- }+ try {+ // Resolve the path to the ESM entry point+ // In pkg snapshot, __dirname points to the virtual directory containing this file+ // We need to use a relative path that works within the snapshot filesystem+ // The error suggests it wants a file URL, but pkg's virtual FS is tricky with ESM++ // Try importing using a relative path first (standard for pkg)+ // This often works better than absolute paths in the virtual FS+ await import('./dist/index.js');+ } catch (err) {+ console.error('Failed to start application:', err);+ console.error(err.stack);+ process.exit(1);+ }})();diff --git a/backend/src/controllers/SetupController.ts b/backend/src/controllers/SetupController.tsnew file mode 100644index 0000000..ece5445--- /dev/null+++ b/backend/src/controllers/SetupController.ts@@ -0,0 +1,154 @@+import { Request, Response } from 'express';+import { keyringService, KeyringCredentials } from '../services/KeyringService';+import { configService } from '../services/ConfigService';+import { requiresKeyringSetup, isBinaryMode } from '../utils/installHelpers';+import { initSetup } from '../utils/initSetup';+import { db } from '../db';+import { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';++export class SetupController {+ /**+ * Get the current setup status+ */+ async getStatus(req: Request, res: Response) {+ try {+ const isSetupPending = configService.isSetupPending();+ const isBinary = isBinaryMode();+ const requiresKeyring = requiresKeyringSetup();++ res.json({+ success: true,+ data: {+ setupPending: isSetupPending,+ isBinary,+ requiresKeyringSetup: requiresKeyring,+ platform: process.platform,+ },+ });+ } catch (error: any) {+ res.status(500).json({+ success: false,+ error: error.message || 'Failed to get setup status',+ });+ }+ }++ /**+ * Complete the initial setup with credentials+ * This endpoint stores credentials in the OS keyring and initializes the app+ */+ async completeSetup(req: Request, res: Response) {+ try {+ // Verify we're in setup pending mode+ if (!configService.isSetupPending()) {+ return res.status(400).json({+ success: false,+ error: 'Setup is not pending. Application is already configured.',+ });+ }++ // Verify we're on a keyring-supported platform+ if (!requiresKeyringSetup()) {+ return res.status(400).json({+ success: false,+ error: 'Keyring setup is only available on Windows and macOS binary installations.',+ });+ }++ const { encryptionKey, userName, userPassword } = req.body;++ // Validate required fields+ if (!encryptionKey || !userName || !userPassword) {+ return res.status(400).json({+ success: false,+ error: 'Missing required fields: encryptionKey, userName, userPassword',+ });+ }++ // Validate encryption key length+ if (encryptionKey.length < 12) {+ return res.status(400).json({+ success: false,+ error: 'Encryption key must be at least 12 characters long',+ });+ }++ // Validate username+ if (userName.length < 1) {+ return res.status(400).json({+ success: false,+ error: 'Username cannot be empty',+ });+ }++ // Validate password+ if (userPassword.length < 1) {+ return res.status(400).json({+ success: false,+ error: 'Password cannot be empty',+ });+ }++ // 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',+ });+ }++ // Update ConfigService with the new credentials+ configService.completeSetup({+ ENCRYPTION_KEY: encryptionKey,+ USER_NAME: userName,+ USER_PASSWORD: userPassword,+ });++ // Run the initial setup (creates database tables, default settings, etc.)+ await initSetup(db as unknown as BetterSQLite3Database);++ res.json({+ success: true,+ message: 'Setup completed successfully. Credentials stored securely.',+ });+ } catch (error: any) {+ console.error('[SetupController] Setup error:', error);+ res.status(500).json({+ success: false,+ error: error.message || 'Failed to complete setup',+ });+ }+ }++ /**+ * Check if keyring is available on this system+ */+ async checkKeyringAvailability(req: Request, res: Response) {+ try {+ const isSupported = keyringService.isPlatformSupported();+ const isAvailable = await keyringService.waitForInitialization();++ res.json({+ success: true,+ data: {+ platformSupported: isSupported,+ keyringAvailable: isAvailable,+ platform: process.platform,+ },+ });+ } catch (error: any) {+ res.status(500).json({+ success: false,+ error: error.message || 'Failed to check keyring availability',+ });+ }+ }+}diff --git a/backend/src/createApp.ts b/backend/src/createApp.tsindex 4067b46..1b8953b 100644--- a/backend/src/createApp.ts+++ b/backend/src/createApp.ts@@ -11,12 +11,14 @@ import { createRestoreRouter } from './routes/restores';import { createUserRouter } from './routes/users';import { createSettingsRouter } from './routes/settings';import { createHealthRouter } from './routes/health';+import { createSetupRouter } from './routes/setup';import { PlanController } from './controllers/PlanController';import { DeviceController } from './controllers/DeviceController';import { StorageController } from './controllers/StorageController';import { RestoreController } from './controllers/RestoreController';import { UserController } from './controllers/UserController';import { SettingsController } from './controllers/SettingsController';+import { SetupController } from './controllers/SetupController';import { createBackupRouter } from './routes/backups';import { BackupController } from './controllers/BackupController';@@ -120,6 +122,7 @@ export async function createApp(): Promise<{ app: Express }> {const storageController = new StorageController(storageService);const settingsController = new SettingsController(settingsService);const userController = new UserController();+ const setupController = new SetupController();console.log('process.env.APP_URL :', process.env.APP_URL);console.log(' configService.config.APP_URL:', configService.config.APP_URL);@@ -155,6 +158,7 @@ export async function createApp(): Promise<{ app: Express }> {});app.use('/api/', apiLimiter);+ app.use('/api/setup', createSetupRouter(setupController)); // Setup route (no auth required)app.use('/api/user', createUserRouter(userController));app.use('/api/plans', createPlanRouter(planController));app.use('/api/backups', createBackupRouter(backupController));diff --git a/backend/src/index.ts b/backend/src/index.tsindex 0c315c2..e517fb7 100644--- a/backend/src/index.ts+++ b/backend/src/index.ts@@ -5,7 +5,8 @@ import { migrate } from 'drizzle-orm/better-sqlite3/migrator';import { createApp } from './createApp';import { db } from './db';import { initSetup } from './utils/initSetup';-import { configService } from './services/ConfigService';+import { configService, ConfigService } from './services/ConfigService';+import { requiresKeyringSetup } from './utils/installHelpers';// Export main entry point for use as a libraryexport { createApp } from './createApp';@@ -23,6 +24,17 @@ const isDevelopment = process.env.NODE_ENV === 'development';if (isMainModule || isDevelopment) {(async () => {+ // For binary installations on Windows/macOS, try to load credentials from keyring+ if (requiresKeyringSetup() && configService.isSetupPending()) {+ console.log('[CORE] Attempting to load credentials from system keyring...');+ const loaded = await ConfigService.reinitializeWithKeyringCredentials();+ if (loaded) {+ console.log('[CORE] Credentials loaded from keyring successfully.');+ } else {+ console.log('[CORE] No credentials found in keyring. Waiting for initial setup...');+ }+ }+// Run database migrations firstif (process.env.NODE_ENV === 'production') {console.log('[CORE] Running database migrations...');@@ -54,11 +66,22 @@ if (isMainModule || isDevelopment) {}}- await initSetup(db as unknown as BetterSQLite3Database);+ // Only run initSetup if not in setup pending mode+ if (!configService.isSetupPending()) {+ await initSetup(db as unknown as BetterSQLite3Database);+ } else {+ console.log('[CORE] Setup pending - skipping initSetup. Complete setup via web interface.');+ }+const { app } = await createApp();const server = app.listen(configService.config.SERVER_PORT || 5173, () => {console.log(`[CORE] Server running on port ${configService.config.SERVER_PORT || 5173}`);+ if (configService.isSetupPending()) {+ console.log(+ `[CORE] ⚠️ Initial setup required. Visit http://localhost:${configService.config.SERVER_PORT || 5173} to complete setup.`+ );+ }});// Graceful shutdown handling for Dockerdiff --git a/backend/src/middlewares/versionMiddleware.ts b/backend/src/middlewares/versionMiddleware.tsindex abe718c..0ef1092 100644--- a/backend/src/middlewares/versionMiddleware.ts+++ b/backend/src/middlewares/versionMiddleware.ts@@ -1,13 +1,16 @@import { Request, Response, NextFunction } from 'express';+import { getInstallType } from '../utils/installHelpers';// Read package.json once at startuplet appVersion: string = process.env.APP_VERSION || 'dev';+/*** Middleware that adds the application version from package.json to response headers*/export default function versionMiddleware(req: Request, res: Response, next: NextFunction) {// Add version to response headersres.setHeader('X-App-Version', appVersion);- res.setHeader('X-SERVER-OS', process.platform);+ res.setHeader('X-Server-OS', process.platform);+ res.setHeader('X-Install-Type', getInstallType());next();}diff --git a/backend/src/routes/index.ts b/backend/src/routes/index.tsindex 5ca06b0..aa9cba1 100644--- a/backend/src/routes/index.ts+++ b/backend/src/routes/index.ts@@ -6,3 +6,4 @@ export { createUserRouter } from './users';export { createBackupRouter } from './backups';export { createSettingsRouter } from './settings';export { createHealthRouter } from './health';+export { createSetupRouter } from './setup';diff --git a/backend/src/routes/setup.ts b/backend/src/routes/setup.tsnew file mode 100644index 0000000..9ec0d19--- /dev/null+++ b/backend/src/routes/setup.ts@@ -0,0 +1,12 @@+import { Router } from 'express';+import { SetupController } from '../controllers/SetupController';++export function createSetupRouter(controller: SetupController): Router {+ const router = Router();++ router.get('/status', (req, res) => controller.getStatus(req, res));+ router.post('/complete', (req, res) => controller.completeSetup(req, res));+ router.get('/keyring-check', (req, res) => controller.checkKeyringAvailability(req, res));++ return router;+}diff --git a/backend/src/services/ConfigService.ts b/backend/src/services/ConfigService.tsindex eea3c19..9f3089e 100644--- a/backend/src/services/ConfigService.ts+++ b/backend/src/services/ConfigService.ts@@ -3,9 +3,10 @@ import fs from 'fs';import crypto from 'crypto';import { appPaths } from '../utils/AppPaths';import path from 'path';+import { requiresKeyringSetup } from '../utils/installHelpers';-// Schema for the .env config file-const configSchema = z.object({+// Schema for the .env config file (with optional sensitive fields for setup mode)+const baseConfigSchema = z.object({// GeneralNODE_ENV: z.enum(['development', 'production', 'test']).default('production'),SERVER_PORT: z.coerce.number().int().positive().default(5173),@@ -19,20 +20,35 @@ const configSchema = z.object({ALLOW_CUSTOM_RESTORE_PATH: z.coerce.boolean().default(true).optional(),ALLOW_FILE_BROWSER: z.coerce.boolean().default(true).optional(),- // Security- ENCRYPTION_KEY: z.string().min(12, { message: 'ENCRYPTION_KEY is required for rclone/restic.' }),+ // Security (optional in setup mode)+ ENCRYPTION_KEY: z+ .string()+ .min(12, { message: 'ENCRYPTION_KEY is required for rclone/restic.' })+ .optional(),SECRET: z.string().min(12).optional(),APIKEY: z.string().min(12).optional(),DISABLE_EVENT_SCRIPTS: z.coerce.boolean().default(false).optional(),- // User Authentication- USER_NAME: z.string().min(1).default('admin'),- USER_PASSWORD: z.string().min(1),+ // User Authentication (optional in setup mode)+ USER_NAME: z.string().min(1).optional(),+ USER_PASSWORD: z.string().min(1).optional(),SESSION_DURATION: z.coerce.number().int().positive().default(7), // in days++ // INTERNAL+ IS_DOCKER: z.coerce.boolean().default(false).optional(),+ IS_BINARY: z.coerce.boolean().default(false).optional(),+ SETUP_PENDING: z.coerce.boolean().default(false).optional(),+});++// Full config schema (requires all sensitive fields)+const configSchema = baseConfigSchema.extend({+ ENCRYPTION_KEY: z.string().min(12, { message: 'ENCRYPTION_KEY is required for rclone/restic.' }),+ USER_NAME: z.string().min(1, { message: 'USER_NAME is required.' }),+ USER_PASSWORD: z.string().min(1, { message: 'USER_PASSWORD is required.' }),});// A schema for the user-editable config.json file-const userConfigSchema = configSchema+const userConfigSchema = baseConfigSchema.pick({APP_TITLE: true,APP_URL: true,@@ -46,17 +62,45 @@ const userConfigSchema = configSchema}).partial();+// Final config schema for normal operation (requires all sensitive fields)const finalConfigSchema = configSchema.extend({SECRET: z.string().min(12),APIKEY: z.string().min(12),});+// Setup mode config schema (doesn't require sensitive fields)+const setupModeConfigSchema = baseConfigSchema.extend({+ SECRET: z.string().min(12),+ APIKEY: z.string().min(12),+ SETUP_PENDING: z.literal(true),+});+export type AppConfig = z.infer<typeof finalConfigSchema>;+export type SetupModeConfig = z.infer<typeof setupModeConfigSchema>;class ConfigService {private static instance: ConfigService;- public readonly config: AppConfig;- private keysPath: string;+ private _config!: AppConfig | SetupModeConfig;+ private keysPath: string = '';+ private _isSetupPending: boolean = false;++ /**+ * Returns the config. In setup mode, some fields may be undefined.+ */+ public get config(): AppConfig {+ if (this._isSetupPending) {+ // Return a partial config that works for setup mode+ return this._config as AppConfig;+ }+ return this._config as AppConfig;+ }++ /**+ * Check if the app is in setup pending mode (waiting for credentials)+ */+ public isSetupPending(): boolean {+ return this._isSetupPending;+ }private constructor() {// Note: dotenv is loaded in index.ts before this service is initialized@@ -80,7 +124,7 @@ class ConfigService {// Initialize or load SECRET and APIKEY// 2. Layer user's config.json file- let fileConfig = {};+ let fileConfig: Record<string, any> = {};const configPath = path.join(appPaths.getConfigDir(), 'config.json');try {if (fs.existsSync(configPath)) {@@ -105,6 +149,8 @@ class ConfigService {fileConfig = userConfigSchema.parse(parsedJson); // Validate the user's config (will exclude sensitive fields)console.log(`[ConfigService] Loaded user configuration from ${configPath}`);+ } else {+ console.log(`[ConfigService] No config.json found at ${configPath}`);}} catch (error) {console.log(@@ -122,13 +168,36 @@ class ConfigService {...fileConfig,SECRET: secrets.SECRET, // System secrets fill in the gapsAPIKEY: secrets.APIKEY,+ IS_DOCKER: rawEnv.IS_DOCKER === 'true' || rawEnv.IS_DOCKER === '1',+ IS_BINARY: (process as any).pkg ? true : false,};// 5. Validate final configurationconst parsedConfig = finalConfigSchema.safeParse(mergedConfig);if (!parsedConfig.success) {- // If validation fails, log the errors and exit immediately.+ // Check if we're in binary mode on a keyring-supported platform+ // In this case, we can start in "setup pending" mode+ if (requiresKeyringSetup()) {+ 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.');++ // Create a setup-mode config with placeholder values+ this._isSetupPending = true;+ this._config = {+ ...mergedConfig,+ ENCRYPTION_KEY: '', // Will be set during setup+ USER_NAME: 'admin', // Default value+ USER_PASSWORD: '', // Will be set during setup+ SETUP_PENDING: true,+ } as SetupModeConfig;++ console.log('⏳ Environment configuration loaded in SETUP PENDING mode.');+ return;+ }++ // If validation fails and not in keyring mode, log the errors and exit immediately.// This is "fail-fast" and prevents the app from running in a broken state.console.error('❌ Invalid environment configuration:');parsedConfig.error.issues.forEach(err => {@@ -142,7 +211,7 @@ class ConfigService {process.exit(1);}- this.config = parsedConfig.data;+ this._config = parsedConfig.data;console.log('✅ Environment configuration loaded and validated successfully.');}@@ -204,7 +273,63 @@ class ConfigService {public isDevelopment(): boolean {return this.config.NODE_ENV === 'development';}++ /**+ * Complete the initial setup by updating config with credentials.+ * This is called after credentials are stored in the keyring.+ */+ public completeSetup(credentials: {+ ENCRYPTION_KEY: string;+ USER_NAME: string;+ USER_PASSWORD: string;+ }): void {+ if (!this._isSetupPending) {+ throw new Error('Setup is not pending. Cannot complete setup.');+ }++ // Update the config with the new credentials+ this._config = {+ ...this._config,+ ...credentials,+ SETUP_PENDING: false,+ } as AppConfig;++ this._isSetupPending = false;+ console.log('✅ [ConfigService] Setup completed. Credentials loaded from keyring.');+ }++ /**+ * Reinitialize ConfigService with credentials from keyring.+ * Used after initial setup to reload config with actual credentials.+ */+ public static async reinitializeWithKeyringCredentials(): 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 && credentials.USER_NAME && credentials.USER_PASSWORD) {+ ConfigService.instance.completeSetup({+ ENCRYPTION_KEY: credentials.ENCRYPTION_KEY,+ USER_NAME: credentials.USER_NAME,+ USER_PASSWORD: credentials.USER_PASSWORD,+ });+ return true;+ }+ } catch (error) {+ console.error('[ConfigService] Failed to reinitialize with keyring credentials:', error);+ }++ return false;+ }}// Export a single, ready-to-use instance (the singleton)export const configService = ConfigService.getInstance();++// Also export the class for static methods+export { ConfigService };diff --git a/backend/src/services/KeyringService.ts b/backend/src/services/KeyringService.tsnew file mode 100644index 0000000..0a77db0--- /dev/null+++ b/backend/src/services/KeyringService.ts@@ -0,0 +1,298 @@+import os from 'os';+import path from 'path';+import { createRequire } from 'module';+import { isLinuxDesktop, isKeyringPlatform, isBinaryMode } from '../utils/installHelpers';++const SERVICE_NAME = 'Pluton';++// Credential keys stored in the OS keyring+export const KEYRING_KEYS = {+ ENCRYPTION_KEY: 'ENCRYPTION_KEY',+ USER_NAME: 'USER_NAME',+ USER_PASSWORD: 'USER_PASSWORD',+} as const;++export type KeyringKey = (typeof KEYRING_KEYS)[keyof typeof KEYRING_KEYS];++export interface KeyringCredentials {+ ENCRYPTION_KEY: string;+ USER_NAME: string;+ USER_PASSWORD: string;+}++/**+ * Gets the platform-specific keyring package name and node file+ */+function getKeyringPlatformInfo(): { packageName: string; nodeFile: string } | null {+ const platform = os.platform();+ const arch = os.arch();++ if (platform === 'win32' && arch === 'x64') {+ return {+ packageName: '@napi-rs/keyring-win32-x64-msvc',+ nodeFile: 'keyring.win32-x64-msvc.node',+ };+ } else if (platform === 'darwin' && arch === 'x64') {+ return {+ packageName: '@napi-rs/keyring-darwin-x64',+ nodeFile: 'keyring.darwin-x64.node',+ };+ } else if (platform === 'darwin' && arch === 'arm64') {+ return {+ packageName: '@napi-rs/keyring-darwin-arm64',+ nodeFile: 'keyring.darwin-arm64.node',+ };+ } else if (platform === 'linux' && arch === 'x64') {+ return {+ packageName: '@napi-rs/keyring-linux-x64-gnu',+ nodeFile: 'keyring.linux-x64-gnu.node',+ };+ } else if (platform === 'linux' && arch === 'arm64') {+ return {+ packageName: '@napi-rs/keyring-linux-arm64-gnu',+ nodeFile: 'keyring.linux-arm64-gnu.node',+ };+ }++ return null;+}++/**+ * KeyringService provides a secure way to store and retrieve sensitive credentials+ * using the OS-specific credential manager (Windows Credential Manager / macOS Keychain / Linux Secret Service).+ *+ * This is only used for pkg-packaged executables on Windows, macOS, and Linux desktop environments.+ * Note: On Windows Requires C++ Redistributable to be installed.+ * https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170#latest-supported-redistributable-version+ */+class KeyringService {+ private static instance: KeyringService;+ private isSupported: boolean = false;+ private Entry: any = null;++ private constructor() {+ this.initializeKeyring();+ }++ /**+ * Loads the keyring native module for pkg binary mode+ * The .node file is placed in node_modules/@napi-rs/keyring-<platform>/ alongside the executable+ */+ private loadKeyringFromExternalPath(): any {+ const platformInfo = getKeyringPlatformInfo();+ if (!platformInfo) {+ throw new Error(`Unsupported platform: ${os.platform()} ${os.arch()}`);+ }++ // In pkg binary mode, native modules are in node_modules next to the executable+ const execDir = path.dirname(process.execPath);+ const nodeFilePath = path.join(+ execDir,+ 'node_modules',+ '@napi-rs',+ platformInfo.packageName.replace('@napi-rs/', ''),+ platformInfo.nodeFile+ );++ console.log(`[KeyringService] Loading keyring from: ${nodeFilePath}`);++ // Use createRequire to load the .node file+ const require = createRequire(import.meta.url);+ const nativeModule = require(nodeFilePath);++ return nativeModule;+ }++ /**+ * Initializes the keyring module if available and supported+ */+ private async initializeKeyring(): Promise<void> {+ const platform = os.platform();+ const isSupportedPlatform = isKeyringPlatform();++ if (!isSupportedPlatform) {+ if (platform === 'linux') {+ console.log(+ '[KeyringService] Linux detected but no desktop environment found (headless/server mode)'+ );+ } else {+ console.log('[KeyringService] Keyring not supported on this platform:', platform);+ }+ this.isSupported = false;+ return;+ }++ try {+ let keyring: any;++ // In pkg binary mode, load from external path+ if (isBinaryMode()) {+ keyring = this.loadKeyringFromExternalPath();+ } else {+ // In development/docker mode, use dynamic import+ keyring = await import('@napi-rs/keyring');+ }++ this.Entry = keyring.Entry;+ this.isSupported = true;+ const envInfo = platform === 'linux' ? ' (Linux desktop)' : '';+ console.log(`[KeyringService] Keyring module loaded successfully${envInfo}`);+ } catch (error) {+ console.log('[KeyringService] Keyring module not available:', error);+ this.isSupported = false;+ }+ }++ /**+ * Gets the singleton instance of KeyringService+ */+ public static getInstance(): KeyringService {+ if (!KeyringService.instance) {+ KeyringService.instance = new KeyringService();+ }+ return KeyringService.instance;+ }++ /**+ * Checks if the keyring is supported on the current platform+ */+ public isPlatformSupported(): boolean {+ return isKeyringPlatform();+ }++ /**+ * Checks if the keyring module is loaded and ready+ */+ public isKeyringAvailable(): boolean {+ return this.isSupported && this.Entry !== null;+ }++ /**+ * Waits for the keyring to be initialized (async initialization)+ */+ public async waitForInitialization(): Promise<boolean> {+ // Give some time for async initialization+ if (!this.isSupported && this.Entry === null) {+ await this.initializeKeyring();+ }+ return this.isKeyringAvailable();+ }++ /**+ * Stores a credential in the OS keyring+ */+ public async setCredential(key: KeyringKey, value: string): Promise<boolean> {+ if (!(await this.waitForInitialization())) {+ console.error('[KeyringService] Keyring not available');+ return false;+ }++ try {+ const entry = new this.Entry(SERVICE_NAME, key);+ entry.setPassword(value);+ console.log(`[KeyringService] Credential '${key}' stored successfully`);+ return true;+ } catch (error) {+ console.error(`[KeyringService] Failed to store credential '${key}':`, error);+ return false;+ }+ }++ /**+ * Retrieves a credential from the OS keyring+ */+ public async getCredential(key: KeyringKey): Promise<string | null> {+ if (!(await this.waitForInitialization())) {+ return null;+ }++ try {+ const entry = new this.Entry(SERVICE_NAME, key);+ const password = entry.getPassword();+ return password || null;+ } catch (error) {+ // Credential not found is not an error, just return null+ return null;+ }+ }++ /**+ * Deletes a credential from the OS keyring+ */+ public async deleteCredential(key: KeyringKey): Promise<boolean> {+ if (!(await this.waitForInitialization())) {+ return false;+ }++ try {+ const entry = new this.Entry(SERVICE_NAME, key);+ entry.deletePassword();+ console.log(`[KeyringService] Credential '${key}' deleted successfully`);+ return true;+ } catch (error) {+ console.error(`[KeyringService] Failed to delete credential '${key}':`, error);+ return false;+ }+ }++ /**+ * Stores all required credentials at once+ */+ public async setAllCredentials(credentials: KeyringCredentials): Promise<boolean> {+ const results = await Promise.all([+ this.setCredential(KEYRING_KEYS.ENCRYPTION_KEY, credentials.ENCRYPTION_KEY),+ this.setCredential(KEYRING_KEYS.USER_NAME, credentials.USER_NAME),+ this.setCredential(KEYRING_KEYS.USER_PASSWORD, credentials.USER_PASSWORD),+ ]);++ return results.every(Boolean);+ }++ /**+ * Retrieves all credentials from the OS keyring+ */+ public async getAllCredentials(): Promise<Partial<KeyringCredentials>> {+ const [encryptionKey, userName, userPassword] = await Promise.all([+ this.getCredential(KEYRING_KEYS.ENCRYPTION_KEY),+ this.getCredential(KEYRING_KEYS.USER_NAME),+ this.getCredential(KEYRING_KEYS.USER_PASSWORD),+ ]);++ const credentials: Partial<KeyringCredentials> = {};++ if (encryptionKey) credentials.ENCRYPTION_KEY = encryptionKey;+ if (userName) credentials.USER_NAME = userName;+ if (userPassword) credentials.USER_PASSWORD = userPassword;++ return credentials;+ }++ /**+ * Checks if all required credentials are stored in the keyring+ */+ public async hasAllCredentials(): Promise<boolean> {+ const credentials = await this.getAllCredentials();+ return !!(+ credentials.ENCRYPTION_KEY &&+ credentials.USER_NAME &&+ credentials.USER_PASSWORD &&+ credentials.ENCRYPTION_KEY.length >= 12+ );+ }++ /**+ * Deletes all Pluton credentials from the OS keyring+ */+ public async deleteAllCredentials(): Promise<boolean> {+ const results = await Promise.all([+ this.deleteCredential(KEYRING_KEYS.ENCRYPTION_KEY),+ this.deleteCredential(KEYRING_KEYS.USER_NAME),+ this.deleteCredential(KEYRING_KEYS.USER_PASSWORD),+ ]);++ return results.every(Boolean);+ }+}++// Export singleton instance+export const keyringService = KeyringService.getInstance();diff --git a/backend/src/utils/installHelpers.ts b/backend/src/utils/installHelpers.tsnew file mode 100644index 0000000..3750a59--- /dev/null+++ b/backend/src/utils/installHelpers.ts@@ -0,0 +1,75 @@+/**+ * Installation Helper Utilities+ *+ * Helper functions to detect installation type, platform capabilities,+ * and environment configuration for the Pluton application.+ */++export type InstallType = 'docker' | 'binary' | 'dev';++/**+ * Check if running as a pkg-packaged binary+ */+export function isBinaryMode(): boolean {+ return !!(process as any).pkg;+}++/**+ * Check if running in Docker container+ */+export function isDockerMode(): boolean {+ return process.env.IS_DOCKER === 'true' || process.env.IS_DOCKER === '1';+}++/**+ * Determines the installation type of the application+ * @returns 'docker' | 'binary' | 'dev'+ */+export function getInstallType(): InstallType {+ if (isDockerMode()) {+ return 'docker';+ }+ if (isBinaryMode()) {+ return 'binary';+ }+ return 'dev';+}++/**+ * Checks if running on a Linux desktop environment (not headless/server)+ * by checking for common display environment variables+ */+export function isLinuxDesktop(): boolean {+ if (process.platform !== 'linux') return false;++ // Check for display server (X11 or Wayland)+ const hasDisplay = !!(process.env.DISPLAY || process.env.WAYLAND_DISPLAY);++ // Check for common desktop environment indicators+ const hasDesktopEnv = !!(+ process.env.XDG_CURRENT_DESKTOP ||+ process.env.DESKTOP_SESSION ||+ process.env.GNOME_DESKTOP_SESSION_ID ||+ process.env.KDE_FULL_SESSION+ );++ return hasDisplay || hasDesktopEnv;+}++/**+ * Check if running on a platform that supports keyring (Windows/macOS/Linux Desktop)+ */+export function isKeyringPlatform(): boolean {+ const platform = process.platform;+ return (+ platform === 'win32' || platform === 'darwin' || (platform === 'linux' && isLinuxDesktop())+ );+}++/**+ * Check if the app requires keyring-based initial setup+ * This is true when: running as binary + on a keyring-supported platform+ */+export function requiresKeyringSetup(): boolean {+ return isBinaryMode() && isKeyringPlatform();+}diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex 1355f6e..664cb1c 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -1,24 +1,20 @@import { createRoot } from 'react-dom/client';-import { RouterProvider } from 'react-router';+import { BrowserRouter } from 'react-router';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { ReactQueryDevtools } from '@tanstack/react-query-devtools';-import { router } from './router';+import { AppRoutes } from './router';import { ThemeProvider } from './context/ThemeContext';import './styles/global.scss';const queryClient = new QueryClient();-function AppWrapper() {- return (- <ThemeProvider>- <RouterProvider router={router} />- </ThemeProvider>- );-}-createRoot(document.getElementById('root')!).render(<QueryClientProvider client={queryClient}>- <AppWrapper />+ <ThemeProvider>+ <BrowserRouter>+ <AppRoutes />+ </BrowserRouter>+ </ThemeProvider><ReactQueryDevtools initialIsOpen={false} buttonPosition="bottom-left" /></QueryClientProvider>,);diff --git a/frontend/src/router.tsx b/frontend/src/router.tsxindex 02d45ba..20cba49 100644--- a/frontend/src/router.tsx+++ b/frontend/src/router.tsx@@ -1,7 +1,9 @@-import { createBrowserRouter, createRoutesFromElements, Route, Navigate } from 'react-router';+import { Routes, Route, Navigate } from 'react-router';import Plans from './routes/Plans/Plans';import Login from './routes/Login/Login';+import Setup from './routes/Setup/Setup';import { useAuth } from './services/users';+import { useSetupStatus } from './services/settings';import App from './components/App/App/App';import Settings from './routes/Settings/Settings';import Storages from './routes/Storages/Storages';@@ -10,29 +12,59 @@ import PlanSingle from './routes/PlanSingle/PlanSingle';import DeviceSingle from './routes/DeviceSingle/DeviceSingle';import Footer from './components/App/Footer/Footer';import NotFoundRoute from './routes/NotFoundRoute/NotFoundRoute';+import Icon from './components/common/Icon/Icon';function ProtectedLayout() {- const { data, isError } = useAuth();- console.log('User data :', data);- // if (isLoading)- // return (- // <div className="loadingScreen">- // <Icon size={60} type="loading" />{' '}- // </div>- // );- if (isError) return <Navigate to="/login" replace />;+ // Check setup status FIRST - this endpoint doesn't require auth+ // and tells us if we're in binary mode and if setup is pending+ const { data: setupStatus, isLoading: setupLoading } = useSetupStatus();+ const { data: authData, isError: authError, isLoading: authLoading } = useAuth();++ // Show loading spinner while checking setup status+ if (setupLoading) {+ return (+ <div className="loadingScreen">+ <Icon size={60} type="loading" />+ </div>+ );+ }++ // If setup status check failed, we can still proceed with auth check+ // (might be a network issue or old backend without setup endpoint)++ // For binary installations with pending setup, redirect to setup page+ // This check happens BEFORE auth check so unauthenticated users can access setup+ if (setupStatus?.data?.isBinary && setupStatus?.data?.setupPending) {+ return <Navigate to="/setup" replace />;+ }++ // Now check auth (setup is either complete or not a binary installation)+ if (authLoading) {+ return (+ <div className="loadingScreen">+ <Icon size={60} type="loading" />+ </div>+ );+ }++ // If auth failed, redirect to login+ if (authError) {+ return <Navigate to="/login" replace />;+ }++ console.log('User data :', authData);return (<><App />- <Footer version={data?.appVersion} />+ <Footer version={authData?.appVersion || ''} /></>);}-export const router = createBrowserRouter(- createRoutesFromElements(- <>+export function AppRoutes() {+ return (+ <Routes><Route path="/" element={<ProtectedLayout />}><Route index element={<Plans />} /><Route path="settings" element={<Settings />} />@@ -43,6 +75,7 @@ export const router = createBrowserRouter(<Route path="*" element={<NotFoundRoute />} /></Route><Route path="login" element={<Login />} />- </>,- ),-);+ <Route path="setup" element={<Setup />} />+ </Routes>+ );+}diff --git a/frontend/src/routes/Setup/BinarySetup.tsx b/frontend/src/routes/Setup/BinarySetup.tsxnew file mode 100644index 0000000..1ad4f34--- /dev/null+++ b/frontend/src/routes/Setup/BinarySetup.tsx@@ -0,0 +1,33 @@+import { Navigate } from 'react-router';+import { Footer, Icon } from '../../components';+import { useSetupStatus } from '../../services/settings';++/**+ * Component that checks setup status for binary installations+ * This is a separate component so useSetupStatus is only called when needed+ */+const BinarySetup = ({ children, appVersion }: { children: React.ReactNode; appVersion: string }) => {+ const { data: setupStatus, isLoading: setupLoading } = useSetupStatus();++ if (setupLoading) {+ return (+ <div className="loadingScreen">+ <Icon size={60} type="loading" />+ </div>+ );+ }++ // If setup is pending, redirect to setup page+ if (setupStatus?.data?.setupPending) {+ return <Navigate to="/setup" replace />;+ }++ return (+ <>+ {children}+ <Footer version={appVersion} />+ </>+ );+};++export default BinarySetup;diff --git a/frontend/src/routes/Setup/Setup.module.scss b/frontend/src/routes/Setup/Setup.module.scssnew file mode 100644index 0000000..10a3ac9--- /dev/null+++ b/frontend/src/routes/Setup/Setup.module.scss@@ -0,0 +1,174 @@+.setupPage {+ width: 100%;+ min-height: 100vh;+ display: flex;+ align-items: center;+ justify-content: flex-start;+ flex-direction: column;+ box-sizing: border-box;+}++.setupLogo {+ margin-bottom: 20px;+ h3 {+ display: flex;+ align-items: center;+ color: var(--primary-color);+ font-size: 1.25rem;+ text-transform: uppercase;+ font-weight: 900;+ span:nth-child(1) {+ display: flex;+ color: var(--primary-color);+ }+ span:nth-child(2) {+ margin-left: 5px;+ }+ }+}++.setupContainer {+ width: 400px;+ max-width: 90%;+ border-radius: 10px;+ background-color: var(--content-background-color);+ padding: 35px 30px;+ box-shadow: 0 0 10px var(--content-shadow-color);+}++.setupHeader {+ text-align: center;+ margin-bottom: 25px;++ h2 {+ margin: 0 0 10px 0;+ color: var(--content-text-color);+ font-size: 1.3rem;+ }++ p {+ margin: 0;+ color: var(--content-text-muted-color);+ font-size: 0.875rem;+ line-height: 1.5;+ }+}++.setupForm {+ width: 100%;+}++.setupInput {+ margin-bottom: 20px;+ position: relative;++ label {+ display: block;+ color: var(--content-text-color);+ font-size: 0.8125rem;+ font-weight: 600;+ margin-bottom: 6px;+ }++ input {+ border: 1px solid;+ border-color: var(--line-color);+ border-radius: 6px;+ padding: 14px;+ padding-left: 40px;+ width: 100%;+ box-sizing: border-box;+ outline: none;+ font-size: 0.875rem;+ transition: border-color 0.2s ease;++ &:focus {+ outline: none;+ border-color: var(--primary-color);+ box-shadow: 0 0 0 3px rgba(var(--primary-color-rgb), 0.1);+ }+ }++ .setupInputIcon {+ position: absolute !important;+ left: 14px;+ top: 42px;+ opacity: 0.6;+ }++ .inputHint {+ margin-top: 6px;+ font-size: 0.75rem;+ color: var(--content-text-muted-color);+ }+}++.setupButton {+ background-color: var(--primary-color);+ color: var(--primary-text-color);+ font-size: 0.875rem;+ border-radius: 6px;+ width: 100%;+ box-sizing: border-box;+ padding: 14px;+ font-weight: 600;+ cursor: pointer;+ transition: opacity 0.2s ease;+ margin-top: 10px;++ &:hover:not(:disabled) {+ opacity: 0.9;+ }++ &:disabled {+ opacity: 0.6;+ cursor: not-allowed;+ }+}++.setupErrorMsg {+ color: var(--error-text-color);+ background-color: var(--error-bg-color);+ padding: 14px;+ border-radius: 6px;+ margin-top: 15px;+ font-size: 0.875rem;+}++.setupSuccessMsg {+ color: var(--success-text-color);+ background-color: var(--success-bg-color);+ padding: 14px;+ border-radius: 6px;+ margin-top: 15px;+ font-size: 0.875rem;+ text-align: center;+}++.setupInfoBox {+ border-left: 4px solid var(--primary-color);+ background-color: var(--primary-color-lighter);+ padding: 15px;+ border-radius: 6px;+ margin-bottom: 25px;++ h4 {+ margin: 0 0 8px 0;+ color: var(--content-text-color);+ font-size: 0.9375rem;+ }++ p {+ margin: 0;+ color: var(--content-text-muted-color);+ font-size: 0.8125rem;+ line-height: 1.5;+ }+}++.loadingSpinner {+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 40px;+}diff --git a/frontend/src/routes/Setup/Setup.tsx b/frontend/src/routes/Setup/Setup.tsxnew file mode 100644index 0000000..37a39f4--- /dev/null+++ b/frontend/src/routes/Setup/Setup.tsx@@ -0,0 +1,194 @@+import { useState } from 'react';+import { useNavigate } from 'react-router';+import classes from './Setup.module.scss';+import Logo from '../../components/common/Logo/Logo';+import { APP_NAME } from '../../utils/constants';+import Icon from '../../components/common/Icon/Icon';+import PageTitle from '../../components/App/PageTitle/PageTitle';+import { useSetupStatus, useCompleteSetup } from '../../services/settings';++const Setup = () => {+ const navigate = useNavigate();+ const [encryptionKey, setEncryptionKey] = useState<string>('');+ const [userName, setUserName] = useState<string>('admin');+ const [userPassword, setUserPassword] = useState<string>('');+ const [confirmPassword, setConfirmPassword] = useState<string>('');+ const [error, setError] = useState<string | null>(null);+ const [success, setSuccess] = useState<boolean>(false);++ const { data: statusData, isLoading: statusLoading, isError: statusError } = useSetupStatus();+ const setupMutation = useCompleteSetup();++ const handleSetup = () => {+ setError(null);++ // Validate encryption key+ if (!encryptionKey || encryptionKey.length < 12) {+ setError('Encryption key must be at least 12 characters long');+ return;+ }++ // Validate username+ if (!userName || userName.length < 1) {+ setError('Username cannot be empty');+ return;+ }++ // Validate password+ if (!userPassword || userPassword.length < 1) {+ setError('Password cannot be empty');+ return;+ }++ // Validate password confirmation+ if (userPassword !== confirmPassword) {+ setError('Passwords do not match');+ return;+ }++ setupMutation.mutate(+ {+ encryptionKey,+ userName,+ userPassword,+ },+ {+ onSuccess: (res) => {+ if (res.success) {+ setSuccess(true);+ setError(null);+ // Redirect to login after 2 seconds+ setTimeout(() => {+ navigate('/login');+ }, 2000);+ } else {+ setError(res.error || 'Setup failed');+ }+ },+ onError: (err: Error) => {+ setError(err.message || 'Setup failed');+ },+ },+ );+ };++ // Show loading state+ if (statusLoading) {+ return (+ <div className={classes.setupPage}>+ <PageTitle title="Initial Setup" />+ <div className={classes.setupLogo}>+ <h3>+ <Logo size={40} /> <span>{APP_NAME}</span>+ </h3>+ </div>+ <div className={classes.setupContainer}>+ <div className={classes.loadingSpinner}>+ <Icon size={40} type="loading" />+ </div>+ </div>+ </div>+ );+ }++ // If setup is not pending, redirect to login+ if (statusData && !statusData.data.setupPending) {+ navigate('/login');+ return null;+ }++ // Show error if status check failed+ if (statusError) {+ return (+ <div className={classes.setupPage}>+ <PageTitle title="Initial Setup" />+ <div className={classes.setupLogo}>+ <h3>+ <Logo size={40} /> <span>{APP_NAME}</span>+ </h3>+ </div>+ <div className={classes.setupContainer}>+ <div className={classes.setupErrorMsg}>Failed to check setup status. Please refresh the page.</div>+ </div>+ </div>+ );+ }++ return (+ <div className={classes.setupPage}>+ <PageTitle title="Initial Setup" />+ <div className={classes.setupLogo}>+ <h3>+ <Logo size={40} /> <span>{APP_NAME}</span>+ </h3>+ </div>+ <div className={classes.setupContainer}>+ <div className={classes.setupHeader}>+ <h2>Initial Setup</h2>+ <p>Configure your {APP_NAME} installation. These credentials will be securely stored in your system's credential manager.</p>+ </div>++ <div className={classes.setupInfoBox}>+ <p>+ Your encryption key will be used to encrypt all your backups.+ <strong> Keep it safe - if you lose it, you won't be able to restore your backups!</strong>+ </p>+ </div>++ {success ? (+ <div className={classes.setupSuccessMsg}>Setup completed successfully! Redirecting to login...</div>+ ) : (+ <div className={classes.setupForm}>+ <div className={classes.setupInput}>+ <label>Encryption Key</label>+ <Icon type="lock" classes={classes.setupInputIcon} />+ <input+ type="password"+ value={encryptionKey}+ placeholder="Enter encryption key (min 12 characters)"+ onChange={(e) => setEncryptionKey(e.target.value)}+ />+ <div className={classes.inputHint}>Used to encrypt all your backups. Minimum 12 characters.</div>+ </div>++ <div className={classes.setupInput}>+ <label>Admin Username</label>+ <Icon type="user" classes={classes.setupInputIcon} />+ <input type="text" value={userName} placeholder="Enter admin username" onChange={(e) => setUserName(e.target.value)} />+ </div>++ <div className={classes.setupInput}>+ <label>Admin Password</label>+ <Icon type="password" classes={classes.setupInputIcon} />+ <input+ type="password"+ value={userPassword}+ placeholder="Enter admin password"+ onChange={(e) => setUserPassword(e.target.value)}+ />+ </div>++ <div className={classes.setupInput}>+ <label>Confirm Password</label>+ <Icon type="password" classes={classes.setupInputIcon} />+ <input+ type="password"+ value={confirmPassword}+ placeholder="Confirm admin password"+ onChange={(e) => setConfirmPassword(e.target.value)}+ />+ </div>++ <button className={classes.setupButton} onClick={handleSetup} disabled={setupMutation.isPending}>+ {setupMutation.isPending ? 'Setting up...' : 'Complete Setup'}+ </button>++ {error && <div className={classes.setupErrorMsg}>{error}</div>}+ </div>+ )}+ </div>+ </div>+ );+};++export default Setup;diff --git a/frontend/src/routes/index.ts b/frontend/src/routes/index.tsindex 44facd2..c40302f 100644--- a/frontend/src/routes/index.ts+++ b/frontend/src/routes/index.ts@@ -5,5 +5,6 @@ export { default as NotFoundRoute } from './NotFoundRoute/NotFoundRoute';export { default as Plans } from './Plans/Plans';export { default as PlanSingle } from './PlanSingle/PlanSingle';export { default as Settings } from './Settings/Settings';+export { default as Setup } from './Setup/Setup';export { default as Sources } from './Sources/Sources';export { default as Storages } from './Storages/Storages';diff --git a/frontend/src/services/settings.ts b/frontend/src/services/settings.tsindex be739b9..b00bf9e 100644--- a/frontend/src/services/settings.ts+++ b/frontend/src/services/settings.ts@@ -1,6 +1,8 @@import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { API_URL } from '../utils/constants';+// ============== Settings API ==============+// Get Settingsexport async function getSettings() {const url = new URL(`${API_URL}/settings`);@@ -161,3 +163,51 @@ export function useValidateIntegration() {},});}++// ============== Setup API ==============++export interface SetupStatus {+ setupPending: boolean;+ isBinary: boolean;+ requiresKeyringSetup: boolean;+ platform: string;+}++export interface SetupCredentials {+ encryptionKey: string;+ userName: string;+ userPassword: string;+}++// Fetch setup status+export async function getSetupStatus(): Promise<{ success: boolean; data: SetupStatus }> {+ const res = await fetch(`${API_URL}/setup/status`, { method: 'GET' });+ if (!res.ok) {+ throw new Error('Failed to get setup status');+ }+ return res.json();+}++export function useSetupStatus() {+ return useQuery({+ queryKey: ['setupStatus'],+ queryFn: getSetupStatus,+ retry: false,+ });+}++// Complete setup+export async function completeSetup(credentials: SetupCredentials): Promise<{ success: boolean; message?: string; error?: string }> {+ const res = await fetch(`${API_URL}/setup/complete`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(credentials),+ });+ return res.json();+}++export function useCompleteSetup() {+ return useMutation({+ mutationFn: completeSetup,+ });+}diff --git a/frontend/src/services/users.ts b/frontend/src/services/users.tsindex 69df9a9..32b431e 100644--- a/frontend/src/services/users.ts+++ b/frontend/src/services/users.ts@@ -7,6 +7,8 @@ interface LoginCredentials {password: string;}+export type InstallType = 'docker' | 'binary' | 'dev';+//VALIDATE USERexport async function validateAuth() {const res = await fetch(`${API_URL}/user/validate`, { method: 'GET', credentials: 'include' });@@ -15,14 +17,17 @@ export async function validateAuth() {}const appVersion = res.headers.get('x-app-version');const serverOS = res.headers.get('x-server-os');+ const installType = (res.headers.get('x-install-type') || 'dev') as InstallType;(window as any).plutonVersion = appVersion || 'unknown';(window as any).plutonServerOS = serverOS || 'unknown';+ (window as any).plutonInstallType = installType;const data = await res.json();return {...data,appVersion,+ installType,};}diff --git a/installers/windows/pluton-setup.iss b/installers/windows/pluton-setup.issindex 7a8b42a..67296a8 100644--- a/installers/windows/pluton-setup.iss+++ b/installers/windows/pluton-setup.iss@@ -70,14 +70,12 @@ Source: "..\..\dist\executables\pluton-win-x64\drizzle\*"; DestDir: "{app}\drizzSource: "tools\nssm.exe"; DestDir: "{app}"; Flags: ignoreversion[Registry]-; Set system-wide environment variables for sensitive data-Root: HKLM; Subkey: "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"; ValueType: string; ValueName: "PLUTON_ENCRYPTION_KEY"; ValueData: "{code:GetEncryptionKey}"; Flags: uninsdeletevalue-Root: HKLM; Subkey: "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"; ValueType: string; ValueName: "PLUTON_USER_NAME"; ValueData: "{code:GetUserName}"; Flags: uninsdeletevalue-Root: HKLM; Subkey: "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"; ValueType: string; ValueName: "PLUTON_USER_PASSWORD"; ValueData: "{code:GetUserPassword}"; Flags: uninsdeletevalue--; Also set the data directory explicitly if needed, though AppPaths defaults to ProgramData+; Set the data directory environment variableRoot: 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 the service using NSSMFilename: "{app}\nssm.exe"; Parameters: "install {#MyAppServiceName} ""{app}\{#MyAppExeName}"""; Flags: runhidden; StatusMsg: "Installing service..."@@ -87,8 +85,10 @@ Filename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} Description ""PFilename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} Start SERVICE_AUTO_START"; Flags: runhidden; Set service AppDirectoryFilename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} AppDirectory ""{app}"""; Flags: runhidden-; Set environment variables directly on the service (Avoids reboot requirement)-Filename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} AppEnvironmentExtra PLUTON_ENCRYPTION_KEY=""{code:GetEncryptionKey}"" PLUTON_USER_NAME=""{code:GetUserName}"" PLUTON_USER_PASSWORD=""{code:GetUserPassword}"" PLUTON_DATA_DIR=""{commonappdata}\{#MyAppName}"""; 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 loggingFilename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} AppStdout ""{commonappdata}\{#MyAppName}\logs\service-out.log"""; Flags: runhiddenFilename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} AppStderr ""{commonappdata}\{#MyAppName}\logs\service-err.log"""; Flags: runhidden@@ -103,22 +103,9 @@ Filename: "{app}\nssm.exe"; Parameters: "remove {#MyAppServiceName} confirm"; Fl[Code]var- SensitivePage: TWizardPage;SettingsPage: TInputQueryWizardPage;- // Custom Controls for Sensitive Page- lblEncryptionKey: TLabel;- txtEncryptionKey: TPasswordEdit;- lblEncryptionKeyInfo: TLabel;-- lblUserName: TLabel;- txtUserName: TNewEdit;-- lblUserPassword: TLabel;- txtUserPassword: TPasswordEdit;-// Variables to store inputs- EncryptionKey, UserName, UserPassword: string;ServerPort, MaxConcurrentBackups: string;procedure InitializeWizard;@@ -126,67 +113,13 @@ begin// Customize Wizard ColorsWizardForm.MainPanel.Color := $fff5f5;- // --- 1. Sensitive Configuration Page (Custom) ---- SensitivePage := CreateCustomPage(wpLicense,- 'Security Configuration', 'Please enter the required security credentials.');-- // Encryption Key Label- lblEncryptionKey := TLabel.Create(WizardForm);- lblEncryptionKey.Parent := SensitivePage.Surface;- lblEncryptionKey.Caption := 'Encryption Key (min 12 chars):';- lblEncryptionKey.Left := 0;- lblEncryptionKey.Top := 0;-- // Encryption Key Input- txtEncryptionKey := TPasswordEdit.Create(WizardForm);- txtEncryptionKey.Parent := SensitivePage.Surface;- txtEncryptionKey.Left := 0;- txtEncryptionKey.Top := lblEncryptionKey.Top + lblEncryptionKey.Height + 6;- txtEncryptionKey.Width := SensitivePage.SurfaceWidth;-- // Encryption Key Info (Caption)- lblEncryptionKeyInfo := TLabel.Create(WizardForm);- lblEncryptionKeyInfo.Parent := SensitivePage.Surface;- lblEncryptionKeyInfo.Caption := 'Used to encrypt all your backups. Do not lose this!';- lblEncryptionKeyInfo.Font.Color := clGray;- lblEncryptionKeyInfo.Left := 0;- lblEncryptionKeyInfo.Top := txtEncryptionKey.Top + txtEncryptionKey.Height + 6;- lblEncryptionKeyInfo.Width := SensitivePage.SurfaceWidth;- lblEncryptionKeyInfo.WordWrap := True;-- // Admin Username Label- lblUserName := TLabel.Create(WizardForm);- lblUserName.Parent := SensitivePage.Surface;- lblUserName.Caption := 'Admin Username:';- lblUserName.Left := 0;- lblUserName.Top := lblEncryptionKeyInfo.Top + lblEncryptionKeyInfo.Height + 16;-- // Admin Username Input- txtUserName := TNewEdit.Create(WizardForm);- txtUserName.Parent := SensitivePage.Surface;- txtUserName.Left := 0;- txtUserName.Top := lblUserName.Top + lblUserName.Height + 6;- txtUserName.Width := SensitivePage.SurfaceWidth;- txtUserName.Text := 'admin'; // Default value-- // Admin Password Label- lblUserPassword := TLabel.Create(WizardForm);- lblUserPassword.Parent := SensitivePage.Surface;- lblUserPassword.Caption := 'Admin Password:';- lblUserPassword.Left := 0;- lblUserPassword.Top := txtUserName.Top + txtUserName.Height + 16;-- // Admin Password Input- txtUserPassword := TPasswordEdit.Create(WizardForm);- txtUserPassword.Parent := SensitivePage.Surface;- txtUserPassword.Left := 0;- txtUserPassword.Top := lblUserPassword.Top + lblUserPassword.Height + 6;- txtUserPassword.Width := SensitivePage.SurfaceWidth;-- // --- 2. General Settings Page ---- SettingsPage := CreateInputQueryPage(SensitivePage.ID,+ // --- 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.+ SettingsPage := CreateInputQueryPage(wpLicense,'General Settings', 'Configure the application defaults.',- 'You can change these settings later in the config file.');+ 'You can change these settings later in the config file.' + #13#10 + #13#10 ++ 'NOTE: Security credentials will be configured via the web interface after installation.');SettingsPage.Add('Server Port:', False);SettingsPage.Add('Max Concurrent Backups:', False);@@ -203,44 +136,9 @@ beginend;function NextButtonClick(CurPageID: Integer): Boolean;-var- I: Integer;beginResult := True;- // Validate Sensitive Page- if CurPageID = SensitivePage.ID then- begin- // Check ENCRYPTION_KEY length- if Length(txtEncryptionKey.Text) < 12 then- begin- MsgBox('Encryption Key must be at least 12 characters long.', mbError, MB_OK);- Result := False;- Exit;- end;-- // Check User Name- if Length(txtUserName.Text) = 0 then- begin- MsgBox('Admin Username cannot be empty.', mbError, MB_OK);- Result := False;- Exit;- end;-- // Check User Password- if Length(txtUserPassword.Text) = 0 then- begin- MsgBox('Admin Password cannot be empty.', mbError, MB_OK);- Result := False;- Exit;- end;-- // Store values- EncryptionKey := txtEncryptionKey.Text;- UserName := txtUserName.Text;- UserPassword := txtUserPassword.Text;- end;-// Validate Settings Pageif CurPageID = SettingsPage.ID thenbegin@@ -250,22 +148,6 @@ beginend;end;-// Getter functions for Registry section-function GetEncryptionKey(Param: String): String;-begin- Result := EncryptionKey;-end;--function GetUserName(Param: String): String;-begin- Result := UserName;-end;--function GetUserPassword(Param: String): String;-begin- Result := UserPassword;-end;-procedure CurStepChanged(CurStep: TSetupStep);varConfigPath: String;@@ -296,7 +178,9 @@ beginbeginWizardForm.FinishedLabel.Caption := 'Setup has finished installing Pluton on your computer.' + #13#10 + #13#10 +'The service has been started successfully.' + #13#10 + #13#10 +- 'You can access the application at: http://localhost:' + ServerPort + #13#10 + #13#10 ++ 'IMPORTANT: Complete the initial setup by visiting:' + #13#10 ++ 'http://localhost:' + ServerPort + #13#10 + #13#10 ++ 'You will need to configure your encryption key and admin credentials.' + #13#10 + #13#10 +'Please click Finish to exit Setup.';// Optional: Open browserdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 54a420c..089e979 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -38,6 +38,9 @@ importers:backend:dependencies:+ '@napi-rs/keyring':+ specifier: ^1.2.0+ version: 1.2.0aedes:specifier: ^0.51.3version: 0.51.3@@ -1678,6 +1681,82 @@ packages:peerDependencies:jsep: ^0.4.0||^1.0.0+ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-CA83rDeyONDADO25JLZsh3eHY8yTEtm/RS6ecPsY+1v+dSawzT9GywBMu2r6uOp1IEhQs/xAfxgybGAFr17lSA==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [darwin]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-dBHjtKRCj4ByfnfqIKIJLo3wueQNJhLRyuxtX/rR4K/XtcS7VLlRD01XXizjpre54vpmObj63w+ZpHG+mGM8uA==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [darwin]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-DPZFr11pNJSnaoh0dzSUNF+T6ORhy3CkzUT3uGixbA71cAOPJ24iG8e8QrLOkuC/StWrAku3gBnth2XMWOcR3Q==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [freebsd]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-8xv6DyEMlvRdqJzp4F39RLUmmTQsLcGYYv/3eIfZNZN1O5257tHxTrFYqAsny659rJJK2EKeSa7PhrSibQqRWQ==}+ engines: {node: '>= 10'}+ cpu: [arm]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-Pu2V6Py+PBt7inryEecirl+t+ti8bhZphjP+W68iVaXHUxLdWmkgL9KI1VkbRHbx5k8K5Tew9OP218YfmVguIA==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-8TDymrpC4P1a9iDEaegT7RnrkmrJN5eNZh3Im3UEV5PPYGtrb82CRxsuFohthCWQW81O483u1bu+25+XA4nKUw==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-awsB5XI1MYL7fwfjMDGmKOWvNgJEO7mM7iVEMS0fO39f0kVJnOSjlu7RHcXAF0LOx+0VfF3oxbWqJmZbvRCRHw==}+ engines: {node: '>= 10'}+ cpu: [riscv64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-8E+7z4tbxSJXxIBqA+vfB1CGajpCDRyTyqXkBig5NtASrv4YXcntSo96Iah2QDR5zD3dSTsmbqJudcj9rKKuHQ==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-8RZ8yVEnmWr/3BxKgBSzmgntI7lNEsY7xouNfOsQkuVAiCNmxzJwETspzK3PQ2FHtDxgz5vHQDEBVGMyM4hUHA==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-AoqaDZpQ6KPE19VBLpxyORcp+yWmHI9Xs9Oo0PJ4mfHma4nFSLVdhAubJCxdlNptHe5va7ghGCHj3L9Akiv4cQ==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-EYL+EEI6bCsYi3LfwcQdnX3P/R76ENKNn+3PmpGheBsUFLuh0gQuP7aMVHM4rTw6UVe+L3vCLZSptq/oeacz0A==}+ engines: {node: '>= 10'}+ cpu: [ia32]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-xFlx/TsmqmCwNU9v+AVnEJgoEAlBYgzFF5Ihz1rMpPAt4qQWWkMd4sCyM1gMJ1A/GnRqRegDiQpwaxGUHFtFbA==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-d0d4Oyxm+v980PEq1ZH2PmS6cvpMIRc17eYpiU47KgW+lzxklMu6+HOEOPmxrpnF/XQZ0+Q78I2mgMhbIIo/dg==}+ engines: {node: '>= 10'}+'@napi-rs/[email protected]':resolution: {integrity: sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==}@@ -8210,6 +8289,57 @@ snapshots:dependencies:jsep: 1.4.0+ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optionalDependencies:+ '@napi-rs/keyring-darwin-arm64': 1.2.0+ '@napi-rs/keyring-darwin-x64': 1.2.0+ '@napi-rs/keyring-freebsd-x64': 1.2.0+ '@napi-rs/keyring-linux-arm-gnueabihf': 1.2.0+ '@napi-rs/keyring-linux-arm64-gnu': 1.2.0+ '@napi-rs/keyring-linux-arm64-musl': 1.2.0+ '@napi-rs/keyring-linux-riscv64-gnu': 1.2.0+ '@napi-rs/keyring-linux-x64-gnu': 1.2.0+ '@napi-rs/keyring-linux-x64-musl': 1.2.0+ '@napi-rs/keyring-win32-arm64-msvc': 1.2.0+ '@napi-rs/keyring-win32-ia32-msvc': 1.2.0+ '@napi-rs/keyring-win32-x64-msvc': 1.2.0+'@napi-rs/[email protected]':dependencies:'@emnapi/core': 1.6.0diff --git a/scripts/build-executables.js b/scripts/build-executables.jsindex 27cb48f..00d0ccc 100644--- a/scripts/build-executables.js+++ b/scripts/build-executables.js@@ -24,6 +24,7 @@ console.log("╚═════════════════════const BETTER_SQLITE3_VERSION = "12.4.4"; // Latest: Check https://github.com/WiseLibs/better-sqlite3/releasesconst RESTIC_VERSION = "0.18.1"; // Latest: Check https://github.com/restic/restic/releasesconst RCLONE_VERSION = "1.71.2"; // Latest: Check https://rclone.org/downloads/+const KEYRING_VERSION = "1.2.0"; // Latest: Check https://www.npmjs.com/package/@napi-rs/keyring// Target configurationsconst targets = {@@ -35,6 +36,8 @@ const targets = {betterSqlite3Url: `https://github.com/WiseLibs/better-sqlite3/releases/download/v${BETTER_SQLITE3_VERSION}/better-sqlite3-v${BETTER_SQLITE3_VERSION}-node-v137-win32-x64.tar.gz`,resticUrl: `https://github.com/restic/restic/releases/download/v${RESTIC_VERSION}/restic_${RESTIC_VERSION}_windows_amd64.zip`,rcloneUrl: `https://downloads.rclone.org/v${RCLONE_VERSION}/rclone-v${RCLONE_VERSION}-windows-amd64.zip`,+ keyringPackage: `@napi-rs/keyring-win32-x64-msvc`,+ keyringNodeFile: `keyring.win32-x64-msvc.node`,},"linux-x64": {pkgTarget: "node24-linux-x64",@@ -44,6 +47,8 @@ const targets = {betterSqlite3Url: `https://github.com/WiseLibs/better-sqlite3/releases/download/v${BETTER_SQLITE3_VERSION}/better-sqlite3-v${BETTER_SQLITE3_VERSION}-node-v137-linux-x64.tar.gz`,resticUrl: `https://github.com/restic/restic/releases/download/v${RESTIC_VERSION}/restic_${RESTIC_VERSION}_linux_amd64.bz2`,rcloneUrl: `https://downloads.rclone.org/v${RCLONE_VERSION}/rclone-v${RCLONE_VERSION}-linux-amd64.zip`,+ keyringPackage: `@napi-rs/keyring-linux-x64-gnu`,+ keyringNodeFile: `keyring.linux-x64-gnu.node`,},"linux-arm64": {pkgTarget: "node24-linux-arm64",@@ -53,6 +58,8 @@ const targets = {betterSqlite3Url: `https://github.com/WiseLibs/better-sqlite3/releases/download/v${BETTER_SQLITE3_VERSION}/better-sqlite3-v${BETTER_SQLITE3_VERSION}-node-v137-linux-arm64.tar.gz`,resticUrl: `https://github.com/restic/restic/releases/download/v${RESTIC_VERSION}/restic_${RESTIC_VERSION}_linux_arm64.bz2`,rcloneUrl: `https://downloads.rclone.org/v${RCLONE_VERSION}/rclone-v${RCLONE_VERSION}-linux-arm64.zip`,+ keyringPackage: `@napi-rs/keyring-linux-arm64-gnu`,+ keyringNodeFile: `keyring.linux-arm64-gnu.node`,},"macos-x64": {pkgTarget: "node24-macos-x64",@@ -62,6 +69,8 @@ const targets = {betterSqlite3Url: `https://github.com/WiseLibs/better-sqlite3/releases/download/v${BETTER_SQLITE3_VERSION}/better-sqlite3-v${BETTER_SQLITE3_VERSION}-node-v137-darwin-x64.tar.gz`,resticUrl: `https://github.com/restic/restic/releases/download/v${RESTIC_VERSION}/restic_${RESTIC_VERSION}_darwin_amd64.bz2`,rcloneUrl: `https://downloads.rclone.org/v${RCLONE_VERSION}/rclone-v${RCLONE_VERSION}-osx-amd64.zip`,+ keyringPackage: `@napi-rs/keyring-darwin-x64`,+ keyringNodeFile: `keyring.darwin-x64.node`,},"macos-arm64": {pkgTarget: "node24-macos-arm64",@@ -71,6 +80,8 @@ const targets = {betterSqlite3Url: `https://github.com/WiseLibs/better-sqlite3/releases/download/v${BETTER_SQLITE3_VERSION}/better-sqlite3-v${BETTER_SQLITE3_VERSION}-node-v137-darwin-arm64.tar.gz`,resticUrl: `https://github.com/restic/restic/releases/download/v${RESTIC_VERSION}/restic_${RESTIC_VERSION}_darwin_arm64.bz2`,rcloneUrl: `https://downloads.rclone.org/v${RCLONE_VERSION}/rclone-v${RCLONE_VERSION}-osx-arm64.zip`,+ keyringPackage: `@napi-rs/keyring-darwin-arm64`,+ keyringNodeFile: `keyring.darwin-arm64.node`,},};@@ -215,7 +226,10 @@ async function compileBackend() {console.log("📦 Step 4: Compiling TypeScript Backend");console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");- exec("pnpm run build:pkg", { cwd: backendDir });+ exec("pnpm run build:pkg", {+ cwd: backendDir,+ env: { USE_LOCAL_CORE: process.env.USE_LOCAL_CORE }, // USE_LOCAL_CORE for build:pkg script (for PRO local development)+ });console.log("✅ Backend compiled successfully");}@@ -317,6 +331,111 @@ async function setupBetterSqlite3() {console.log("\n✅ better-sqlite3 binaries setup completed");}+/**+ * Step 5b: Download and Setup @napi-rs/keyring Native Binaries+ */+async function setupKeyring() {+ console.log("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");+ console.log("📦 Step 5b: Setting up @napi-rs/keyring Native Binaries");+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");++ const pkgAssetsDir = join(rootDir, "dist", "pkg-assets");+ await mkdir(pkgAssetsDir, { recursive: true });++ // Check if all keyring binaries already exist (caching)+ let allKeyringBinariesExist = true;+ for (const [platform, config] of Object.entries(targets)) {+ const keyringNodePath = join(+ pkgAssetsDir,+ platform,+ "keyring",+ config.keyringNodeFile+ );+ if (!(await fileExists(keyringNodePath))) {+ allKeyringBinariesExist = false;+ break;+ }+ }++ if (allKeyringBinariesExist) {+ console.log("✅ All keyring binaries already exist, skipping download\n");+ console.log(+ "💡 To force re-download, delete the dist/pkg-assets/*/keyring folders"+ );+ return;+ }++ for (const [platform, config] of Object.entries(targets)) {+ console.log(`\n🔧 Setting up @napi-rs/keyring for ${platform}...`);++ const keyringDir = join(pkgAssetsDir, platform, "keyring");+ const keyringNodePath = join(keyringDir, config.keyringNodeFile);++ // Skip if already exists (individual platform caching)+ if (await fileExists(keyringNodePath)) {+ console.log(+ ` ✓ keyring already exists for ${platform}, skipping download`+ );+ continue;+ }++ await mkdir(keyringDir, { recursive: true });++ try {+ // Use npm pack to download the platform-specific package+ const tempDir = join(pkgAssetsDir, `keyring-temp-${platform}`);+ await mkdir(tempDir, { recursive: true });++ // Download and extract the npm package+ console.log(+ ` ⬇️ Downloading ${config.keyringPackage}@${KEYRING_VERSION}...`+ );+ execSync(`npm pack ${config.keyringPackage}@${KEYRING_VERSION}`, {+ cwd: tempDir,+ stdio: "pipe",+ });++ // Find the downloaded tarball+ const files = await readdir(tempDir);+ const tarball = files.find((f) => f.endsWith(".tgz"));++ if (!tarball) {+ throw new Error("Could not find downloaded tarball");+ }++ // Extract the tarball+ const tarballPath = join(tempDir, tarball);+ const isWindows = os.platform() === "win32";+ const tarCommand = isWindows+ ? `tar -xzf "${tarballPath}" -C "${tempDir}"`+ : `tar -xzf ${tarballPath} -C ${tempDir}`;++ execSync(tarCommand, { stdio: "pipe" });++ // Find and copy the .node file+ const packageDir = join(tempDir, "package");+ const nodeFile = join(packageDir, config.keyringNodeFile);++ if (await fileExists(nodeFile)) {+ await copyFile(nodeFile, keyringNodePath);+ console.log(` ✅ keyring binary ready for ${platform}`);+ } else {+ throw new Error(`Could not find ${config.keyringNodeFile} in package`);+ }++ // Clean up temp directory+ await rm(tempDir, { recursive: true, force: true });+ } catch (error) {+ console.warn(+ ` ⚠️ Failed to download keyring for ${platform}: ${error.message}`+ );+ console.warn(` Keyring functionality may not work on this platform`);+ }+ }++ console.log("\n✅ @napi-rs/keyring binaries setup completed");+}+/*** Step 6: Download Platform-Specific Binaries (restic/rclone)*/@@ -649,6 +768,28 @@ async function createDistributionPackages() {console.log(` ✓ Copied better-sqlite3 native module`);}+ // Copy @napi-rs/keyring native module+ const keyringAssetsDir = join(pkgAssetsDir, platform, "keyring");+ const keyringSourceFile = join(keyringAssetsDir, config.keyringNodeFile);+ if (await fileExists(keyringSourceFile)) {+ // The path structure @napi-rs/keyring expects is:+ // node_modules/@napi-rs/keyring-<platform>/keyring.<platform>.node+ const keyringDestDir = join(+ packageDir,+ "node_modules",+ "@napi-rs",+ config.keyringPackage.replace("@napi-rs/", "")+ );+ await mkdir(keyringDestDir, { recursive: true });++ const keyringDestFile = join(keyringDestDir, config.keyringNodeFile);+ await copyFile(keyringSourceFile, keyringDestFile);++ console.log(` ✓ Copied @napi-rs/keyring native module`);+ } else {+ console.warn(` ⚠️ keyring native module not found for ${platform}`);+ }+// Copy binaries if they existconst sourceBinariesDir = join(binariesDir, config.binaryPlatform);if (await fileExists(sourceBinariesDir)) {@@ -715,6 +856,7 @@ async function main() {await installBackendDeps();await compileBackend();await setupBetterSqlite3();+ await setupKeyring();await downloadBinaries();await generateExecutables();await createDistributionPackages();