Last active
May 8, 2021 14:22
-
-
Save arthurdenner/b77acf930ed42fab1fa8d1fc5ad17518 to your computer and use it in GitHub Desktop.
Intercepting fs.promises methods to customize behaviour at runtime with Proxies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Original source code: https://github.com/ErickWendel/securing-files-using-nodejs-crypto-yt | |
// Proxy documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy | |
// app.js | |
// `promises` is now a param instead of an import | |
async function run(promises) { | |
... | |
} | |
// index.js | |
const CryptoHelper = require('./src/cryptoHelper') | |
const app = require('./src/app') | |
;(async () => { | |
const config = { | |
// aes-192 | |
// 24 caracteres * 8 = 192 bits | |
cryptoKey: 'minha-senha-super-segura', | |
} | |
const cryptoHelper = await CryptoHelper.setup(config) | |
const writeFileHandler = { | |
apply: async function (target, that, args) { | |
const [filename, data, encoding = ''] = args | |
const encryptedText = await cryptoHelper.encrypt(data) | |
return target(filename, encryptedText, encoding) | |
}, | |
} | |
const readFileHandler = { | |
apply: async function (target, that, args) { | |
const data = await target(...args) | |
const decrypted = await cryptoHelper.decrypt(data) | |
return decrypted | |
}, | |
} | |
const promisesHandler = { | |
get: function (target, prop, receiver) { | |
switch (prop) { | |
case 'writeFile': | |
return new Proxy(target[prop], writeFileHandler) | |
case 'readFile': | |
return new Proxy(target[prop], readFileHandler) | |
default: | |
return Reflect.get(...arguments) | |
} | |
}, | |
} | |
const customFsPromises = new Proxy(require('fs').promises, promisesHandler) | |
await app.run(customFsPromises) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment