You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. const { any } = require('bbhverse');
  2. const fs = require('fs')
  3. var path = require('path');
  4. var cli = require('./cliverse')
  5. var nodeShellExec = cli.nodeShellExec;
  6. function elevatedRunIPCWriteMessage( target, m ) {
  7. fs.writeFileSync(target, ', ' + JSON.stringify( m ), { 'flag': 'a+' })
  8. }
  9. function toHTML(l, x, r, ol, or){
  10. ol = ol || '<div>'
  11. or = or || '</div>'
  12. l = l || '<div>'
  13. r = r || '</div>'
  14. if(Object.prototype.toString.call(x) === '[object Array]') {
  15. var ahtml = []
  16. x.forEach(xi => { ahtml.push( `${l}${xi}${r}` ) })
  17. return `${ol}${ahtml.join('')}${or}`
  18. }
  19. }
  20. var __isElevated = null;
  21. var shell_verse = {
  22. // getCommonTask is agnostic of whether we are running in an elevated shell or not. It runs in either case.
  23. init( o ){ Object.assign(this, o) }
  24. , downloadsdir : '../Downloads'
  25. , getCommonTask( taskToRun ){ return ()=>{ return shell_verse.runTask(taskToRun) }}
  26. , runTask : ( taskToRun ) => {
  27. if (__isElevated) return shell_verse.elevatedRunner( taskToRun )
  28. else return shell_verse.runNonElevated( taskToRun )
  29. }
  30. , elevatedRunner( taskToRun, inBatch ){
  31. // PB : TODO -- Should be called only when we are in an elevated shell that was already requested from an unelevated shell with a batch of tasks.
  32. try {
  33. var runlogjson = `${taskToRun.selectedinstance.root}/.elxr/run-${taskToRun.runtimestamp}/run.log`
  34. var __runasresult = null;
  35. return taskToRun().then((r)=>{
  36. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  37. elevatedRunIPCWriteMessage( runlogjson, { info : taskToRun.info, success: true } )
  38. if(!inBatch) fs.writeFileSync('run.done', 'success') // PB : TODO -- This should be done conditionally if we are running inproc.
  39. return __runasresult = r;
  40. })
  41. .catch((e) => {
  42. elevatedRunIPCWriteMessage( runlogjson, e)
  43. if(!inBatch)fs.writeFileSync('run.done', 'failure')
  44. console.error(e)
  45. })
  46. .finally(() => {
  47. // if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  48. })
  49. }
  50. catch (e) {
  51. console.error('Error Invalid command : ' + e)
  52. if(!inBatch) fs.writeFileSync('run.done', 'error')
  53. }
  54. finally {
  55. }
  56. }
  57. , getElevatedTask : function( taskToRun ){ return ()=>{ return shell_verse.runElevated(taskToRun) }}
  58. , getElevatedTaskInBatch : function( taskToRun ){ return ()=>{ return shell_verse.runElevatedInBatch(taskToRun) }}
  59. , runElevatedInBatch : ( taskToRun ) => {
  60. if (__isElevated) return shell_verse.elevatedRunner(taskToRun, true)
  61. else return shell_verse.requestElevation(shell_verse.elevatedRunner, taskToRun)
  62. }
  63. , runElevated : ( taskToRun ) => {
  64. // Let shell_verse decide whether to Elevate Out of Proc or In Proc
  65. // taskToRun by default is the launched command and args. Specially in windows out of proc.
  66. // taskToRun = taskToRun || (()=>{ return op[processedArgs.label || processedArgs._[0] || 'undefined'](processedArgs) })
  67. if(taskToRun.processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  68. if (__isElevated) {
  69. return shell_verse.elevatedRunner(taskToRun)
  70. }
  71. else {
  72. console.log('Requesting Elevated Privileges');
  73. // requesteElevation is acutally request elevation and run. Both In Proc and Out of Proc.
  74. // Linux doesnt require elevation for most commands...
  75. return shell_verse.requestElevation(shell_verse.elevatedRunner, taskToRun)
  76. }
  77. }
  78. , runElevatedBatch( batchToRun ){
  79. // 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.
  80. // Irrespective of the batch we just call runElevated once.
  81. if (__isElevated) {
  82. return any(batchToRun).then((r)=>{
  83. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  84. // fs.writeFileSync('run.log', ', ' + JSON.stringify( { info : taskToRun.info, success: true }), { 'flag': 'a+' })
  85. fs.writeFileSync('run.done', 'success') // PB : TODO -- This should be done conditionally if we are running inproc.
  86. return __runasresult = r;
  87. })
  88. .catch((e) => {
  89. // fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  90. fs.writeFileSync('run.done', 'failure')
  91. console.error(e)
  92. })
  93. // .finally(() => {
  94. // if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  95. // });
  96. }
  97. else {
  98. return this.runElevated(batchToRun[0])
  99. }
  100. }
  101. , getNonElevatedTask : function( taskToRun ){ return ()=>{ return shell_verse.runNonElevated(taskToRun) } }
  102. , runNonElevated : ( taskToRun ) => {
  103. // Let shell_verse decide whether to Elevate Out of Proc or In Proc
  104. if(__isElevated) {
  105. return Promise.resolve( 'Skipping regular task in elevated shell.' ) // Regular tasks unless marked as common tasks should not run in elevated shell...
  106. }
  107. else {
  108. // taskToRun by default is the launched command and args.
  109. // taskToRun = taskToRun || (()=>{ return op[processedArgs.label || processedArgs._[0] || 'undefined'](processedArgs) })
  110. return taskToRun().then(r=>{
  111. taskToRun.statuslog.statuslog(null, taskToRun.info /*repo*/ )
  112. return r;
  113. }).catch((e) => {
  114. e.info = taskToRun.info;
  115. if(taskToRun.errHandler) throw taskToRun.errHandler(e)
  116. taskToRun.statuslog.statuslog(e); //
  117. // console.error(e)
  118. throw e;
  119. }).finally(()=>{})
  120. }
  121. }
  122. , isElevated : ()=>{
  123. return acquireElevationState().then( ()=>{
  124. shell_verse.isElevated = () => {
  125. return Promise.resolve(__isElevated)
  126. }
  127. return shell_verse.isElevated()
  128. })
  129. }
  130. // , isElevationOutOfProc : ()=>{ return true }
  131. , acquireElevationState : () => {
  132. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  133. inherit: true
  134. // , shell: true
  135. , stdio: 'ignore'
  136. , env: process.env
  137. , title: `check privileged execution mode using "fsutil dirty query C:"`
  138. }).then((exitcode) => {
  139. console.log('Elevated')
  140. __isElevated = true;
  141. shell_verse.acquireElevationState = ()=> Promise.resolve(__isElevated);
  142. shell_verse.isElevated = () => { return Promise.resolve(__isElevated)}
  143. return __isElevated
  144. }).catch((e) => {
  145. __isElevated = false;
  146. shell_verse.acquireElevationState = ()=> Promise.resolve(__isElevated);
  147. shell_verse.isElevated = () => { return Promise.resolve(__isElevated)}
  148. console.log('Not Elevated');
  149. return __isElevated
  150. })
  151. // .finally(()=>{
  152. // shell_verse.acquireElevationState = ()=> Promise.resolve(__isElevated);
  153. // shell_verse.isElevated = () => { return Promise.resolve(__isElevated)}
  154. // // return __isElevated; // Value returned from finally is not supported by node.
  155. // })
  156. }
  157. , getTaskCheckExists : cli.createTask('getTaskCheckExists', 'where')
  158. , getbash : ()=>{ return "C:\\Program Files\\Git\\bin\\sh.exe" }
  159. , createJuntionOrLink : (dirOrFile, target, opts) =>{
  160. return nodeShellExec('mklink', ['/J', dirOrFile, target], opts).catch((e) => { console.error(e) })
  161. }
  162. , removeJuncionOrLink : ( junctionOrLink )=>{
  163. return nodeShellExec('rmdir', [junctionOrLink], { inherit: true, shell: true, env: process.env })
  164. }
  165. , requestElevation(elevatedRunner, taskToRun) {
  166. // PB : TODO -- Multiple parallel request elevations should be queued into a batch and serialized as a single promise.
  167. var processedArgs = taskToRun.processedArgs, statuslog = taskToRun.statuslog
  168. // Wait for the runas to complete before we read it.
  169. try {
  170. fs.unlinkSync('run.done') // Need a unique file for aech elevated run.
  171. }
  172. catch (e) { } //Ignore
  173. // Find node path to send to hta.
  174. return nodeShellExec('where', ['node']).then(r => {
  175. var args = taskToRun.args
  176. var options = taskToRun.args ? taskToRun.args.pop() : {
  177. inherit: true
  178. , shell: true
  179. , env: taskToRun.ENV
  180. , runas: 'self'
  181. , title: `runas`
  182. }
  183. options.env = Object.assign({}, taskToRun.ENV, { wd : options.cwd })
  184. var spawntimestamp = (new Date()).getTime()
  185. if(!args) {
  186. var namedArgs = [];
  187. console.log('result : ' + JSON.stringify(r))
  188. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  189. // PB : TODO -- Convert all the cli args back to string.
  190. args = [].concat(processedArgs._)
  191. namedArgs.length > 0 ? args = args.concat(namedArgs.join(' ')) : null;
  192. }
  193. else {
  194. // args = args.splice(-1) -- Already popped
  195. args.push(`--root=${selectedinstance.root}`);
  196. }
  197. args.splice(0,0, path.normalize(`${taskToRun.selectedinstance.root}/.elxr/run-${taskToRun.runtimestamp}/windowselevate.hta`))
  198. args.push('--runas=self');
  199. // args.debug = true
  200. if(args.debug) args.push(`--debug=${args.debug}`);
  201. args.push(`--runtimestamp=${spawntimestamp}`);
  202. // args.push(`--wd=${options.cwd}`);
  203. // args.push('--nodepath=' + r.messages[r.messages.length - 1])
  204. // if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  205. // if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  206. // console.dir(processedArgs._)
  207. // console.dir(namedArgs.join(' '))
  208. console.dir(args)
  209. // throw 'test'
  210. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`], options ).then(() => {
  211. // runas returned.
  212. try {
  213. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  214. var runlogjson = `${taskToRun.selectedinstance.root}/.elxr/run-${spawntimestamp}/run.log`
  215. var runaslog = JSON.parse('[' + fs.readFileSync(runlogjson, { flags: 'a+' }) + ']');
  216. try { fs.unlinkSync(runlogjson) } catch(e){ } // PB : TODO -- Have a unique file for each elevated run.
  217. // console.log( "runaslog : " + runaslog.length )
  218. // Assemble elevated run results into the main run log
  219. runaslog.forEach((logEntry) => {
  220. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  221. logEntry.success ? (console.log(['success :' + (logEntry.result || logEntry.success)]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  222. })
  223. }
  224. catch (e) {
  225. // We must have a runas log
  226. statuslog.statuslog(e)
  227. console.error('Run log error probably was not created by runas : ' + e)
  228. }
  229. })
  230. .catch(err => console.error('Elevation failed : ' + JSON.stringify(err)));
  231. })
  232. }
  233. , launchui() {
  234. // PB : TODO -- Multiple parallel requests should be queued into a batch and serialized as a single promise.
  235. // PB : TODO -- cleanup elevated execution code from here. This is a non elevated hta.
  236. var processedArgs = this.processedArgs
  237. // Wait for the runas to complete before we read it.
  238. try {
  239. fs.unlinkSync('run.done') // Need a unique file for aech elevated run.
  240. }
  241. catch (e) { } //Ignore
  242. console.log(this.processedArgs.awaiturn)
  243. // Find node path to send to hta.
  244. return nodeShellExec('where', ['node']).then(r => {
  245. var namedArgs = [];
  246. console.log('result : ' + JSON.stringify(r))
  247. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  248. // PB : TODO -- Convert all the cli args back to string.
  249. var _args = []
  250. if(processedArgs._[0] === 'launchui' ) { _args = processedArgs._.slice(1); _args.splice(0,0, 'pull') } // Default command.
  251. else _args = processedArgs._;
  252. var args = [ path.normalize(`${this.selectedinstance.root}/.elxr/run-${this.runtimestamp}/windowselevate.hta`) ].concat(_args)
  253. namedArgs.length > 0 ? args = args.concat(namedArgs.join(' ')) : null;
  254. // args.push('--runas=self');
  255. var spawntimestamp = (new Date()).getTime()
  256. args.push(`--runtimestamp=${spawntimestamp}`);
  257. // args.push('--nodepath=' + r.messages[r.messages.length - 1])
  258. // if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  259. // if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  260. // console.dir(processedArgs._)
  261. // console.dir(namedArgs.join(' '))
  262. console.dir(args)
  263. // throw 'test'
  264. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  265. , {
  266. inherit: true
  267. , shell: true
  268. , env: this.ENV
  269. // , runas: 'self'
  270. // , title: `runas`
  271. }
  272. ).then(() => {
  273. // runas returned.
  274. try {
  275. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  276. var runlogjson = `${this.selectedinstance.root}/.elxr/run-${spawntimestamp}/run.log`
  277. var runaslog = JSON.parse('[' + fs.readFileSync(runlogjson, { flags: 'a+' }) + ']');
  278. try { fs.unlinkSync(runlogjson) } catch(e){ } // PB : TODO -- Have a unique file for each elevated run.
  279. // console.log( "runaslog : " + runaslog.length )
  280. // Assemble elevated run results into the main run log
  281. runaslog.forEach((logEntry) => {
  282. this.statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  283. logEntry.success ? (console.log(['success :' + (logEntry.result || logEntry.success)]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  284. })
  285. }
  286. catch (e) {
  287. // We must have a runas log
  288. this.statuslog.statuslog(e)
  289. console.error('Run log error probably was not created by runas : ' + e)
  290. }
  291. })
  292. .catch(err => console.error('Elevation failed : ' + err));
  293. })
  294. }
  295. , ensureDirectoryExistence(filePath) {
  296. var dirname = path.dirname(filePath);
  297. if (fs.existsSync(dirname)) {
  298. return filePath;
  299. }
  300. this.ensureDirectoryExistence(dirname);
  301. fs.mkdirSync(dirname);
  302. return filePath;
  303. }
  304. , generateDependencies(){
  305. // PB : TODO -- Keep only the last n runs...
  306. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  307. this.ensureDirectoryExistence(`${this.selectedinstance.root}/.elxr/run-${this.runtimestamp}/download.bat`)
  308. fs.writeFileSync(this.ensureDirectoryExistence(path.normalize(`${this.selectedinstance.root}/${this.downloadsdir}/readme.txt`)), `${this.getVersion()} Your local downloads for this instance`)
  309. // PB : TODO include and build from files... using rollup..
  310. var downloadbatch =
  311. `::**************************************************************************
  312. :Download_ <url> <File>
  313. Powershell.exe ^
  314. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  315. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  316. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  317. exit /b
  318. ::**************************************************************************`
  319. fs.writeFileSync(`${this.selectedinstance.root}/.elxr/run-${this.runtimestamp}/download.bat`, downloadbatch)
  320. var windowselevate =
  321. `
  322. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  323. <script language="vbscript">
  324. document.title = "elxr control panel"
  325. self.ResizeTo 1024,1000
  326. Sub Window_Onload
  327. self.MoveTo (screen.availWidth - (screen.availWidth/2 + 40)),10
  328. End Sub
  329. Set objShell = CreateObject("WScript.Shell")
  330. Set objENV = objShell.Environment("Process")
  331. dim NODE_ENV
  332. NODE_ENV = objENV("NODE_ENV")
  333. </script>
  334. <script language="javascript">
  335. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  336. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  337. // alert(windowselevate.commandLine)
  338. var args = windowselevate.commandLine.split('"').slice(3);
  339. // alert(args)
  340. var processedArgs = { _ : [] }
  341. var namedArgs = [];
  342. namedArgs.push('--wd=' + objENV('wd'))
  343. // alert(namedArgs)
  344. for(var item in args){
  345. if(args[item].charAt(0) === '-'){
  346. namedArgs.push(args[item])
  347. var split = args[item].split('=');
  348. processedArgs[split[0].slice(2)] = split[1] || true;
  349. }
  350. else processedArgs._.push(args[item]);
  351. }
  352. var awaitrun = true;
  353. if(!processedArgs.awaitrun) {
  354. awaitrun = false;
  355. delete processedArgs.awaitrun
  356. }
  357. // args = args.forEach(function(item){ })
  358. // alert('processedArgs._ : ' + processedArgs._);
  359. // alert(processedArgs.runas);
  360. // alert(objENV('wd'))
  361. // PB : TODO -- Convert all the cli args back to string.
  362. // __filename will sure we are launhed using the same entry point.
  363. var cargs = (processedArgs.debug ? '--inspect-brk=9226' : '') + ' ${__filename.replace(/\\/g, '\\\\').replace("win_verse", "index")} ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  364. var shell = new ActiveXObject('shell.application');
  365. // alert('launching node privilged. ' + processedArgs['nodepath'])
  366. // shell.ShellExecute('cmd.exe', '/k where node', '', '', 10);
  367. // shell.ShellExecute('cmd.exe', '/k notepad.exe', '', 'runas', 1);
  368. // shell.ShellExecute('cmd.exe ', '/k node ', '', 'runas', 1);
  369. // shell.ShellExecute('cmd.exe ', '/k node ' + cargs + '', '', 'runas', 1);
  370. // alert(cargs)
  371. function run(runas){ shell.ShellExecute('node', cargs, '', runas, 1); }
  372. if(!awaitrun) { run('runas') }
  373. var log = document.createElement('div');
  374. log.innerHTML='Please Wait';
  375. function l(msg){ log.innerHTML+= msg; };
  376. // log.style.color = 'blue';
  377. log.style.width = '95%';
  378. log.id = 'log';
  379. function endconsole(from){
  380. // alert('endconsole ' + from)
  381. if(fso.FileExists("run.done")) {
  382. fso.DeleteFile('run.done') // PB : TODO -- IPC through files is needed only for windows we need to do it per run...
  383. }
  384. // alert('closing window')
  385. window.close();
  386. };
  387. var timer = function(){
  388. // alert('here')
  389. l('.');
  390. if(fso.FileExists("run.done")) {
  391. endconsole('timer')
  392. }
  393. else window.setTimeout(timer, 1000);
  394. };
  395. // alert('/k node ' + cargs + '')
  396. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  397. var fso = new ActiveXObject('Scripting.FileSystemObject');
  398. function i(html){ var e = document.createElement('div'); e.innerHTML = html; document.body.appendChild(e); };
  399. // window.onbeforeunload = function (e) {
  400. // endconsole('onbeforeunload')
  401. // };
  402. window.onload = function() {
  403. document.body.style.backgroundColor = 'black';
  404. document.body.style.fontFamily = 'arial';
  405. document.body.style.color = 'cyan';
  406. var cmds = document.createElement('div');
  407. cmds.innerHTML = '';
  408. cmds.w = function(msg){ cmds.innerHTML+= msg; };
  409. cmds.w('<Br/>Current config : ')
  410. // cmds.w('<div style="width:50%" onclick="endconsole()">X</div>' )
  411. cmds.w('<input type="button" value="Close Console" onclick="endconsole()">')
  412. cmds.w('<Br/>NODE_ENV = ' + NODE_ENV)
  413. var namedArgs = [];
  414. for(var v in processedArgs){
  415. if(v != '_' && v!== 'runtimestamp') {
  416. namedArgs.push('--' + v + '=' + processedArgs[v])
  417. }
  418. }
  419. // cmds.w('<Br/>cmd = ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ') )
  420. cmds.w('<Br/><Br/>')
  421. cmds.w('cmd = <input style="width:80%" type="text" value="' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ') + '"></input> <input type="button" value="Run" onclick="run()"></input>')
  422. cmds.w('${toHTML('<option>', Object.keys(this.cmds), '</option>', '<select>', '</select>')}');
  423. // cmds.style.color = 'blue';
  424. // processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  425. document.body.appendChild(cmds);
  426. document.body.appendChild(log);
  427. // alert(fso.GetAbsolutePathName("."))
  428. window.setTimeout(timer, 3000);
  429. };
  430. </script>
  431. </html>
  432. `
  433. fs.writeFileSync(`${this.selectedinstance.root}/.elxr/run-${this.runtimestamp}/windowselevate.hta`, windowselevate)
  434. }
  435. , getchrome(){
  436. // Chrome install location from registry.
  437. return shell_verse.regread("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe\\").then(chromepath => {
  438. // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe
  439. console.log(chromepath)
  440. return chromepath
  441. });
  442. }
  443. , regread(s){
  444. var uniquerun = (new Date()).getTime()
  445. var out = `${this.selectedinstance.root}/.elxr/run-${this.runtimestamp}/${uniquerun}-regread.out`
  446. var outescaped = out.replace(/\\/g,"\\\\")
  447. // console.log('out ::: ' + out)
  448. fs.writeFileSync(`${this.selectedinstance.root}/.elxr/run-${this.runtimestamp}/${uniquerun}-regread.js`,
  449. `
  450. // WScript.Echo('------------UNNAMED-----------')
  451. // WScript.Echo(WScript.Arguments.Item(0))
  452. argEnumerator = new Enumerator(WScript.Arguments.Unnamed)
  453. var args = []
  454. for(; !argEnumerator.atEnd(); argEnumerator.moveNext()){
  455. args.push('' + argEnumerator.item() + '')
  456. // WScript.Echo('-arg-' + argEnumerator.item() + '-arg-') // Value
  457. }
  458. // WScript.Echo(args[0])
  459. var objShell = WScript.createobject("wscript.shell")
  460. if(!args[0]) {
  461. WScript.Echo( '' )
  462. }
  463. else {
  464. WScript.Echo(args[0])
  465. var read = objShell.RegRead(args[0])
  466. try {
  467. var fs = new ActiveXObject('Scripting.FileSystemObject');
  468. var fh = fs.CreateTextFile('${outescaped}', true);
  469. fh.WriteLine(read);
  470. fh.Close();
  471. }
  472. catch(e){ WScript.Echo(e.message) }
  473. // WScript.Echo( read )
  474. }
  475. `
  476. )
  477. return nodeShellExec('cscript', [path.normalize(`${this.selectedinstance.root}/.elxr/run-${this.runtimestamp}/${uniquerun}-regread.js`), `${s}`])
  478. .then(read => {
  479. // console.log("REGREAD RESULT : " + read)
  480. // console.dir(read)
  481. if(read.success) {
  482. return (fs.readFileSync(out) + "").trim()
  483. }
  484. else throw 'regread failed'
  485. })
  486. }
  487. , iswin(){ return true}
  488. , islin(){ return false}
  489. }
  490. module.exports = shell_verse