UNPKG

hsynchronous-fs

Version:

Post-Quantum filesystem encryption using a hybrid encryption protocol "hsynchronous"

1 lines 8.79 kB
'use strict';var fs=require('fs'),path=require('path'),child_process=require('child_process'),os=require('os'),util=require('util'),crypto=require('crypto'),hsynchronous=require('hsynchronous'),zipLib=require('zip-lib'),z=require('args');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var z__default=/*#__PURE__*/_interopDefault(z);var g=(e,r)=>()=>(e&&(r=e(e=0)),r);var W=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports);var a=(e,r,o)=>new Promise((t,s)=>{var c=p=>{try{l(o.next(p));}catch(d){s(d);}},n=p=>{try{l(o.throw(p));}catch(d){s(d);}},l=p=>p.done?t(p.value):Promise.resolve(p.value).then(c,n);l((o=o.apply(e,r)).next());});function $(e,r,o){return a(this,null,function*(){try{let t=path.join(__dirname,"../",r),s=path.join(__dirname,"../",o);try{fs.existsSync(t)&&(fs.rmSync(t,{recursive:!0,force:!0}),console.log(`Successfully removed folder: ${t}`));}catch(n){console.warn(`Warning: Could not remove folder ${t}: ${n.message}`);}try{fs.existsSync(s)&&(fs.rmSync(s,{force:!0}),console.log(`Successfully removed zip file: ${s}`));}catch(n){console.warn(`Warning: Could not remove zip file ${s}: ${n.message}`);}let c=os.platform();try{if(c==="win32"){let n=`subst ${e}: /D`;yield G(n),console.log(`Successfully unmounted drive ${e}:`);}else console.warn(`Cleanup for platform ${c} only supports file deletion, not unmounting`);}catch(n){}}catch(t){throw console.error("Error during cleanup:",t.message),new Error(`Cleanup failed: ${t.message}`)}})}function F(e){return a(this,null,function*(){try{let r=path.join(__dirname,"../",e);if(!fs.existsSync(r))throw new Error(`Key file not found at path: ${r}`);let o;try{o=fs.readFileSync(r,"utf8");}catch(s){throw new Error(`Failed to read key file: ${s.message}`)}let t=o.trim();if(!t)throw new Error("Key file is empty (contains only whitespace)");return t}catch(r){let o=`Failed to load key from ${e}: ${r.message}`;throw console.error(`Key loading error: ${o}`),new Error(o)}})}function I(e){return a(this,null,function*(){try{if(!e||typeof e!="string")throw new Error("Invalid file path provided");let r=`${e}.bak`;if(!fs.existsSync(e)){console.warn(`Warning: Source file ${e} does not exist, skipping backup creation.`);return}let o;try{o=fs.readFileSync(e,"utf8");}catch(t){throw new Error(`Failed to read source file: ${t.message}`)}if(o===void 0)throw new Error("File content was not read properly");try{fs.writeFileSync(r,o,"utf8"),console.log(`Success: Created backup at ${r}`);}catch(t){throw new Error(`Failed to create backup file: ${t.message}`)}}catch(r){throw console.error(`Backup Error: Failed to create backup for ${e}:`,r.message),new Error(`Backup operation failed: ${r.message}`)}})}function A(e){return a(this,null,function*(){try{if(!e||typeof e!="string")throw new Error("Invalid file path provided");let r=`${e}.bak`;if(!fs.existsSync(r)){console.warn(`Warning: Backup file ${r} does not exist, skipping deletion.`);return}try{fs.rmSync(r,{force:!0}),console.log(`Success: Deleted backup at ${r}`);}catch(o){throw new Error(`Failed to delete backup file: ${o.message}`)}}catch(r){throw console.error(`Backup Error: Failed to delete backup for ${e}:`,r.message),new Error(`Backup deletion failed: ${r.message}`)}})}function m(e,r=100,o=125){for(let t=0;t<r;t++)typeof e=="string"?e=crypto.randomBytes(o).toString("hex"):e&&typeof e=="object"&&(e={kemKeyPair:crypto.randomBytes(o).toString("hex"),sigKeyPair:crypto.randomBytes(o).toString("hex")});}var G,E=g(()=>{G=util.promisify(child_process.exec);});function b(e,r){return a(this,null,function*(){try{let o=path.join(__dirname,"../",r),t;try{t=fs.readFileSync(o,"hex");}catch(n){throw new Error(`Failed to read zip file: ${n.message}`)}try{fs.rmSync(o,{force:!0});}catch(n){throw new Error(`Failed to remove original zip file: ${n.message}`)}let s;try{s=yield hsynchronous.encrypt(t,e),m(e);}catch(n){throw new Error(`Encryption failed: ${n.message}`)}let c=path.join(__dirname,"../","encrypted");try{fs.writeFileSync(c,s);}catch(n){throw new Error(`Failed to write encrypted file: ${n.message}`)}}catch(o){throw new Error(`encryptCompressVirtualDrive failed: ${o.message}`)}})}function O(e,r,o){return a(this,null,function*(){try{let t=path.join(process.cwd(),o),s=path.join(__dirname,"../",r),c;try{c=fs.readFileSync(t,"utf8");}catch(l){throw new Error(`Failed to read encrypted file: ${l.message}`)}let n;try{n=yield hsynchronous.decrypt(c,e),m(e);}catch(l){throw new Error(`Decryption failed: ${l.message}`)}if(!n||!n.message)throw new Error("Decrypted data is invalid or missing message");try{fs.writeFileSync(s,n.message,{encoding:"hex"});}catch(l){throw new Error(`Failed to write decrypted file: ${l.message}`)}}catch(t){throw new Error(`decryptVirtualDrive failed: ${t.message}`)}})}var T=g(()=>{E();});function V(e){return a(this,null,function*(){let r=os.platform();try{if(r==="win32"){let o=`subst ${e}: /D`;yield k(o),console.log(`Virtual drive ${e}: unmounted successfully`);}else throw new Error(`Unsupported platform: ${r}`)}catch(o){throw console.error("Error unmounting virtual drive:",o.message),new Error(`Failed to unmount virtual drive: ${o.message}`)}})}function R(e,r,o,t,s){return a(this,null,function*(){let c=os.platform(),n=path.join(__dirname,"../",e),l=path.join(process.cwd(),o),p=path.join(__dirname,"../",t);if(fs.existsSync(l)){if(yield O(s,t,o),m(s),!fs.existsSync(p))throw new Error(`Zip file ${t} does not exist after decryption`);fs.rmSync(l,{force:true}),yield zipLib.extract(p,n),fs.rmSync(p,{force:true});}fs.existsSync(n)||fs.mkdirSync(n,{recursive:true});try{if(c==="win32"){let d=`subst ${r}: "${n}"`;yield k(d);}else throw new Error(`Unsupported platform: ${c}`)}catch(d){throw console.error("Error creating virtual drive:",d.message),new Error(`Failed to create virtual drive: ${d.message}`)}})}function C(e){return a(this,null,function*(){try{let r=path.join(__dirname,"../",e);if(!fs.existsSync(r)){console.warn(`Folder ${r} does not exist, skipping deletion`);return}fs.rmSync(r,{recursive:!0,force:!0});}catch(r){throw console.error("Error deleting virtual drive:",r.message),new Error(`Failed to delete virtual drive: ${r.message}`)}})}function H(e){return a(this,null,function*(){let r=os.platform();try{if(r==="win32")yield k(`start ${e}:`),console.log(`Opened virtual drive ${e}: in File Explorer`);else throw new Error(`Unsupported platform: ${r}`)}catch(o){throw console.error("Error opening virtual drive:",o.message),new Error(`Failed to open virtual drive: ${o.message}`)}})}function M(e,r){return a(this,null,function*(){let o=path.join(__dirname,"../",e),t=path.join(__dirname,"../",r);if(!fs.existsSync(t))throw new Error(`Source folder ${t} does not exist`);yield zipLib.archiveFolder(t,o,{compressionLevel:9});})}var k,U=g(()=>{T();E();k=util.promisify(child_process.exec);});var sr=W(B=>{T();E();U();z__default.default.option("drive","The Drive letter to mount to","A").option("key","The key file path").option("file","The input and output file that holds your encrypted data","./encrypted");var P=z__default.default.parse(process.argv),i={DRIVE_LETTER:P.drive.toUpperCase().replace(":","")||"A",MOUNT_FOLDER_PATH:"./tmp",ZIP_FILE_NAME:"tmp.zip",KEY_FILE_PATH:P.key||"./key.txt",ENCRYPTED_FILE_PATH:P.file||"./encrypted"};function ar(){return a(this,null,function*(){console.log(""),console.log(` __QQ \x1B[1m hsynchronous ${hsynchronous.VERSION}\x1B[0m`),console.log(' (_)_\x1B[31m"\x1B[0m> Post-Quantum Filesystem Encryption'),console.log("_) \x1B[2m github.com/doodad-labs\x1B[0m"),console.log(""),/^[A-Z]$/.test(i.DRIVE_LETTER)||(console.error(`Error: Invalid drive letter (${i.DRIVE_LETTER}). Use format like "C:", "D:", etc.`),process.exit(1)),yield $(i.DRIVE_LETTER,i.MOUNT_FOLDER_PATH,i.ZIP_FILE_NAME);let e=yield F(i.KEY_FILE_PATH);m(e);let r=yield hsynchronous.importKeys(e);I(i.ENCRYPTED_FILE_PATH),console.log("\x1B[41mDO NOT TERMINATE OR CLOSE THIS PROCESS WITHOUT UNMOUNTING, \x1B[1mYOU WILL LOSE ALL DATA.\x1B[0m"),yield R(i.MOUNT_FOLDER_PATH,i.DRIVE_LETTER,i.ENCRYPTED_FILE_PATH,i.ZIP_FILE_NAME,r),m(r),yield H(i.DRIVE_LETTER),console.log("\x1B[1mPress Enter to unmount and encrypt the virtual drive...\x1B[0m"),process.stdin.once("data",()=>a(null,null,function*(){yield V(i.DRIVE_LETTER),yield M(i.ZIP_FILE_NAME,i.MOUNT_FOLDER_PATH),yield C(i.MOUNT_FOLDER_PATH),console.log("Virtual drive unmounted and compressed. Now encrypting..."),e=yield F(i.KEY_FILE_PATH),m(e),r=yield hsynchronous.importKeys(e),yield b(r,i.ZIP_FILE_NAME),m(r),A(i.ENCRYPTED_FILE_PATH),process.exit(0);}));})}process.on("exit",()=>a(null,null,function*(){console.log("Cleaning up..."),yield $(i.DRIVE_LETTER,i.MOUNT_FOLDER_PATH,i.ZIP_FILE_NAME);}));ar().catch(e=>{console.error("Script error:",e.message),process.exit(1);});});var index = sr();module.exports=index;