Skip to content

Instantly share code, notes, and snippets.

@arthurdenner
Last active May 8, 2021 14:22
Show Gist options
  • Save arthurdenner/b77acf930ed42fab1fa8d1fc5ad17518 to your computer and use it in GitHub Desktop.
Save arthurdenner/b77acf930ed42fab1fa8d1fc5ad17518 to your computer and use it in GitHub Desktop.
Intercepting fs.promises methods to customize behaviour at runtime with Proxies
// 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