const fs = require('fs') var cli = require('./cliverse') var nodeShellExec = cli.nodeShellExec; var __isElevated = null; var shell_verse = { // getCommonTask is agnostic of whether we are running in an elevated shell or not. It runs in either case. getCommonTask( taskToRun ){ return ()=>{ return shell_verse.runTask(taskToRun) }} , runTask : ( taskToRun ) => { if (__isElevated) return shell_verse.elevatedRunner( taskToRun ) else return shell_verse.runNonElevated( taskToRun ) } , elevatedRunner( taskToRun ){ try { var __runasresult = null; return taskToRun().then((r)=>{ // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here... fs.writeFileSync('run.log', ', ' + JSON.stringify( { info : taskToRun.info, success: true }), { 'flag': 'a+' }) fs.writeFileSync('run.done', 'success') // PB : TODO -- This should be done conditionally if we are running inproc. return __runasresult = r; }) .catch((e) => { fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' }) fs.writeFileSync('run.done', 'failure') console.error(e) }) .finally(() => { if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done') }) } catch (e) { console.error('Error Invalid command : ' + e) fs.writeFileSync('run.done', 'error') } finally { } } , getElevatedTask : function( taskToRun ){ return ()=>{ return shell_verse.runElevated(taskToRun) }} , runElevated : ( taskToRun ) => { // Let shell_verse decide whether to Elevate Out of Proc or In Proc // taskToRun by default is the launched command and args. Specially in windows out of proc. // taskToRun = taskToRun || (()=>{ return op[processedArgs.label || processedArgs._[0] || 'undefined'](processedArgs) }) if(taskToRun.processedArgs.skipelevated) return Promise.resolve({ skipped : true }); if (__isElevated) { return shell_verse.elevatedRunner(taskToRun) } else { console.log('Requesting Elevated Privileges'); // requesteElevation is acutally request elevation and run. Both In Proc and Out of Proc. // Linux doesnt require elevation for most commands... return shell_verse.requestElevation(shell_verse.elevatedRunner, taskToRun) } } , runElevatedBatch( batchToRun ){ // In windows we don't need to run each task. We hand over to another shell which in elevated state rebuilds the whole batch and runs. // Irrespective of the batch we just call runElevated once. return [runElevated(batchToRun[0])] } , getNonElevatedTask : function( taskToRun ){ return ()=>{ return shell_verse.runNonElevated(taskToRun) } } , runNonElevated : ( taskToRun ) => { // Let shell_verse decide whether to Elevate Out of Proc or In Proc if(__isElevated) { return Promise.resolve( new Error('Cannot Run Task in Elevated Mode.') ) } else { // taskToRun by default is the launched command and args. // taskToRun = taskToRun || (()=>{ return op[processedArgs.label || processedArgs._[0] || 'undefined'](processedArgs) }) return taskToRun().then(r=>{ taskToRun.statuslog.statuslog(null, taskToRun.info /*repo*/ ) return r; }).catch((e) => { e.info = taskToRun.info; taskToRun.statuslog.statuslog(e); if(taskToRun.errHandler) throw taskToRun.errHandler(e) // console.error(e) throw e; }).finally(()=>{}) } } , isElevated : ()=>{ return acquireElevationState().then( ()=>{ shell_verse.isElevated = () => { return Promise.resolve(__isElevated) } return shell_verse.isElevated() }) } // , isElevationOutOfProc : ()=>{ return true } , acquireElevationState : () => { return nodeShellExec("fsutil", ["dirty", "query", "C:"], { inherit: true // , shell: true , stdio: 'ignore' , env: process.env , title: `check privileged execution mode using "fsutil dirty query C:"` }).then((exitcode) => { console.log('Elevated') __isElevated = true; }).catch(() => { __isElevated = false; console.log('Not Elevated'); }).finally(()=>{ shell_verse.acquireElevationState = ()=> Promise.resolve(__isElevated); shell_verse.isElevated = () => { return Promise.resolve(__isElevated)} return __isElevated; }) } , getTaskCheckExists : cli.createTask('getTaskCheckExists', 'where') , getbash : ()=>{ return "C:\\Program Files\\Git\\bin\\sh.exe" } , createJuntionOrLink : (dirOrFile, target, opts) =>{ return nodeShellExec('mklink', ['/J', dirOrFile, target], opts).catch((e) => { console.error(e) }) } , removeJuncionOrLink : ( junctionOrLink )=>{ return nodeShellExec('rmdir', [junctionOrLink], { inherit: true, shell: true, env: process.env }) } , requestElevation(elevatedRunner, taskToRun) { // PB : TODO -- Multiple parallel request elevations should be queued into a promise. var processedArgs = taskToRun.processedArgs, selectedinstance = taskToRun.selectedinstance , statuslog = taskToRun.statuslog // Wait for the runas to complete before we read it. try { fs.unlinkSync('run.done') fs.unlinkSync('run.log') } catch (e) { } //Ignore // Find node path to send to hta. return nodeShellExec('where', ['node']).then(r => { var namedArgs = []; console.log('result : ' + JSON.stringify(r)) Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; }) // PB : TODO -- Convert all the cli args back to string. var args = [`${selectedinstance.root}/.elxr/run-${taskToRun.runtimestamp}/windowselevate.hta`].concat(processedArgs._) namedArgs.length > 0 ? args = args.concat(namedArgs.join(' ')) : null; args.push('--runas=self'); // args.push('--nodepath=' + r.messages[r.messages.length - 1]) // if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV) // if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated.. // console.dir(processedArgs._) // console.dir(namedArgs.join(' ')) console.dir(args) // throw 'test' return nodeShellExec('MSHTA', [`"${args.join('" "')}"`] , { inherit: true , shell: true , env: taskToRun.ENV , runas: 'self' , title: `runas` } ).then(() => { // runas returned. try { // PB : TODO -- Log is comma prefixed. Needs to be proper JSON. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']'); runaslog.forEach((logEntry) => { statuslog.statuslog(logEntry.success ? null : logEntry, logEntry) logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' '))) }) } catch (e) { // We must have a runas log statuslog.statuslog(e) console.error('Run log error probably was not created by runas : ' + e) } }) .catch(err => console.error('Elevation failed : ' + err)); }) } } module.exports = shell_verse