diff --git a/packages/sdk/electron/__tests__/index.test.ts b/packages/sdk/electron/__tests__/index.test.ts index 1c44f47153..3daba42e0a 100644 --- a/packages/sdk/electron/__tests__/index.test.ts +++ b/packages/sdk/electron/__tests__/index.test.ts @@ -1,3 +1,13 @@ -it('can run tests', () => { - expect(true).toBe(true); +import type { LDElectronStorage } from '../src'; + +it('exports the LDElectronStorage type for custom storage implementations', () => { + const storage: LDElectronStorage = { + get: async () => null, + set: async () => undefined, + clear: async () => undefined, + }; + + expect(typeof storage.get).toBe('function'); + expect(typeof storage.set).toBe('function'); + expect(typeof storage.clear).toBe('function'); }); diff --git a/packages/sdk/electron/__tests__/options.test.ts b/packages/sdk/electron/__tests__/options.test.ts index a87996f997..148ebcb496 100644 --- a/packages/sdk/electron/__tests__/options.test.ts +++ b/packages/sdk/electron/__tests__/options.test.ts @@ -141,3 +141,86 @@ it('filters to base options', () => { expect(logger.warn).not.toHaveBeenCalled(); expect(logger.error).not.toHaveBeenCalled(); }); + +it('applies a custom storage implementation with get, set and clear functions', () => { + const logger = createMockLogger(); + const storage = { get: jest.fn(), set: jest.fn(), clear: jest.fn() }; + + const opts = validateOptions({ storage }, logger); + + expect(opts.storage).toBe(storage); + expect(logger.warn).not.toHaveBeenCalled(); +}); + +it('leaves storage undefined by default', () => { + const logger = createMockLogger(); + const opts = validateOptions({}, logger); + + expect(opts.storage).toBeUndefined(); +}); + +it('warns and falls back to the default storage when storage is not an object', () => { + const logger = createMockLogger(); + + // @ts-ignore + const opts = validateOptions({ storage: 'disk' }, logger); + + expect(opts.storage).toBeUndefined(); + expect(logger.warn).toHaveBeenCalledWith( + 'Config option "storage" should be of type LDElectronStorage ({ get, set, clear }), got string, using default value', + ); +}); + +it('warns and falls back to the default storage when storage lacks the required functions', () => { + const logger = createMockLogger(); + + // @ts-ignore + const opts = validateOptions({ storage: { get: jest.fn() } }, logger); + + expect(opts.storage).toBeUndefined(); + expect(logger.warn).toHaveBeenCalledWith( + 'Config option "storage" should be of type LDElectronStorage ({ get, set, clear }), got object, using default value', + ); +}); + +it('applies encryptStorage when set', () => { + const logger = createMockLogger(); + const opts = validateOptions({ encryptStorage: true }, logger); + + expect(opts.encryptStorage).toBe(true); + expect(logger.warn).not.toHaveBeenCalled(); +}); + +it('defaults encryptStorage to false', () => { + const logger = createMockLogger(); + const opts = validateOptions({}, logger); + + expect(opts.encryptStorage).toBe(false); +}); + +it('warns for invalid encryptStorage type', () => { + const logger = createMockLogger(); + + validateOptions( + { + // @ts-ignore + encryptStorage: 'yes', + }, + logger, + ); + + expect(logger.warn).toHaveBeenCalledWith( + 'Config option "encryptStorage" should be of type boolean, got string, using default value', + ); +}); + +it('warns that encryptStorage has no effect when a custom storage is provided', () => { + const logger = createMockLogger(); + const storage = { get: jest.fn(), set: jest.fn(), clear: jest.fn() }; + + const opts = validateOptions({ storage, encryptStorage: true }, logger); + + expect(opts.storage).toBe(storage); + expect(logger.warn).toHaveBeenCalledTimes(1); + expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('encryptStorage')); +}); diff --git a/packages/sdk/electron/__tests__/platform/ElectronInfo.test.ts b/packages/sdk/electron/__tests__/platform/ElectronInfo.test.ts index 873d520919..021ea7f52e 100644 --- a/packages/sdk/electron/__tests__/platform/ElectronInfo.test.ts +++ b/packages/sdk/electron/__tests__/platform/ElectronInfo.test.ts @@ -88,3 +88,21 @@ describe('given an information instance with mock data', () => { expect(data.os?.name).toEqual(processed); }); }); + +describe('given a wrapper name and version', () => { + it('includes them in sdkData', () => { + const info = new ElectronInfo({ wrapperName: 'my-wrapper', wrapperVersion: '1.2.3' }); + + const sdkInfo = info.sdkData(); + expect(sdkInfo.wrapperName).toEqual('my-wrapper'); + expect(sdkInfo.wrapperVersion).toEqual('1.2.3'); + }); + + it('omits them from sdkData when not provided', () => { + const info = new ElectronInfo(); + + const sdkInfo = info.sdkData(); + expect(sdkInfo.wrapperName).toBeUndefined(); + expect(sdkInfo.wrapperVersion).toBeUndefined(); + }); +}); diff --git a/packages/sdk/electron/__tests__/platform/ElectronPlatform.test.ts b/packages/sdk/electron/__tests__/platform/ElectronPlatform.test.ts index 288da954b7..c9be0ac713 100644 --- a/packages/sdk/electron/__tests__/platform/ElectronPlatform.test.ts +++ b/packages/sdk/electron/__tests__/platform/ElectronPlatform.test.ts @@ -1,16 +1,17 @@ import type { LDLogger } from '@launchdarkly/js-client-sdk-common'; +import ElectronInfo from '../../src/platform/ElectronInfo'; import ElectronPlatform from '../../src/platform/ElectronPlatform'; +import ElectronRequests from '../../src/platform/ElectronRequests'; +import { getElectronStorage } from '../../src/platform/ElectronStorage'; -const failingStorage = { - get: jest.fn().mockRejectedValue(new Error('disk read failed')), - set: jest.fn().mockRejectedValue(new Error('disk write failed')), - clear: jest.fn().mockRejectedValue(new Error('disk clear failed')), -}; +const storageInstance = { get: jest.fn(), set: jest.fn(), clear: jest.fn() }; jest.mock('../../src/platform/ElectronStorage', () => ({ - getElectronStorage: () => failingStorage, + getElectronStorage: jest.fn(() => storageInstance), })); +jest.mock('../../src/platform/ElectronInfo'); +jest.mock('../../src/platform/ElectronRequests'); const logger: LDLogger = { debug: jest.fn(), @@ -19,34 +20,108 @@ const logger: LDLogger = { error: jest.fn(), }; -let platform: ElectronPlatform; - beforeEach(() => { jest.clearAllMocks(); - platform = new ElectronPlatform(logger, {}); }); -it('logs error and returns null when storage get fails', async () => { - const result = await platform.storage!.get('some-key'); +it('uses the shared ElectronStorage singleton without encryption by default', () => { + const platform = new ElectronPlatform(logger, {}); - expect(result).toBeNull(); - expect(logger.error).toHaveBeenCalledWith( - expect.stringContaining('Error getting key from storage: some-key'), - ); + expect(getElectronStorage).toHaveBeenCalledWith(logger, { encrypt: false }); + expect(platform.storage).toBe(storageInstance); }); -it('logs error and swallows when storage set fails', async () => { - await platform.storage!.set('some-key', 'some-value'); +it('requests an encrypted shared cache when encryptStorage is true', () => { + // eslint-disable-next-line no-new + new ElectronPlatform(logger, { encryptStorage: true }); - expect(logger.error).toHaveBeenCalledWith( - expect.stringContaining('Error setting key in storage: some-key'), - ); + expect(getElectronStorage).toHaveBeenCalledWith(logger, { encrypt: true }); +}); + +it('ignores encryptStorage when a custom storage is provided', async () => { + const customStorage = { + get: jest.fn().mockResolvedValue(null), + set: jest.fn().mockResolvedValue(undefined), + clear: jest.fn().mockResolvedValue(undefined), + }; + + const platform = new ElectronPlatform(logger, { storage: customStorage, encryptStorage: true }); + await platform.storage.set('k', 'v'); + + expect(customStorage.set).toHaveBeenCalledWith('k', 'v'); + expect(getElectronStorage).not.toHaveBeenCalled(); +}); + +it('threads wrapperName/wrapperVersion into ElectronInfo', () => { + // eslint-disable-next-line no-new + new ElectronPlatform(logger, { wrapperName: 'my-wrapper', wrapperVersion: '1.2.3' }); + + expect(ElectronInfo).toHaveBeenCalledWith({ + wrapperName: 'my-wrapper', + wrapperVersion: '1.2.3', + }); +}); + +it('constructs ElectronRequests with enableEventCompression', () => { + // eslint-disable-next-line no-new + new ElectronPlatform(logger, { + enableEventCompression: true, + }); + + expect(ElectronRequests).toHaveBeenCalledWith(true); }); -it('logs error and swallows when storage clear fails', async () => { - await platform.storage!.clear('some-key'); +it('uses the custom storage and never creates the built-in storage when storage is provided', async () => { + const customStorage = { + get: jest.fn().mockResolvedValue('custom-value'), + set: jest.fn().mockResolvedValue(undefined), + clear: jest.fn().mockResolvedValue(undefined), + }; + + const platform = new ElectronPlatform(logger, { storage: customStorage }); + + await expect(platform.storage.get('test-key')).resolves.toBe('custom-value'); + await platform.storage.set('test-key', 'val'); + await platform.storage.clear('test-key'); + + expect(customStorage.get).toHaveBeenCalledWith('test-key'); + expect(customStorage.set).toHaveBeenCalledWith('test-key', 'val'); + expect(customStorage.clear).toHaveBeenCalledWith('test-key'); + expect(getElectronStorage).not.toHaveBeenCalled(); +}); + +it('logs errors from the custom storage and keeps running', async () => { + const failingStorage = { + get: jest.fn().mockRejectedValue(new Error('custom get failed')), + set: jest.fn().mockRejectedValue(new Error('custom set failed')), + clear: jest.fn().mockRejectedValue(new Error('custom clear failed')), + }; + + const platform = new ElectronPlatform(logger, { storage: failingStorage }); + + await expect(platform.storage.get('key')).resolves.toBeNull(); + await expect(platform.storage.set('key', 'val')).resolves.toBeUndefined(); + await expect(platform.storage.clear('key')).resolves.toBeUndefined(); expect(logger.error).toHaveBeenCalledWith( - expect.stringContaining('Error clearing key from storage: some-key'), + expect.stringContaining('Error getting key from storage: key'), ); + expect(logger.error).toHaveBeenCalledWith( + expect.stringContaining('Error setting key in storage: key'), + ); + expect(logger.error).toHaveBeenCalledWith( + expect.stringContaining('Error clearing key from storage: key'), + ); +}); + +it('returns null when the custom storage resolves a non-string value', async () => { + const oddStorage = { + get: jest.fn().mockResolvedValue(42), + set: jest.fn().mockResolvedValue(undefined), + clear: jest.fn().mockResolvedValue(undefined), + }; + + const platform = new ElectronPlatform(logger, { storage: oddStorage }); + + await expect(platform.storage.get('key')).resolves.toBeNull(); }); diff --git a/packages/sdk/electron/__tests__/platform/ElectronStorage.encrypted.test.ts b/packages/sdk/electron/__tests__/platform/ElectronStorage.encrypted.test.ts new file mode 100644 index 0000000000..375a24e439 --- /dev/null +++ b/packages/sdk/electron/__tests__/platform/ElectronStorage.encrypted.test.ts @@ -0,0 +1,279 @@ +import { safeStorage } from 'electron'; +import * as fs from 'fs/promises'; +import * as os from 'os'; +import * as path from 'path'; + +import ElectronStorage, { + getElectronStorage, + resetElectronStorage, +} from '../../src/platform/ElectronStorage'; +import { createMockLogger } from '../testHelpers'; + +let tmpRoot: string; +let userDataPath: string; +let cacheDir: string; + +const mockState = { + appReady: true, + encryptionAvailable: true, + storageBackend: 'gnome_libsecret', +}; +const originalPlatform = process.platform; + +function setPlatform(platform: NodeJS.Platform) { + Object.defineProperty(process, 'platform', { value: platform }); +} +const mockWhenReady = jest.fn(() => Promise.resolve()); + +// A reversible stand-in for safeStorage. It adds a marker prefix and reverses the UTF-8 bytes. +// That is enough to show that the file on disk is not the plain JSON and that reads go through +// decryptString. +jest.mock('electron', () => ({ + app: { + getPath: jest.fn(() => userDataPath), + isReady: jest.fn(() => mockState.appReady), + whenReady: () => mockWhenReady(), + }, + safeStorage: { + isEncryptionAvailable: jest.fn(() => mockState.encryptionAvailable), + getSelectedStorageBackend: jest.fn(() => mockState.storageBackend), + encryptString: jest.fn((plainText: string) => + Buffer.concat([Buffer.from('ENC:'), Buffer.from(plainText, 'utf8').reverse()]), + ), + decryptString: jest.fn((encrypted: Buffer) => { + if (!encrypted.subarray(0, 4).equals(Buffer.from('ENC:'))) { + throw new Error('Decryption failed'); + } + return Buffer.from(encrypted.subarray(4)).reverse().toString('utf8'); + }), + }, +})); + +beforeEach(async () => { + tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'electron-storage-enc-test-')); + userDataPath = tmpRoot; + cacheDir = path.join(tmpRoot, 'ldclient-user-cache'); + mockState.appReady = true; + mockState.encryptionAvailable = true; + mockState.storageBackend = 'gnome_libsecret'; + mockWhenReady.mockClear(); + (safeStorage.isEncryptionAvailable as jest.Mock).mockClear(); +}); + +afterEach(async () => { + setPlatform(originalPlatform); + resetElectronStorage(); + await fs.rm(tmpRoot, { recursive: true, force: true }); +}); + +it('writes an encrypted cache file and no plain-text file', async () => { + const storage = new ElectronStorage(createMockLogger(), { encrypt: true }); + await storage.set('alpha', 'one'); + + const onDisk = await fs.readFile(path.join(cacheDir, 'ldcache.enc')); + expect(onDisk.subarray(0, 4).toString()).toBe('ENC:'); + expect(onDisk.toString('utf8')).not.toContain('"alpha"'); + await expect(fs.access(path.join(cacheDir, 'ldcache'))).rejects.toMatchObject({ + code: 'ENOENT', + }); +}); + +it('loads values from the encrypted cache file on construction', async () => { + const first = new ElectronStorage(createMockLogger(), { encrypt: true }); + await first.set('alpha', 'one'); + + const second = new ElectronStorage(createMockLogger(), { encrypt: true }); + await expect(second.get('alpha')).resolves.toBe('one'); +}); + +it('deletes an existing plain-text cache and does not load its values', async () => { + await fs.mkdir(cacheDir, { recursive: true }); + await fs.writeFile(path.join(cacheDir, 'ldcache'), JSON.stringify({ secret: 'plain' }), 'utf8'); + + const storage = new ElectronStorage(createMockLogger(), { encrypt: true }); + + await expect(storage.get('secret')).resolves.toBeNull(); + await expect(fs.access(path.join(cacheDir, 'ldcache'))).rejects.toMatchObject({ + code: 'ENOENT', + }); +}); + +it('keeps flags in memory only and writes no file when encryption is unavailable', async () => { + mockState.encryptionAvailable = false; + const logger = createMockLogger(); + const storage = new ElectronStorage(logger, { encrypt: true }); + + await storage.set('alpha', 'one'); + await expect(storage.get('alpha')).resolves.toBe('one'); + + expect(logger.warn).toHaveBeenCalledTimes(1); + expect(logger.warn).toHaveBeenCalledWith( + expect.stringContaining('safeStorage encryption is not available'), + ); + expect(logger.error).not.toHaveBeenCalled(); + await expect(fs.readdir(cacheDir)).resolves.toEqual([]); +}); + +it('keeps flags in memory only when Linux safeStorage uses the basic_text backend', async () => { + setPlatform('linux'); + mockState.storageBackend = 'basic_text'; + const logger = createMockLogger(); + const storage = new ElectronStorage(logger, { encrypt: true }); + + await storage.set('alpha', 'one'); + await expect(storage.get('alpha')).resolves.toBe('one'); + + expect(logger.warn).toHaveBeenCalledTimes(1); + expect(logger.warn).toHaveBeenCalledWith( + expect.stringContaining('safeStorage uses the Linux basic_text backend'), + ); + await expect(fs.readdir(cacheDir)).resolves.toEqual([]); +}); + +it('uses the encrypted cache on Linux with a real secret store', async () => { + setPlatform('linux'); + const logger = createMockLogger(); + const storage = new ElectronStorage(logger, { encrypt: true }); + + await storage.set('alpha', 'one'); + + expect(logger.warn).not.toHaveBeenCalled(); + await expect(fs.readdir(cacheDir)).resolves.toEqual(['ldcache.enc']); +}); + +it('ignores the storage backend on platforms other than Linux', async () => { + setPlatform('darwin'); + mockState.storageBackend = 'basic_text'; + const logger = createMockLogger(); + const storage = new ElectronStorage(logger, { encrypt: true }); + + await storage.set('alpha', 'one'); + + expect(logger.warn).not.toHaveBeenCalled(); + await expect(fs.readdir(cacheDir)).resolves.toEqual(['ldcache.enc']); +}); + +it('deletes the plain-text cache even when encryption is unavailable', async () => { + mockState.encryptionAvailable = false; + await fs.mkdir(cacheDir, { recursive: true }); + await fs.writeFile(path.join(cacheDir, 'ldcache'), JSON.stringify({ secret: 'plain' }), 'utf8'); + + const storage = new ElectronStorage(createMockLogger(), { encrypt: true }); + + await expect(storage.get('secret')).resolves.toBeNull(); + await expect(fs.readdir(cacheDir)).resolves.toEqual([]); +}); + +it('waits for the app ready event before using safeStorage', async () => { + mockState.appReady = false; + let resolveReady: () => void = () => {}; + mockWhenReady.mockReturnValueOnce( + new Promise((resolve) => { + resolveReady = resolve; + }), + ); + const storage = new ElectronStorage(createMockLogger(), { encrypt: true }); + + // Let initialization run as far as it can while the app is not ready. + const pendingSet = storage.set('alpha', 'one'); + await new Promise((resolve) => { + setImmediate(resolve); + }); + expect(safeStorage.isEncryptionAvailable).not.toHaveBeenCalled(); + + resolveReady(); + await pendingSet; + + expect(safeStorage.isEncryptionAvailable).toHaveBeenCalledTimes(1); + await expect(fs.access(path.join(cacheDir, 'ldcache.enc'))).resolves.toBeUndefined(); +}); + +it('waits for the app ready event before it reads the Linux storage backend', async () => { + setPlatform('linux'); + mockState.appReady = false; + (safeStorage.getSelectedStorageBackend as jest.Mock).mockClear(); + let resolveReady: () => void = () => {}; + mockWhenReady.mockReturnValueOnce( + new Promise((resolve) => { + resolveReady = resolve; + }), + ); + const storage = new ElectronStorage(createMockLogger(), { encrypt: true }); + + // Let initialization run as far as it can while the app is not ready. + const pendingSet = storage.set('alpha', 'one'); + await new Promise((resolve) => { + setImmediate(resolve); + }); + expect(safeStorage.getSelectedStorageBackend).not.toHaveBeenCalled(); + + resolveReady(); + await pendingSet; + + expect(safeStorage.getSelectedStorageBackend).toHaveBeenCalledTimes(1); + await expect(fs.access(path.join(cacheDir, 'ldcache.enc'))).resolves.toBeUndefined(); +}); + +it('deletes a plain-text temp file left by an interrupted write', async () => { + await fs.mkdir(cacheDir, { recursive: true }); + await fs.writeFile(path.join(cacheDir, 'ldcache.tmp'), '{"secret":"plain"}', 'utf8'); + + const storage = new ElectronStorage(createMockLogger(), { encrypt: true }); + await storage.get('secret'); + + await expect(fs.access(path.join(cacheDir, 'ldcache.tmp'))).rejects.toMatchObject({ + code: 'ENOENT', + }); +}); + +it('writes no plain-text or temp file when encryption fails at write time', async () => { + const logger = createMockLogger(); + const storage = new ElectronStorage(logger, { encrypt: true }); + await storage.get('alpha'); + (safeStorage.encryptString as jest.Mock).mockImplementationOnce(() => { + throw new Error('Encryption failed'); + }); + + await storage.set('alpha', 'one'); + + expect(logger.error).toHaveBeenCalledTimes(1); + const files = await fs.readdir(cacheDir); + expect(files).not.toContain('ldcache'); + expect(files.filter((f) => f.endsWith('.tmp'))).toEqual([]); +}); + +it('discards an encrypted cache file that cannot be decrypted and keeps working', async () => { + await fs.mkdir(cacheDir, { recursive: true }); + await fs.writeFile(path.join(cacheDir, 'ldcache.enc'), 'not encrypted', 'utf8'); + + const logger = createMockLogger(); + const storage = new ElectronStorage(logger, { encrypt: true }); + + await expect(storage.get('anything')).resolves.toBeNull(); + expect(logger.warn).toHaveBeenCalledWith( + expect.stringContaining('Discarding malformed flag cache'), + ); + + await storage.set('alpha', 'one'); + const second = new ElectronStorage(createMockLogger(), { encrypt: true }); + await expect(second.get('alpha')).resolves.toBe('one'); +}); + +it('keeps writing the plain-text file when encryption is off', async () => { + const storage = new ElectronStorage(createMockLogger(), { encrypt: false }); + await storage.set('alpha', 'one'); + + const onDisk = await fs.readFile(path.join(cacheDir, 'ldcache'), 'utf8'); + expect(JSON.parse(onDisk)).toEqual({ alpha: 'one' }); +}); + +it('returns separate shared instances for plain and encrypted callers without warning', () => { + const logger = createMockLogger(); + + const plain = getElectronStorage(logger, { encrypt: false }); + const encrypted = getElectronStorage(logger, { encrypt: true }); + + expect(encrypted).not.toBe(plain); + expect(getElectronStorage(logger, { encrypt: true })).toBe(encrypted); + expect(logger.warn).not.toHaveBeenCalled(); +}); diff --git a/packages/sdk/electron/__tests__/platform/ElectronStorage.test.ts b/packages/sdk/electron/__tests__/platform/ElectronStorage.test.ts index 8651b1da0f..a68956af70 100644 --- a/packages/sdk/electron/__tests__/platform/ElectronStorage.test.ts +++ b/packages/sdk/electron/__tests__/platform/ElectronStorage.test.ts @@ -1,178 +1,293 @@ import * as fs from 'fs/promises'; +import * as os from 'os'; +import * as path from 'path'; import ElectronStorage, { getElectronStorage, resetElectronStorage, } from '../../src/platform/ElectronStorage'; +import { createMockLogger } from '../testHelpers'; + +let tmpRoot: string; +let userDataPath: string; +let cacheDir: string; -jest.mock('fs/promises'); jest.mock('electron', () => ({ app: { - getPath: jest.fn().mockReturnValue('/user/data'), + getPath: jest.fn(() => userDataPath), }, })); -const storageFile = '/user/data/ldcache'; -const tempFile = `${storageFile}.tmp`; +beforeEach(async () => { + tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'electron-storage-test-')); + userDataPath = tmpRoot; + cacheDir = path.join(tmpRoot, 'ldclient-user-cache'); + resetElectronStorage(); +}); -beforeEach(() => { - jest.clearAllMocks(); +afterEach(async () => { resetElectronStorage(); + await fs.rm(tmpRoot, { recursive: true, force: true }); }); -it('throws on clear when initialization failed', async () => { - (fs.readFile as jest.Mock).mockRejectedValueOnce(new Error('file not found')); - (fs.writeFile as jest.Mock).mockRejectedValueOnce(new Error('write failed')); +it('returns null when a key has never been written', async () => { + const storage = new ElectronStorage(); + await expect(storage.get('missing')).resolves.toBeNull(); +}); +it('round-trips values through set and get', async () => { const storage = new ElectronStorage(); - await expect(storage.clear('key1')).rejects.toThrow('Storage is not initialized: write failed'); + await storage.set('alpha', 'one'); + await expect(storage.get('alpha')).resolves.toBe('one'); }); -it('can clear values', async () => { - (fs.readFile as jest.Mock).mockReturnValueOnce( - JSON.stringify({ key1: 'value1', key2: 'value2' }), - ); +it('overwrites a value when set is called again', async () => { + const storage = new ElectronStorage(); + await storage.set('alpha', 'one'); + await storage.set('alpha', 'two'); + await expect(storage.get('alpha')).resolves.toBe('two'); +}); +it('clears a key so subsequent gets return null', async () => { const storage = new ElectronStorage(); - await storage.clear('key1'); + await storage.set('alpha', 'one'); + await storage.clear('alpha'); + await expect(storage.get('alpha')).resolves.toBeNull(); +}); - expect(await storage.get('key1')).toBeNull(); +it('persists writes atomically to ldcache in an SDK-owned subdirectory of userData', async () => { + const storage = new ElectronStorage(); + await storage.set('alpha', 'one'); - expect(fs.writeFile).toHaveBeenCalledWith( - tempFile, - JSON.stringify({ key2: 'value2' }), - expect.anything(), - ); - expect(fs.rename).toHaveBeenCalledWith(tempFile, storageFile); + const onDisk = await fs.readFile(path.join(cacheDir, 'ldcache'), 'utf8'); + expect(JSON.parse(onDisk)).toEqual({ alpha: 'one' }); }); -it('does nothing when clearing a non-existent key', async () => { - (fs.readFile as jest.Mock).mockReturnValueOnce( - JSON.stringify({ key1: 'value1', key2: 'value2' }), +// Windows does not use POSIX permission bits. +(process.platform === 'win32' ? it.skip : it)( + 'creates the cache directory readable only by the owner', + async () => { + const storage = new ElectronStorage(); + await storage.set('alpha', 'one'); + + // eslint-disable-next-line no-bitwise + expect((await fs.stat(cacheDir)).mode & 0o777).toBe(0o700); + }, +); + +it('loads prior contents from the storage file on construction', async () => { + await fs.mkdir(cacheDir, { recursive: true }); + await fs.writeFile( + path.join(cacheDir, 'ldcache'), + JSON.stringify({ persisted: 'value' }), + 'utf8', ); const storage = new ElectronStorage(); - await storage.clear('key3'); - - expect(fs.writeFile).not.toHaveBeenCalled(); - expect(fs.rename).not.toHaveBeenCalled(); + await expect(storage.get('persisted')).resolves.toBe('value'); }); -it('updates cache even when disk flush fails on clear', async () => { - (fs.readFile as jest.Mock).mockReturnValueOnce( - JSON.stringify({ key1: 'value1', key2: 'value2' }), - ); - (fs.writeFile as jest.Mock).mockRejectedValueOnce(new Error('write failed')); +it('recovers when the storage file contains invalid JSON', async () => { + await fs.mkdir(cacheDir, { recursive: true }); + await fs.writeFile(path.join(cacheDir, 'ldcache'), 'not json', 'utf8'); const storage = new ElectronStorage(); - // The flush error propagates so the per-client wrapper can log it - await expect(storage.clear('key1')).rejects.toThrow('write failed'); - - // Cache is updated synchronously — the in-memory state reflects the clear - // even if the disk write failed. - expect(await storage.get('key1')).toBeNull(); + await expect(storage.get('anything')).resolves.toBeNull(); + await storage.set('alpha', 'one'); + await expect(storage.get('alpha')).resolves.toBe('one'); }); -it('throws on get when initialization failed', async () => { - (fs.readFile as jest.Mock).mockRejectedValueOnce(new Error('file not found')); - (fs.writeFile as jest.Mock).mockRejectedValueOnce(new Error('write failed')); +it('does not warn on first run when the cache file does not exist', async () => { + const logger = createMockLogger(); + const storage = new ElectronStorage(logger); + await expect(storage.get('anything')).resolves.toBeNull(); + expect(logger.warn).not.toHaveBeenCalled(); +}); + +it('does not preemptively write the cache file on first run', async () => { const storage = new ElectronStorage(); - await expect(storage.get('key1')).rejects.toThrow('Storage is not initialized: write failed'); + await expect(storage.get('anything')).resolves.toBeNull(); + + await expect(fs.access(path.join(cacheDir, 'ldcache'))).rejects.toMatchObject({ + code: 'ENOENT', + }); }); -it('can get values', async () => { - (fs.readFile as jest.Mock).mockReturnValueOnce( - JSON.stringify({ key1: 'value1', key2: 'value2' }), - ); +it('warns when the cache file is not valid JSON', async () => { + await fs.mkdir(cacheDir, { recursive: true }); + await fs.writeFile(path.join(cacheDir, 'ldcache'), 'not json', 'utf8'); - const storage = new ElectronStorage(); - const value = await storage.get('key1'); + const logger = createMockLogger(); + const storage = new ElectronStorage(logger); + await expect(storage.get('anything')).resolves.toBeNull(); - expect(value).toEqual('value1'); + expect(logger.warn).toHaveBeenCalledWith( + expect.stringContaining('Discarding malformed flag cache'), + ); }); -it('returns null when getting a non-existent key', async () => { - (fs.readFile as jest.Mock).mockReturnValueOnce( - JSON.stringify({ key1: 'value1', key2: 'value2' }), +it('ignores non-string values when loading the cache', async () => { + await fs.mkdir(cacheDir, { recursive: true }); + await fs.writeFile( + path.join(cacheDir, 'ldcache'), + JSON.stringify({ good: 'keep', obj: { nested: true }, arr: [1, 2], num: 5 }), + 'utf8', ); const storage = new ElectronStorage(); - const value = await storage.get('key3'); - - expect(value).toBeNull(); + await expect(storage.get('good')).resolves.toBe('keep'); + await expect(storage.get('obj')).resolves.toBeNull(); + await expect(storage.get('arr')).resolves.toBeNull(); + await expect(storage.get('num')).resolves.toBeNull(); }); -it('throws on set when initialization failed', async () => { - (fs.readFile as jest.Mock).mockRejectedValueOnce(new Error('file not found')); - (fs.writeFile as jest.Mock).mockRejectedValueOnce(new Error('write failed')); - +it('does not follow a symlink planted at the temp file path', async () => { const storage = new ElectronStorage(); - await expect(storage.set('key3', 'value3')).rejects.toThrow( - 'Storage is not initialized: write failed', - ); + // Ensure initialization (which clears any temp file) has completed before planting. + await storage.get('warmup'); + + const victim = path.join(tmpRoot, 'victim.txt'); + await fs.writeFile(victim, 'protected', 'utf8'); + await fs.symlink(victim, path.join(cacheDir, 'ldcache.tmp')); + + await storage.set('alpha', 'one'); + + // The exclusive open removes the symlink and writes a fresh file, so the victim is untouched. + await expect(fs.readFile(victim, 'utf8')).resolves.toBe('protected'); + await expect(storage.get('alpha')).resolves.toBe('one'); }); -it('can set values', async () => { - (fs.readFile as jest.Mock).mockReturnValueOnce( - JSON.stringify({ key1: 'value1', key2: 'value2' }), +it('falls back to in-memory storage instead of following a symlinked SDK cache directory', async () => { + const victimDir = path.join(tmpRoot, 'victim-dir'); + await fs.mkdir(victimDir); + await fs.symlink(victimDir, cacheDir); + + const logger = createMockLogger(); + const storage = new ElectronStorage(logger); + + await storage.set('alpha', 'one'); + await expect(storage.get('alpha')).resolves.toBe('one'); + expect(logger.error).not.toHaveBeenCalled(); + expect(logger.warn).toHaveBeenCalledWith( + expect.stringContaining('Using in-memory storage as a fallback'), ); - const storage = new ElectronStorage(); - await storage.set('key3', 'value3'); + // The victim directory the symlink pointed at was never written to. + await expect(fs.readdir(victimDir)).resolves.toEqual([]); +}); + +it('discards a symlink planted at the storage file path instead of reading through it', async () => { + await fs.mkdir(cacheDir, { recursive: true }); + const victim = path.join(tmpRoot, 'victim.json'); + await fs.writeFile(victim, JSON.stringify({ secret: 'do-not-load' }), 'utf8'); + await fs.symlink(victim, path.join(cacheDir, 'ldcache')); - expect(await storage.get('key3')).toEqual('value3'); + const logger = createMockLogger(); + const storage = new ElectronStorage(logger); - expect(fs.writeFile).toHaveBeenCalledWith( - tempFile, - JSON.stringify({ key1: 'value1', key2: 'value2', key3: 'value3' }), - expect.anything(), + // The symlinked "cache" is discarded rather than followed, so its contents never load. + await expect(storage.get('secret')).resolves.toBeNull(); + expect(logger.warn).toHaveBeenCalledWith( + expect.stringContaining('Discarding malformed flag cache'), ); - expect(fs.rename).toHaveBeenCalledWith(tempFile, storageFile); + expect(logger.error).not.toHaveBeenCalled(); + + await storage.set('alpha', 'one'); + await expect(storage.get('alpha')).resolves.toBe('one'); + const onDisk = await fs.readFile(path.join(cacheDir, 'ldcache'), 'utf8'); + expect(JSON.parse(onDisk)).toEqual({ alpha: 'one' }); }); -it('can set values with existing keys', async () => { - (fs.readFile as jest.Mock).mockReturnValueOnce( - JSON.stringify({ key1: 'value1', key2: 'value2' }), +it('falls back to in-memory storage and warns once when the cache directory cannot be created', async () => { + // An intermediate path segment that is a file means mkdir cannot traverse through it, so + // this must fall back to in-memory storage rather than throwing out of get/set/clear. + const fileInThePath = path.join(tmpRoot, 'not-a-dir'); + await fs.writeFile(fileInThePath, 'sentinel', 'utf8'); + userDataPath = path.join(fileInThePath, 'subdir'); + + const logger = createMockLogger(); + const storage = new ElectronStorage(logger); + + await expect(storage.get('alpha')).resolves.toBeNull(); + await storage.set('alpha', 'one'); + await expect(storage.get('alpha')).resolves.toBe('one'); + await storage.clear('alpha'); + await expect(storage.get('alpha')).resolves.toBeNull(); + + expect(logger.error).not.toHaveBeenCalled(); + expect(logger.warn).toHaveBeenCalledTimes(1); + expect(logger.warn).toHaveBeenCalledWith( + expect.stringContaining('Using in-memory storage as a fallback'), ); +}); - const storage = new ElectronStorage(); - await storage.set('key1', 'new-value1'); +it('falls back to in-memory storage when a file occupies the cache directory path', async () => { + // No prerelease (v0) installation has customer data to migrate, so a plain file sitting at + // the cache directory path is just treated as a generic, unrecoverable init failure. + await fs.writeFile(cacheDir, 'not a directory', 'utf8'); - expect(await storage.get('key1')).toEqual('new-value1'); + const logger = createMockLogger(); + const storage = new ElectronStorage(logger); - expect(fs.writeFile).toHaveBeenCalledWith( - tempFile, - JSON.stringify({ key1: 'new-value1', key2: 'value2' }), - expect.anything(), + await storage.set('alpha', 'one'); + await expect(storage.get('alpha')).resolves.toBe('one'); + expect(logger.error).not.toHaveBeenCalled(); + expect(logger.warn).toHaveBeenCalledTimes(1); + expect(logger.warn).toHaveBeenCalledWith( + expect.stringContaining('Using in-memory storage as a fallback'), ); - expect(fs.rename).toHaveBeenCalledWith(tempFile, storageFile); + expect((await fs.stat(cacheDir)).isDirectory()).toBe(false); }); -it('updates cache even when disk flush fails on set', async () => { - (fs.readFile as jest.Mock).mockReturnValueOnce( - JSON.stringify({ key1: 'value1', key2: 'value2' }), +it('falls back to in-memory storage when rewriting a discarded malformed cache fails', async () => { + // The cache directory itself is created successfully, but the rewrite that normally follows + // discarding a malformed cache file fails because a directory occupies the temp-file path. + // This exercises the fallback triggering from a site other than cache-directory creation. + await fs.mkdir(cacheDir, { recursive: true }); + await fs.writeFile(path.join(cacheDir, 'ldcache'), 'not json', 'utf8'); + await fs.mkdir(path.join(cacheDir, 'ldcache.tmp')); + + const logger = createMockLogger(); + const storage = new ElectronStorage(logger); + + await expect(storage.get('anything')).resolves.toBeNull(); + expect(logger.warn).toHaveBeenCalledWith( + expect.stringContaining('Discarding malformed flag cache'), + ); + expect(logger.warn).toHaveBeenCalledWith( + expect.stringContaining('Using in-memory storage as a fallback'), ); - (fs.writeFile as jest.Mock).mockRejectedValueOnce(new Error('write failed')); + expect(logger.error).not.toHaveBeenCalled(); - const storage = new ElectronStorage(); - // The flush error propagates so the per-client wrapper can log it - await expect(storage.set('key3', 'value3')).rejects.toThrow('write failed'); + await storage.set('alpha', 'one'); + await expect(storage.get('alpha')).resolves.toBe('one'); - // Cache is updated synchronously — the in-memory state reflects the set - // even if the disk write failed. - expect(await storage.get('key3')).toEqual('value3'); + // Persistence is disabled, so the untouched malformed file on disk proves no flush was attempted. + await expect(fs.readFile(path.join(cacheDir, 'ldcache'), 'utf8')).resolves.toBe('not json'); }); -it('getElectronStorage returns the same instance on subsequent calls', () => { - const a = getElectronStorage(); - const b = getElectronStorage(); - expect(a).toBe(b); +it('returns the same singleton across getElectronStorage calls', () => { + const first = getElectronStorage(); + const second = getElectronStorage(); + expect(second).toBe(first); }); -it('resetElectronStorage causes a fresh instance on next call', () => { - const a = getElectronStorage(); +it('rebuilds the singleton after resetElectronStorage', () => { + const first = getElectronStorage(); resetElectronStorage(); - const b = getElectronStorage(); - expect(a).not.toBe(b); + const second = getElectronStorage(); + expect(second).not.toBe(first); +}); + +it('returns the same instance and does not warn when later callers ask for the same encryption setting', () => { + const logger = createMockLogger(); + const first = getElectronStorage(logger, { encrypt: false }); + + const second = getElectronStorage(logger, { encrypt: false }); + const third = getElectronStorage(logger); + + expect(second).toBe(first); + expect(third).toBe(first); + expect(logger.warn).not.toHaveBeenCalled(); }); diff --git a/packages/sdk/electron/contract-tests/entity/src/ClientEntity.ts b/packages/sdk/electron/contract-tests/entity/src/ClientEntity.ts index 05874ae137..c8e6d266be 100644 --- a/packages/sdk/electron/contract-tests/entity/src/ClientEntity.ts +++ b/packages/sdk/electron/contract-tests/entity/src/ClientEntity.ts @@ -119,12 +119,9 @@ export class ClientEntity { async close() { try { await this._client.close(); - if (fs.existsSync(this._storagePath)) { - fs.rmSync(this._storagePath, { recursive: true }); - } - if (fs.existsSync(`${this._storagePath}.tmp`)) { - fs.rmSync(`${this._storagePath}.tmp`, { recursive: true }); - } + // The SDK cache lives in this directory. A stale cache changes the + // first evaluation of the next test, so remove the whole directory. + fs.rmSync(this._storagePath, { recursive: true, force: true }); // Reset the singleton so the next client gets a fresh storage instance // that reads from disk instead of returning stale in-memory data. resetElectronStorage(); @@ -241,7 +238,7 @@ export async function createEntity(options: CreateInstanceParams) { const clientSideId = options.configuration.credential || 'unknown-env-id'; logger.info(`Creating client with configuration: ${JSON.stringify(options.configuration)}`); - const storagePath = path.join(app.getPath('userData'), 'ldcache'); + const storagePath = path.join(app.getPath('userData'), 'ldclient-user-cache'); const timeoutMs = options.configuration.startWaitTimeMs !== null && diff --git a/packages/sdk/electron/src/ElectronClient.ts b/packages/sdk/electron/src/ElectronClient.ts index 32011d3836..4c1fad0c3a 100644 --- a/packages/sdk/electron/src/ElectronClient.ts +++ b/packages/sdk/electron/src/ElectronClient.ts @@ -96,7 +96,7 @@ export class ElectronClient extends LDClientImpl { initialContext, }; - const platform = new ElectronPlatform(logger, options); + const platform = new ElectronPlatform(logger, validatedElectronOptions); const derivedNs = deriveNamespace(credential, validatedElectronOptions.namespace); const endpoints = useClientSideId ? browserFdv1Endpoints(credential) : mobileFdv1Endpoints(); diff --git a/packages/sdk/electron/src/ElectronOptions.ts b/packages/sdk/electron/src/ElectronOptions.ts index 171b492f61..c3f9c881dc 100644 --- a/packages/sdk/electron/src/ElectronOptions.ts +++ b/packages/sdk/electron/src/ElectronOptions.ts @@ -1,15 +1,21 @@ -import { ConnectionMode, LDOptions as LDOptionsBase } from '@launchdarkly/js-client-sdk-common'; +import { + ConnectionMode, + LDOptions as LDOptionsBase, + LDStorage, +} from '@launchdarkly/js-client-sdk-common'; import type { LDPlugin } from './LDPlugin'; +/** + * A custom storage implementation for the flag cache. See {@link LDStorage} for the contract. + */ +export type LDElectronStorage = LDStorage; + export interface ElectronOptions extends LDOptionsBase { /** - * Set to true to opt in to compressing event payloads if the SDK supports it, since the - * compression library may not be supported in the underlying SDK framework. If the compression - * library is not supported then event payloads will not be compressed even if this option - * is enabled. + * Set to `true` to compress analytics event payloads with gzip before they are sent. * - * Defaults to false. + * Defaults to `false`. */ enableEventCompression?: boolean; @@ -54,4 +60,32 @@ export interface ElectronOptions extends LDOptionsBase { * from other clients using the same credential in the same process. */ namespace?: string; + + /** + * A custom storage implementation that replaces the built-in file cache. + * + * @remarks + * By default the SDK persists cached flags to a file in the `ldclient-user-cache` directory + * under the Electron `userData` directory. + * Provide an {@link LDElectronStorage} to store that data somewhere else. The SDK catches and logs + * errors thrown by a custom storage, so they never reach the application. + */ + storage?: LDElectronStorage; + + /** + * When `true`, the built-in file cache is encrypted with Electron's `safeStorage` API and is + * written to its own file. A plain-text cache from an earlier run is deleted and never read. + * + * When `safeStorage` reports that encryption is not available, the SDK logs a warning and keeps + * flags in memory only. It never writes a plain-text cache while this option is `true`. On + * Linux, the SDK also keeps flags in memory only when `safeStorage` uses the `basic_text` + * backend, because that backend encrypts with a hardcoded password. + * `safeStorage` is usable only after the Electron `ready` event on Windows and Linux. The cache + * waits for that event on every platform. + * + * This option has no effect when {@link ElectronOptions.storage} is set. + * + * Defaults to `false`. + */ + encryptStorage?: boolean; } diff --git a/packages/sdk/electron/src/LDCommon.ts b/packages/sdk/electron/src/LDCommon.ts index 87f72731ba..3c579d020c 100644 --- a/packages/sdk/electron/src/LDCommon.ts +++ b/packages/sdk/electron/src/LDCommon.ts @@ -30,6 +30,7 @@ export type { LDSingleKindContext, TrackSeriesContext, LDPluginBase, + LDStorage, LDPluginEnvironmentMetadata, LDPluginSdkMetadata, LDPluginApplicationMetadata, diff --git a/packages/sdk/electron/src/index.ts b/packages/sdk/electron/src/index.ts index d2d90e43db..70c0658ba5 100644 --- a/packages/sdk/electron/src/index.ts +++ b/packages/sdk/electron/src/index.ts @@ -1,5 +1,5 @@ import { makeClient } from './ElectronClient'; -import type { ElectronOptions } from './ElectronOptions'; +import type { ElectronOptions, LDElectronStorage } from './ElectronOptions'; import type { LDClient, LDStartOptions } from './LDClient'; import type { LDContext } from './LDCommon'; import type { LDPlugin } from './LDPlugin'; @@ -9,7 +9,7 @@ export * from './LDCommon'; /** @internal */ export { resetElectronStorage } from './platform/ElectronStorage'; -export type { ElectronOptions as LDOptions, LDClient, LDPlugin, LDStartOptions }; +export type { ElectronOptions as LDOptions, LDClient, LDElectronStorage, LDPlugin, LDStartOptions }; /** * Creates the LaunchDarkly client in the Electron main process. The client is not ready until diff --git a/packages/sdk/electron/src/options.ts b/packages/sdk/electron/src/options.ts index 55e43bcaf6..d1a8b5fdf0 100644 --- a/packages/sdk/electron/src/options.ts +++ b/packages/sdk/electron/src/options.ts @@ -7,7 +7,7 @@ import { TypeValidators, } from '@launchdarkly/js-client-sdk-common'; -import type { ElectronOptions } from './ElectronOptions'; +import type { ElectronOptions, LDElectronStorage } from './ElectronOptions'; import type { LDPlugin } from './LDPlugin'; class ConnectionModeValidator implements TypeValidator { @@ -19,6 +19,19 @@ class ConnectionModeValidator implements TypeValidator { } } +class StorageOptionsValidator implements TypeValidator { + is(u: unknown): u is LDElectronStorage { + if (typeof u !== 'object' || u === null) { + return false; + } + const has = (k: string) => typeof (u as Record)[k] === 'function'; + return has('get') && has('set') && has('clear'); + } + getType(): string { + return 'LDElectronStorage ({ get, set, clear })'; + } +} + export interface ValidatedOptions { enableEventCompression?: boolean; initialConnectionMode: ConnectionMode; @@ -26,6 +39,10 @@ export interface ValidatedOptions { enableIPC: boolean; useClientSideId: boolean; namespace?: string; + storage?: LDElectronStorage; + encryptStorage?: boolean; + wrapperName?: string; + wrapperVersion?: string; } const optDefaults: ValidatedOptions = { @@ -35,6 +52,10 @@ const optDefaults: ValidatedOptions = { enableIPC: true, useClientSideId: false, namespace: undefined, + storage: undefined, + encryptStorage: false, + wrapperName: undefined, + wrapperVersion: undefined, }; const validators: { [Property in keyof ElectronOptions]: TypeValidator | undefined } = { @@ -44,6 +65,10 @@ const validators: { [Property in keyof ElectronOptions]: TypeValidator | undefin enableIPC: TypeValidators.Boolean, useClientSideId: TypeValidators.Boolean, namespace: TypeValidators.String, + storage: new StorageOptionsValidator(), + encryptStorage: TypeValidators.Boolean, + wrapperName: TypeValidators.String, + wrapperVersion: TypeValidators.String, }; export function filterToBaseOptions(opts: ElectronOptions): LDOptionsBase { @@ -73,5 +98,11 @@ export default function validateOptions(opts: ElectronOptions, logger: LDLogger) } }); + if (output.storage !== undefined && output.encryptStorage) { + logger.warn( + 'Config option "encryptStorage" has no effect when a custom "storage" is provided.', + ); + } + return output; } diff --git a/packages/sdk/electron/src/platform/ElectronInfo.ts b/packages/sdk/electron/src/platform/ElectronInfo.ts index 587950afb0..99fe4f7b46 100644 --- a/packages/sdk/electron/src/platform/ElectronInfo.ts +++ b/packages/sdk/electron/src/platform/ElectronInfo.ts @@ -19,6 +19,8 @@ function processPlatformName(name: string): string { } export default class ElectronInfo implements Info { + constructor(private readonly _config: { wrapperName?: string; wrapperVersion?: string } = {}) {} + platformData(): PlatformData { return { os: { @@ -35,10 +37,17 @@ export default class ElectronInfo implements Info { } sdkData(): SdkData { - return { + const data: SdkData = { name: sdkName, version: sdkVersion, userAgentBase: 'ElectronClient', }; + if (this._config.wrapperName) { + data.wrapperName = this._config.wrapperName; + } + if (this._config.wrapperVersion) { + data.wrapperVersion = this._config.wrapperVersion; + } + return data; } } diff --git a/packages/sdk/electron/src/platform/ElectronPlatform.ts b/packages/sdk/electron/src/platform/ElectronPlatform.ts index ce9dc0947b..cbce6fc2f8 100644 --- a/packages/sdk/electron/src/platform/ElectronPlatform.ts +++ b/packages/sdk/electron/src/platform/ElectronPlatform.ts @@ -1,6 +1,6 @@ -import { LDLogger, platform } from '@launchdarkly/js-client-sdk-common'; +import { createSafeStorage, LDLogger, platform } from '@launchdarkly/js-client-sdk-common'; -import type { ElectronOptions } from '../ElectronOptions'; +import type { ValidatedOptions } from '../options'; import ElectronCrypto from './ElectronCrypto'; import ElectronEncoding from './ElectronEncoding'; import ElectronInfo from './ElectronInfo'; @@ -10,43 +10,32 @@ import { getElectronStorage } from './ElectronStorage'; // NOTE: Because Electron main process runs on Node.js, this platform should be // very similar to the Node server sdk platform. +export type ElectronPlatformOptions = Pick< + ValidatedOptions, + 'enableEventCompression' | 'wrapperName' | 'wrapperVersion' | 'storage' | 'encryptStorage' +>; + export default class ElectronPlatform implements platform.Platform { - info: platform.Info = new ElectronInfo(); + info: platform.Info; crypto: platform.Crypto = new ElectronCrypto(); encoding?: platform.Encoding = new ElectronEncoding(); - storage?: platform.Storage; + storage: platform.Storage; requests: platform.Requests; - constructor(logger: LDLogger, options: ElectronOptions) { - const globalStorage = getElectronStorage(); - this.storage = { - async get(key: string): Promise { - try { - return await globalStorage.get(key); - } catch (error) { - logger.error(`Error getting key from storage: ${key}, reason: ${error}`); - return null; - } - }, - async set(key: string, value: string): Promise { - try { - await globalStorage.set(key, value); - } catch (error) { - logger.error(`Error setting key in storage: ${key}, reason: ${error}`); - } - }, - async clear(key: string): Promise { - try { - await globalStorage.clear(key); - } catch (error) { - logger.error(`Error clearing key from storage: ${key}, reason: ${error}`); - } - }, - }; + constructor(logger: LDLogger, options: ElectronPlatformOptions) { + this.info = new ElectronInfo({ + wrapperName: options.wrapperName, + wrapperVersion: options.wrapperVersion, + }); + // A custom storage is application code, so every call is guarded and errors are logged. The + // built-in singleton is created only when no custom storage is given. + this.storage = options.storage + ? createSafeStorage(options.storage, logger) + : getElectronStorage(logger, { encrypt: !!options.encryptStorage }); this.requests = new ElectronRequests(options.enableEventCompression); } } diff --git a/packages/sdk/electron/src/platform/ElectronStorage.ts b/packages/sdk/electron/src/platform/ElectronStorage.ts index a6d120c489..bdde1428dc 100644 --- a/packages/sdk/electron/src/platform/ElectronStorage.ts +++ b/packages/sdk/electron/src/platform/ElectronStorage.ts @@ -2,88 +2,235 @@ import * as electron from 'electron'; import * as fs from 'fs/promises'; import * as path from 'path'; -import type { Storage } from '@launchdarkly/js-client-sdk-common'; +import type { LDLogger, Storage } from '@launchdarkly/js-client-sdk-common'; + +// OS, user, and app code can all relocate `userData`, sometimes through a symlink (app.setPath, +// OneDrive Known Folder Move, roaming profiles). The symlink check guards an SDK-owned +// subdirectory, so a normal `userData` move does not trip it. +const CACHE_DIR_NAME = 'ldclient-user-cache'; +const PLAIN_CACHE_FILE = 'ldcache'; +const ENCRYPTED_CACHE_FILE = 'ldcache.enc'; + +const ERROR_PREFIX = { + set: 'Error setting key in storage', + clear: 'Error clearing key from storage', +} as const; + +type StorageOp = keyof typeof ERROR_PREFIX; + +export interface ElectronStorageOptions { + /** + * Encrypts the cache file with Electron's `safeStorage` API and keeps it in its own file. + */ + encrypt?: boolean; +} export default class ElectronStorage implements Storage { + private readonly _storageDir: string; private readonly _storageFile: string; + private readonly _plainFile: string; private readonly _tempFile: string; - private readonly _initialized: Promise; - private _initError?: Error; - private _cache: Map; + private readonly _encrypt: boolean; + private readonly _initialized: Promise; + private readonly _logger?: LDLogger; + private _persistenceDisabled: boolean = false; + private _cache: Map = new Map(); private _flushPending: boolean = false; private _flushQueue: Promise = Promise.resolve(); - constructor() { - this._storageFile = path.join(electron.app.getPath('userData'), 'ldcache'); + constructor(logger?: LDLogger, options: ElectronStorageOptions = {}) { + this._encrypt = !!options.encrypt; + this._storageDir = path.join(electron.app.getPath('userData'), CACHE_DIR_NAME); + this._plainFile = path.join(this._storageDir, PLAIN_CACHE_FILE); + this._storageFile = this._encrypt + ? path.join(this._storageDir, ENCRYPTED_CACHE_FILE) + : this._plainFile; this._tempFile = `${this._storageFile}.tmp`; - this._cache = new Map(); + this._logger = logger; this._initialized = this._initialize(); } - private async _initialize(): Promise { + private async _initialize(): Promise { try { + await fs.mkdir(this._storageDir, { recursive: true, mode: 0o700 }); + + // fs.mkdir succeeds silently if the path already exists as a symlink to a directory, so a + // pre-planted symlink would otherwise redirect where the cache is read from and written to + // without ever surfacing as an init failure. + if ((await fs.lstat(this._storageDir)).isSymbolicLink()) { + throw new Error( + `Storage directory path is a symlink, not a real directory: ${this._storageDir}`, + ); + } + try { await fs.unlink(this._tempFile); } catch { - // Ignore error if file doesn't exist + // Ignore if temp file does not exist. + } + + if (this._encrypt) { + // A plain-text cache is never read or kept once encryption is requested. + await this._removePlainCache(); + const unavailableReason = await this._encryptionUnavailableReason(); + if (unavailableReason) { + this._persistenceDisabled = true; + this._logger?.warn( + `Encrypted flag cache requested, but ${unavailableReason}. Using in-memory storage - flags will not persist across restarts and no plain-text cache is written.`, + ); + return; + } } try { - const data = await fs.readFile(this._storageFile, 'utf8'); + const fileStat = await fs.lstat(this._storageFile); + if (!fileStat.isFile()) { + throw new Error(`Storage file exists but is not a regular file: ${this._storageFile}`); + } + + const data = await this._readCacheFile(); const parsed = JSON.parse(data); - this._cache = new Map(Object.entries(parsed)); - } catch { - await this._atomicWriteToFile(this._cache); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + const entries = Object.entries(parsed).filter( + ([, value]) => typeof value === 'string', + ) as [string, string][]; + this._cache = new Map(entries); + } + } catch (error) { + if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') { + this._logger?.warn( + `Discarding malformed flag cache at ${this._storageFile}: ${error instanceof Error ? error.message : error}`, + ); + await this._atomicWriteToFile(this._cache); + } } + } catch (error) { + this._persistenceDisabled = true; + this._logger?.warn( + `Failed to initialize local flag cache at ${this._storageDir}: ${error instanceof Error ? error.message : error}. Using in-memory storage as a fallback - flags will not persist across restarts.`, + ); + } + } + + // On Windows and Linux, safeStorage answers only after the app `ready` event. + private async _encryptionUnavailableReason(): Promise { + if (!electron.app.isReady()) { + await electron.app.whenReady(); + } + if (!electron.safeStorage.isEncryptionAvailable()) { + return 'safeStorage encryption is not available on this system'; + } + // Without a secret store, Linux safeStorage encrypts with a hardcoded password. That does not + // protect the cache, so the SDK does not use it. + if ( + process.platform === 'linux' && + electron.safeStorage.getSelectedStorageBackend() === 'basic_text' + ) { + return 'safeStorage uses the Linux basic_text backend, which encrypts with a hardcoded password'; + } + return undefined; + } + + private async _removePlainCache(): Promise { + // The temp file covers a plain-mode write that a crash interrupted. + await this._removePlainFile(this._plainFile); + await this._removePlainFile(`${this._plainFile}.tmp`); + } - return true; + private async _removePlainFile(file: string): Promise { + try { + await fs.unlink(file); + this._logger?.info( + `Deleted the plain-text flag cache file at ${file} because the cache is encrypted.`, + ); } catch (error) { - this._initError = error instanceof Error ? error : new Error(String(error)); - return false; + if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') { + this._logger?.warn( + `Failed to delete the plain-text flag cache file at ${file}: ${error instanceof Error ? error.message : error}`, + ); + } } } + private async _readCacheFile(): Promise { + if (this._encrypt) { + return electron.safeStorage.decryptString(await fs.readFile(this._storageFile)); + } + return fs.readFile(this._storageFile, 'utf8'); + } + + private _serializeCache(data: Map): string | Buffer { + const content = JSON.stringify(Object.fromEntries(data)); + return this._encrypt ? electron.safeStorage.encryptString(content) : content; + } + private async _atomicWriteToFile(data: Map): Promise { + const content = this._serializeCache(data); + let handle: fs.FileHandle | undefined; try { - const content = JSON.stringify(Object.fromEntries(data)); - await fs.writeFile(this._tempFile, content, { encoding: 'utf8', mode: 0o600 }); + try { + await fs.unlink(this._tempFile); + } catch { + // The temp file may not exist. Another failure, such as a permissions problem, also + // makes the write below fail, and the handler of that write reports it. + } + handle = await fs.open(this._tempFile, 'wx', 0o600); + await handle.writeFile(content, 'utf8'); + await handle.close(); + handle = undefined; await fs.rename(this._tempFile, this._storageFile); } catch (error) { + if (handle) { + try { + await handle.close(); + } catch (closeError) { + this._logger?.warn(`Failed to close storage temp file during cleanup: ${closeError}`); + } + } try { await fs.unlink(this._tempFile); } catch { - // Ignore cleanup errors + // Ignore cleanup errors. } throw error; } } - private async _throwIfNotInitialized() { - const initialized = await this._initialized; - if (!initialized) { - const reason = this._initError ? `: ${this._initError.message}` : ''; - throw new Error(`Storage is not initialized${reason}`); - } - } - - async clear(key: string): Promise { - await this._throwIfNotInitialized(); - if (this._cache.has(key)) { - this._cache.delete(key); - await this._scheduleFlush(); - } + private _logError(op: StorageOp, key: string, reason: unknown): void { + this._logger?.error(`${ERROR_PREFIX[op]}: ${key}, reason: ${reason}`); } async get(key: string): Promise { - await this._throwIfNotInitialized(); - const value = this._cache.get(key); - return value ?? null; + await this._initialized; + return this._cache.get(key) ?? null; } async set(key: string, value: string): Promise { - await this._throwIfNotInitialized(); + await this._initialized; this._cache.set(key, value); - await this._scheduleFlush(); + if (this._persistenceDisabled) { + return; + } + try { + await this._scheduleFlush(); + } catch (error) { + this._logError('set', key, error); + } + } + + async clear(key: string): Promise { + await this._initialized; + if (this._cache.has(key)) { + this._cache.delete(key); + if (this._persistenceDisabled) { + return; + } + try { + await this._scheduleFlush(); + } catch (error) { + this._logError('clear', key, error); + } + } } private _scheduleFlush(): Promise { @@ -102,18 +249,38 @@ export default class ElectronStorage implements Storage { } } -// Storage should be a singleton to support multiple instances of the SDK. This should have -// the same limitations as the browser sdk using the shared localStorage cache. -let instance: ElectronStorage | undefined; +// Storage is a singleton per mode to support multiple instances of the SDK. This has the same +// limitations as the browser SDK using the shared localStorage cache. The plain and encrypted +// caches use different files, so a client that asks for encryption never gets the plain cache. +// An encrypted storage deletes the plain cache file at init, and a plain storage writes its +// file again on its next flush. +let plainInstance: ElectronStorage | undefined; +let encryptedInstance: ElectronStorage | undefined; -export function getElectronStorage(): ElectronStorage { - if (!instance) { - instance = new ElectronStorage(); +// Returns `Storage`, not the concrete `ElectronStorage` class. The package entry point does not +// export the class. An exported function that returns the class breaks the generated type +// declarations for this file. +export function getElectronStorage( + logger?: LDLogger, + options: ElectronStorageOptions = {}, +): Storage { + if (options.encrypt) { + encryptedInstance ??= new ElectronStorage(logger, { encrypt: true }); + return encryptedInstance; } - return instance; + plainInstance ??= new ElectronStorage(logger, { encrypt: false }); + return plainInstance; } -/** @internal Visible for testing only. */ +/** + * Resets the storage singleton so the next call to {@link getElectronStorage} creates a + * new instance. + * + * @remarks + * For test use only. Lets the contract-test entity and this package's own tests reset + * storage state between runs. + */ export function resetElectronStorage(): void { - instance = undefined; + plainInstance = undefined; + encryptedInstance = undefined; }