Refractoring Stage 2 Add Refractor plan.md
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
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 };
|
||||
Reference in New Issue
Block a user