34 lines
1.4 KiB
JavaScript
34 lines
1.4 KiB
JavaScript
const fs = require('node:fs/promises');
|
|
const path = require('node:path');
|
|
|
|
function createSecureJsonStore({ getFilePath, safeStorage, assertSecureStorage, unavailableMessage }) {
|
|
if (typeof getFilePath !== 'function') throw new TypeError('A file path provider is required.');
|
|
if (!safeStorage || typeof safeStorage.encryptStringAsync !== 'function' ||
|
|
typeof safeStorage.decryptStringAsync !== 'function' ||
|
|
typeof safeStorage.isAsyncEncryptionAvailable !== 'function') {
|
|
throw new TypeError('An asynchronous safe storage adapter is required.');
|
|
}
|
|
if (typeof assertSecureStorage !== 'function') throw new TypeError('A secure-storage check is required.');
|
|
|
|
return {
|
|
async load() {
|
|
assertSecureStorage();
|
|
const encrypted = await fs.readFile(getFilePath());
|
|
const { result } = await safeStorage.decryptStringAsync(encrypted);
|
|
return JSON.parse(result);
|
|
},
|
|
|
|
async save(value) {
|
|
assertSecureStorage();
|
|
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error(unavailableMessage);
|
|
const file = getFilePath();
|
|
const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(value));
|
|
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
await fs.writeFile(`${file}.tmp`, encrypted, { mode: 0o600 });
|
|
await fs.rename(`${file}.tmp`, file);
|
|
}
|
|
};
|
|
}
|
|
|
|
module.exports = { createSecureJsonStore };
|