|
| 1 | +var request = require('request'); |
| 2 | +var debug = require('debug')('jsforce-ajax-proxy'); |
| 3 | + |
| 4 | +/** |
| 5 | + * Allowed request headers |
| 6 | + */ |
| 7 | +var ALLOWED_HEADERS = [ |
| 8 | + 'Authorization', |
| 9 | + 'Content-Type', |
| 10 | + 'Salesforceproxy-Endpoint', |
| 11 | + 'X-Authorization', |
| 12 | + 'X-SFDC-Session', |
| 13 | + 'SOAPAction', |
| 14 | + 'SForce-Auto-Assign', |
| 15 | + 'If-Modified-Since', |
| 16 | + 'X-User-Agent' |
| 17 | +]; |
| 18 | + |
| 19 | +/** |
| 20 | + * Endpoint URL validation |
| 21 | + */ |
| 22 | +var SF_ENDPOINT_REGEXP = |
| 23 | + /^https:\/\/[a-zA-Z0-9\.\-]+\.(force|salesforce|cloudforce|database)\.com\//; |
| 24 | + |
| 25 | +/** |
| 26 | + * Create middleware to proxy request to salesforce server |
| 27 | + */ |
| 28 | +module.exports = function(options) { |
| 29 | + |
| 30 | + options = options || {} |
| 31 | + var proxyCounter = 0; |
| 32 | + |
| 33 | + return function(req, res) { |
| 34 | + if (options.enableCORS) { |
| 35 | + res.header('Access-Control-Allow-Origin', options.allowedOrigin || '*'); |
| 36 | + res.header('Access-Control-Allow-Methods', 'GET,POST,PATCH,PUT,DELETE'); |
| 37 | + res.header('Access-Control-Allow-Headers', ALLOWED_HEADERS.join(',')); |
| 38 | + res.header('Access-Control-Expose-Headers', 'SForce-Limit-Info'); |
| 39 | + if (req.method === 'OPTIONS') { |
| 40 | + res.end(); |
| 41 | + return; |
| 42 | + } |
| 43 | + } |
| 44 | + var sfEndpoint = req.headers["salesforceproxy-endpoint"]; |
| 45 | + if (!SF_ENDPOINT_REGEXP.test(sfEndpoint)) { |
| 46 | + res.send(400, "Proxying endpoint is not allowed."); |
| 47 | + return; |
| 48 | + } |
| 49 | + var headers = {}; |
| 50 | + ALLOWED_HEADERS.forEach(function(header) { |
| 51 | + header = header.toLowerCase(); |
| 52 | + var value = req.headers[header] |
| 53 | + if (value) { |
| 54 | + var name = header === 'x-authorization' ? 'authorization' : header; |
| 55 | + headers[name] = req.headers[header]; |
| 56 | + } |
| 57 | + }); |
| 58 | + var params = { |
| 59 | + url: sfEndpoint || "https://login.salesforce.com//services/oauth2/token", |
| 60 | + method: req.method, |
| 61 | + headers: headers |
| 62 | + }; |
| 63 | + proxyCounter++; |
| 64 | + debug("(++req++) " + new Array(proxyCounter+1).join('*')); |
| 65 | + debug("method=" + params.method + ", url=" + params.url); |
| 66 | + req.pipe(request(params)) |
| 67 | + .on('response', function() { |
| 68 | + proxyCounter--; |
| 69 | + debug("(--res--) " + new Array(proxyCounter+1).join('*')); |
| 70 | + }) |
| 71 | + .on('error', function() { |
| 72 | + proxyCounter--; |
| 73 | + debug("(--err--) " + new Array(proxyCounter+1).join('*')); |
| 74 | + }) |
| 75 | + .pipe(res); |
| 76 | + } |
| 77 | +}; |
0 commit comments