-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.js
More file actions
109 lines (86 loc) · 2.79 KB
/
command.js
File metadata and controls
109 lines (86 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
const { spawnSync } = require('child_process');
// Credits to mgcrea/node-openssl-wrapper for these regex:
const expectedStderrForAction = {
'cms': { "verify": /^verification successful/i },
'genrsa': /^generating/i,
'pkcs12': /^mac verified ok/i,
'req': { "new": /^generating/i },
'req': { "verify": /^verify ok/i },
'rsa': /^writing rsa key/i,
'smime': { "verify": /^verification successful/i },
'x509': { "req": /^signature ok/i }
};
class OpenSSLError extends Error {
constructor(args){
super(args);
this.name = this.code = "OpenSSLError";
}
}
function checkOpenSSLError(args, result) {
let expectedStderr = expectedStderrForAction[args[0]];
if (expectedStderr && !(expectedStderr instanceof RegExp)) {
expectedStderr = expectedStderr[args[1]];
}
if (result.status || (result.stderr && expectedStderr && !result.stderr.toString().match(expectedStderr))) {
throw new OpenSSLError(result.stderr.toString());
}
}
class Command {
constructor(opensslBin) {
this._stdin = "";
this._command = opensslBin || "openssl";
}
cmd(...params) {
if (params.length == 1)
this._args = params[0].replace(/^\s+/g, '').replace(/\s+$/g, '').split(/\s+/);
else
this._args = params;
// exec() ONLY EXISTS AFTER cmd() IS CALLED
this.exec = function (throwOnOpenSSLError) {
let result = spawnSync(this._command, this._args, { input: this._stdin });
if (result.error)
throw result.error;
if (throwOnOpenSSLError) {
checkOpenSSLError(this._args, result);
}
return new Executed(result);
}
return this;
}
stdin(input) {
this._stdin = input;
return this;
}
}
class Executed extends Command {
constructor(spawned) {
super();
this._rawstdout = spawned.stdout;
this._rawstderr = spawned.stderr;
this._status = spawned.status;
this._stdout = spawned.stdout.toString();
this._stderr = spawned.stderr.toString();
this._stdin = this._stdout.toString(); // PIPE
delete this.stdin; // DON'T ALLOW PIPE REWRITE
delete this.exec; // exec() ONLY EXISTS AFTER cmd() IS CALLED
}
get status() {
return this._status;
}
get stdout() {
return this._stdout;
}
get rawstdout() {
return this._rawstdout;
}
get stderr() {
return this._stderr;
}
get rawstderr() {
return this._rawstderr;
}
get pipe() {
return this; // This is just a syntax aid
}
}
module.exports = { Command, Executed };