-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathproxy.js
More file actions
81 lines (76 loc) · 2.35 KB
/
proxy.js
File metadata and controls
81 lines (76 loc) · 2.35 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
var request = require('request');
var debug = require('debug')('jsforce-ajax-proxy');
/**
* Allowed request headers
*/
var ALLOWED_HEADERS = [
'Authorization',
'Content-Type',
'Salesforceproxy-Endpoint',
'X-Authorization',
'X-SFDC-Session',
'SOAPAction',
'SForce-Auto-Assign',
'If-Modified-Since',
'X-User-Agent',
'X-Proxy-Authorization'
];
/**
* Endpoint URL validation
*/
var SF_ENDPOINT_REGEXP =
/^https:\/\/[a-zA-Z0-9\.\-]+\.(force|salesforce|cloudforce|database)\.com\//;
/**
* Create middleware to proxy request to salesforce server
*/
module.exports = function(options) {
options = options || {}
var proxyCounter = 0;
return function(req, res) {
if (options.enableCORS) {
res.header('Access-Control-Allow-Origin', options.allowedOrigin || '*');
res.header('Access-Control-Allow-Methods', 'GET,POST,PATCH,PUT,DELETE');
res.header('Access-Control-Allow-Headers', ALLOWED_HEADERS.join(','));
res.header('Access-Control-Expose-Headers', 'SForce-Limit-Info');
if (req.method === 'OPTIONS') {
res.end();
return;
}
}
var sfEndpoint = req.headers["salesforceproxy-endpoint"];
if (!SF_ENDPOINT_REGEXP.test(sfEndpoint)) {
res.send(400, "Proxying endpoint is not allowed. `salesforceproxy-endpoint` header must be a valid Salesforce domain: " + sfEndpoint);
return;
}
var headers = {};
ALLOWED_HEADERS.forEach(function(header) {
header = header.toLowerCase();
var value = req.headers[header]
if (value) {
var name = header === 'x-authorization' ? 'authorization' : header;
headers[name] = req.headers[header];
}
});
if (headers['x-proxy-authorization']) {
delete headers['x-proxy-authorization'];
}
var params = {
url: sfEndpoint || "https://login.salesforce.com//services/oauth2/token",
method: req.method,
headers: headers
};
proxyCounter++;
debug("(++req++) " + new Array(proxyCounter+1).join('*'));
debug("method=" + params.method + ", url=" + params.url);
req.pipe(request(params))
.on('response', function() {
proxyCounter--;
debug("(--res--) " + new Array(proxyCounter+1).join('*'));
})
.on('error', function() {
proxyCounter--;
debug("(--err--) " + new Array(proxyCounter+1).join('*'));
})
.pipe(res);
}
};