Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

docusign-rooms

Package Overview
Dependencies
Maintainers
0
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

docusign-rooms - npm Package Compare versions

Comparing version 2.0.0 to 3.0.0

42

CHANGELOG.md

@@ -5,2 +5,44 @@ # DocuSign Node Client Changelog

## [v3.0.0] - Rooms API v2-1.1.1 - 2024-11-20
### Breaking Changes
<details>
<summary><b>Click here for change details</b></summary>
**Security Updates**
- Updated HTTP Client: Due to identified security vulnerabilities in Superagent proxy version 3.0.0, we have transitioned from using Superagent to the more secure Axios HTTP client. This update helps in safeguarding your interactions by patching potential security gaps.
**New Features**
- Proxy Support for HTTP Requests: We've introduced the ability to make HTTP requests through a proxy. This enhancement is particularly useful for users operating within corporate or restricted networks.
- JWT Token Request Functionality: The new sendJWTTokenRequest method allows you to obtain authentication tokens without exposing your privateKey. This method is designed to enhance security in your authentication processes.
**Changes to Existing Features**
- Updated Callback Response Structure: We have made changes to the response structure for callbacks. If you are using callback functions in your integration, please note the updated response object attributes:
> statusCode
header
body
**Migration Guide**
- For those using callback functions, please adjust your implementation to handle the new response structure as detailed above.
</details>
## [v2.0.0-rc3] - Rooms API v2-1.1.1 - 2024-04-24
### Changed
**Security Updates**
- Updated HTTP Client: Due to identified security vulnerabilities in Superagent proxy version 3.0.0, we have transitioned from using Superagent to the more secure Axios HTTP client. This update helps in safeguarding your interactions by patching potential security gaps.
**New Features**
- Proxy Support for HTTP Requests: We've introduced the ability to make HTTP requests through a proxy. This enhancement is particularly useful for users operating within corporate or restricted networks.
- JWT Token Request Functionality: The new sendJWTTokenRequest method allows you to obtain authentication tokens without exposing your privateKey. This method is designed to enhance security in your authentication processes.
**Changes to Existing Features**
- Updated Callback Response Structure: We have made changes to the response structure for callbacks. If you are using callback functions in your integration, please note the updated response object attributes:
> statusCode
header
body
**Migration Guide**
- For those using callback functions, please adjust your implementation to handle the new response structure as detailed above.
## [v2.0.0] - Rooms API v2-1.1.0 - 2023-01-23

@@ -7,0 +49,0 @@ ### Breaking

14

package.json
{
"name": "docusign-rooms",
"version": "2.0.0",
"version": "3.0.0",
"description": "DocuSign Node.js API client.",

@@ -53,8 +53,9 @@ "license": "MIT",

},
"dependencies": {
"dependencies": {
"axios": "^1.6.8",
"@devhigley/parse-proxy":"^1.0.3",
"csv-stringify": "^1.0.0",
"jsonwebtoken": "^9.0.0",
"passport-oauth2": "^1.6.1",
"safe-buffer": "^5.1.2",
"superagent": "3.8.2"
"jsonwebtoken": "^9.0.0",
"passport-oauth2": "^1.6.1",
"safe-buffer": "^5.1.2"
},

@@ -67,4 +68,5 @@ "devDependencies": {

"mocha-junit-reporter": "^1.18.0",
"pdf-parse-fork": "^1.2.0",
"semistandard": "^12.0.1"
}
}

@@ -19,3 +19,3 @@ # The Official DocuSign Rooms Node Client

## Requirements
- Node 4
- Node 12
- Free [Developer Account](https://go.docusign.com/sandbox/productshot/?elqCampaignId=16531)

@@ -26,3 +26,3 @@ - DocuSign Rooms account connected to your Developer account. [Here is how to create a Rooms developer account](https://developers.docusign.com/docs/rooms-api/rooms101/create-account)

- Node 4+
- Node 12+

@@ -48,3 +48,3 @@ ## Note:

- Superagent 3.8.2
- axios 1.6.8

@@ -51,0 +51,0 @@ ### Optional:

@@ -256,3 +256,3 @@ /**

* @param {Boolean} optsOrCallback.onlyAssignable Returns assignable roles based on calling user's company permissions. DEPRECATED: Please use filterContext parameter to get the assignable roles. AssignableRolesBasedOnCompanyPermissions returns same results as onlyAssignable=true (default to false)
* @param {Object} optsOrCallback.filterContext Attribute establishing filter context for roles being returned - AllRoles, AssignableRolesBasedOnCompanyPermissions, AssignableRolesBasedOnAllPermissions
* @param {module:model/String} optsOrCallback.filterContext Attribute establishing filter context for roles being returned - AllRoles, AssignableRolesBasedOnCompanyPermissions, AssignableRolesBasedOnAllPermissions
* @param {String} optsOrCallback.filter A search filter that returns roles by the beginning of the role name. You can enter the beginning of the role name only to return all of the roles that begin with the text that you entered.

@@ -259,0 +259,0 @@ * @param {Number} optsOrCallback.startPosition The starting zero-based index position of the result set. The default value is 0. (default to 0)

@@ -736,3 +736,3 @@ /**

* @param {String} optsOrCallback.filter Returns room users filtered by Name and Email.
* @param {Object} optsOrCallback.sort Sorts results. Options are FirstNameAsc, FirstNameDesc, LastNameAsc, LastNameDesc, EmailAsc, EmailDesc. Defaults to LastNameDesc
* @param {module:model/String} optsOrCallback.sort Sorts results. Options are FirstNameAsc, FirstNameDesc, LastNameAsc, LastNameDesc, EmailAsc, EmailDesc. Defaults to LastNameDesc
* @param {module:api/RoomsApi~getRoomUsersCallback} callback The callback function, accepting three arguments: error, data, response

@@ -810,3 +810,3 @@ * data is of type: {@link module:model/RoomUsersResult}

* @param {Number} optsOrCallback.startPosition Position of the first item in the total results. Defaults to 0. (default to 0)
* @param {Object} optsOrCallback.roomStatus Status of the rooms to return. Defaults to \"Active\".
* @param {module:model/String} optsOrCallback.roomStatus Status of the rooms to return. Defaults to \"Active\".
* @param {Number} optsOrCallback.officeId Only return rooms in this office.

@@ -813,0 +813,0 @@ * @param {String} optsOrCallback.fieldDataChangedStartDate Fields data changed start datetime in UTC. Valid formats: yyyy-mm-dd hh:mm:ss or yyyy/mm/dd hh:mm:ss -Time is optional and will default to 00:00:00.

@@ -261,5 +261,5 @@ /**

* @param {String} optsOrCallback.filter Filters by name and email
* @param {Object} optsOrCallback.sort Valid values are 'FirstNameAsc', 'FirstNameDesc', 'LastNameAsc', 'LastNameDesc', 'EmailAsc', 'EmailDesc'
* @param {module:model/String} optsOrCallback.sort Valid values are 'FirstNameAsc', 'FirstNameDesc', 'LastNameAsc', 'LastNameDesc', 'EmailAsc', 'EmailDesc'
* @param {Number} optsOrCallback.defaultOfficeId Default office ID
* @param {Object} optsOrCallback.accessLevel Valid values are 'Company', 'Region', 'Office', 'Contributor'
* @param {module:model/String} optsOrCallback.accessLevel Valid values are 'Company', 'Region', 'Office', 'Contributor'
* @param {Number} optsOrCallback.titleId Only valid for classic companies

@@ -266,0 +266,0 @@ * @param {Number} optsOrCallback.roleId Only valid for next gen companies

@@ -12,9 +12,13 @@ /**

(function(root, factory) {
if (typeof define === 'function' && define.amd) {
(function (root, factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(['superagent'], factory);
} else if (typeof module === 'object' && module.exports) {
define(["axios"], factory);
define(["@devhigley/parse-proxy"], factory);
} else if (typeof module === "object" && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('superagent'));
module.exports = factory(
require("axios"),
require("@devhigley/parse-proxy")
);
} else {

@@ -25,8 +29,19 @@ // Browser globals (root is window)

}
root.Docusign.ApiClient = factory(root.superagent, optsOrCallback);
root.Docusign.ApiClient = factory(root.axios, optsOrCallback);
}
}(this, function(superagent, optsOrCallback) {
'use strict';
})(this, function (axios, parseProxy, optsOrCallback) {
"use strict";
var removeNulls = function(obj) {
/*
* The default HTTP headers to be included for all API calls.
* @type {Array.<String>}
* @default {}
* */
var defaultHeaders = {
"X-DocuSign-SDK": "Node",
"Node-Ver": process.version,
"User-Agent": `Swagger-Codegen/node/${process.version}`,
};
var removeNulls = function (obj) {
var isArray = obj instanceof Array;

@@ -41,4 +56,11 @@ for (var k in obj) {

var generateAndSignJWTAssertion = function(clientId, scopes, privateKey, oAuthBasePath, expiresIn, userId) {
if(typeof expiresIn !== 'number' || expiresIn < 0)
var generateAndSignJWTAssertion = function (
clientId,
scopes,
privateKey,
oAuthBasePath,
expiresIn,
userId
) {
if (typeof expiresIn !== "number" || expiresIn < 0)
throw new Error("Invalid expires in param detected");

@@ -50,4 +72,4 @@

later = now + expiresIn,
jwt = require('jsonwebtoken'),
parsedScopes = Array.isArray(scopes) ? scopes.join(' ') : scopes;
jwt = require("jsonwebtoken"),
parsedScopes = Array.isArray(scopes) ? scopes.join(" ") : scopes;

@@ -63,3 +85,3 @@ var jwtPayload = {

/** optional parameters **/
if(userId) {
if (userId) {
jwtPayload.sub = userId;

@@ -70,39 +92,80 @@ }

var sendJWTTokenRequest = function (assertion, oAuthBasePath, callback) {
var request = superagent.post("https://" + oAuthBasePath + "/oauth/token")
.timeout(exports.prototype.timeout)
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Cache-Control', 'no-store')
.set('Pragma', 'no-cache')
.send({
'assertion': assertion,
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer'
var sendJWTTokenRequest = function (
assertion,
oAuthBasePath,
proxy,
callback
) {
const requestConfig = {
baseURL: `https://${oAuthBasePath}`,
method: "post",
url: "/oauth/token",
headers: {
...defaultHeaders,
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-store",
Pragma: "no-cache",
},
timeout: exports.prototype.timeout,
data: {
assertion: assertion,
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
},
};
if (proxy) {
const proxyObj = parseProxy(proxy);
requestConfig.proxy = proxyObj[0];
}
const oauthRequest = axios.request(requestConfig);
if (!callback) {
return new Promise(function (resolve, reject) {
oauthRequest
.then((response) => {
const stdResponse = normalizeResponseFormat(response);
resolve(stdResponse);
})
.catch((err) => {
const stdErrResponse = normalizeResponseFormat(err.response);
reject(stdErrResponse);
});
});
if (!callback){
return new Promise(function(resolve, reject){
request.end(function(err, data){
if (err){
reject(err);
} else {
resolve(data);
}
} else {
oauthRequest
.then((response) => {
const stdResponse = normalizeResponseFormat(response);
callback(null, stdResponse.body, stdResponse);
})
})
} else {
request.end(callback);
.catch((err) => {
const stdErrResponse = normalizeResponseFormat(err.response);
callback(stdErrResponse);
});
}
};
var deriveOAuthBasePathFromRestBasePath = function(basePath) {
const normalizeResponseFormat = (res) => {
if (res) {
const { data: body, headers: header, status: statusCode } = res;
return {
statusCode,
header,
body
};
}
return null;
};
var deriveOAuthBasePathFromRestBasePath = function (basePath) {
if (basePath == null) {
return exports.prototype.OAuth.BasePath.PRODUCTION;
}
if (basePath.includes('https://stage')) {
if (basePath.includes("https://stage")) {
return exports.prototype.OAuth.BasePath.STAGE;
}
if (basePath.includes('https://demo')) {
if (basePath.includes("https://demo")) {
return exports.prototype.OAuth.BasePath.DEMO;
}
if (basePath.includes('https://www.docusign')) {
if (basePath.includes("https://www.docusign")) {
return exports.prototype.OAuth.BasePath.PRODUCTION;

@@ -125,10 +188,12 @@ }

*/
var exports = function(optsOrCallback) {
var exports = function (optsOrCallback) {
var defaults = {
basePath: 'https://www.docusign.net/restapi'.replace(/\/+$/, ''),
oAuthBasePath: require('./OAuth').BasePath.PRODUCTION,
basePath: "https://www.docusign.net/restapi".replace(/\/+$/, ""),
oAuthBasePath: require("./OAuth").BasePath.PRODUCTION,
};
optsOrCallback = Object.assign({},defaults, optsOrCallback);
optsOrCallback.oAuthBasePath = deriveOAuthBasePathFromRestBasePath(optsOrCallback.basePath);
optsOrCallback = Object.assign({}, defaults, optsOrCallback);
optsOrCallback.oAuthBasePath = deriveOAuthBasePathFromRestBasePath(
optsOrCallback.basePath
);

@@ -154,12 +219,5 @@ /**

this.authentications = {
'docusignAccessCode': {type: 'oauth2'}
docusignAccessCode: { type: "oauth2" },
};
/**
* The default HTTP headers to be included for all API calls.
* @type {Array.<String>}
* @default {}
*/
this.defaultHeaders = { "X-DocuSign-SDK": "Node" };
/**
* The default HTTP timeout for all API calls.

@@ -172,2 +230,10 @@ * @type {Number}

/**
* The full URI for the desired proxy.
* A complete list of supported proxies can be found here: https://www.npmjs.com/package/proxy-agent.
* @type {String}
* @default
*/
this.proxy = optsOrCallback.proxy;
/**
* If set to false an additional timestamp parameter is added to all API GET calls to

@@ -206,3 +272,5 @@ * prevent browser caching

*/
exports.prototype.setOAuthBasePath = function setOAuthBasePath(oAuthBasePath) {
exports.prototype.setOAuthBasePath = function setOAuthBasePath(
oAuthBasePath
) {
this.oAuthBasePath = oAuthBasePath;

@@ -214,7 +282,20 @@ };

*/
exports.prototype.addDefaultHeader = function addDefaultHeader(header, value) {
this.defaultHeaders[header] = value;
exports.prototype.addDefaultHeader = function addDefaultHeader(
header,
value
) {
defaultHeaders[header] = value;
};
/**
* Sets default JWT authorization token for APIs.
*/
exports.prototype.setJWTToken = function setJWTToken(token) {
if(!token){
throw new Error("Missing the required parameter 'token' when calling setJWTToken.");
}
defaultHeaders["Authorization"] = `Bearer ${token}`;
};
/**
* Returns a string representation for an actual parameter.

@@ -224,5 +305,5 @@ * @param param The actual parameter.

*/
exports.prototype.paramToString = function(param) {
exports.prototype.paramToString = function (param) {
if (param == undefined || param == null) {
return '';
return "";
}

@@ -242,9 +323,9 @@ if (param instanceof Date) {

*/
exports.prototype.buildUrl = function(path, pathParams) {
exports.prototype.buildUrl = function (path, pathParams) {
if (!path.match(/^\//)) {
path = '/' + path;
path = "/" + path;
}
var url = this.basePath + path;
var _this = this;
url = url.replace(/\{([\w-]+)\}/g, function(fullMatch, key) {
url = url.replace(/\{([\w-]+)\}/g, function (fullMatch, key) {
var value;

@@ -272,4 +353,6 @@ if (pathParams.hasOwnProperty(key)) {

*/
exports.prototype.isJsonMime = function(contentType) {
return Boolean(contentType != null && contentType.match(/^application\/json(;.*)?$/i));
exports.prototype.isJsonMime = function (contentType) {
return Boolean(
contentType != null && contentType.match(/^application\/json(;.*)?$/i)
);
};

@@ -282,3 +365,3 @@

*/
exports.prototype.jsonPreferredMime = function(contentTypes) {
exports.prototype.jsonPreferredMime = function (contentTypes) {
for (var i = 0; i < contentTypes.length; i++) {

@@ -297,20 +380,22 @@ if (this.isJsonMime(contentTypes[i])) {

*/
exports.prototype.isFileParam = function(param) {
exports.prototype.isFileParam = function (param) {
// fs.ReadStream in Node.js (but not in runtime like browserify)
if (typeof window === 'undefined' &&
typeof require === 'function' &&
require('fs') &&
param instanceof require('fs').ReadStream) {
if (
typeof window === "undefined" &&
typeof require === "function" &&
require("fs") &&
param instanceof require("fs").ReadStream
) {
return true;
}
// Buffer in Node.js
if (typeof Buffer === 'function' && param instanceof Buffer) {
if (typeof Buffer === "function" && param instanceof Buffer) {
return true;
}
// Blob in browser
if (typeof Blob === 'function' && param instanceof Blob) {
if (typeof Blob === "function" && param instanceof Blob) {
return true;
}
// File in browser (it seems File object is also instance of Blob, but keep this for safe)
if (typeof File === 'function' && param instanceof File) {
if (typeof File === "function" && param instanceof File) {
return true;

@@ -331,6 +416,10 @@ }

*/
exports.prototype.normalizeParams = function(params) {
exports.prototype.normalizeParams = function (params) {
var newParams = {};
for (var key in params) {
if (params.hasOwnProperty(key) && params[key] != undefined && params[key] != null) {
if (
params.hasOwnProperty(key) &&
params[key] != undefined &&
params[key] != null
) {
var value = params[key];

@@ -357,3 +446,3 @@ if (this.isFileParam(value) || Array.isArray(value)) {

*/
CSV: ',',
CSV: ",",
/**

@@ -363,3 +452,3 @@ * Space-separated values. Value: <code>ssv</code>

*/
SSV: ' ',
SSV: " ",
/**

@@ -369,3 +458,3 @@ * Tab-separated values. Value: <code>tsv</code>

*/
TSV: '\t',
TSV: "\t",
/**

@@ -375,3 +464,3 @@ * Pipe(|)-separated values. Value: <code>pipes</code>

*/
PIPES: '|',
PIPES: "|",
/**

@@ -381,3 +470,3 @@ * Native array. Value: <code>multi</code>

*/
MULTI: 'multi'
MULTI: "multi",
};

@@ -392,3 +481,6 @@

*/
exports.prototype.buildCollectionParam = function buildCollectionParam(param, collectionFormat) {
exports.prototype.buildCollectionParam = function buildCollectionParam(
param,
collectionFormat
) {
if (param == null) {

@@ -398,15 +490,15 @@ return null;

switch (collectionFormat) {
case 'csv':
return param.map(this.paramToString).join(',');
case 'ssv':
return param.map(this.paramToString).join(' ');
case 'tsv':
return param.map(this.paramToString).join('\t');
case 'pipes':
return param.map(this.paramToString).join('|');
case 'multi':
// return the array directly as SuperAgent will handle it as expected
case "csv":
return param.map(this.paramToString).join(",");
case "ssv":
return param.map(this.paramToString).join(" ");
case "tsv":
return param.map(this.paramToString).join("\t");
case "pipes":
return param.map(this.paramToString).join("|");
case "multi":
// return the array directly as axios will handle it as expected
return param.map(this.paramToString);
default:
throw new Error('Unknown collection format: ' + collectionFormat);
throw new Error("Unknown collection format: " + collectionFormat);
}

@@ -417,37 +509,46 @@ };

* Applies authentication headers to the request.
* @param {Object} request The request object created by a <code>superagent()</code> call.
* @param {Object} requestConfig The request configuration object used for Axios Request.
* @param {Array.<String>} authNames An array of authentication method names.
*/
exports.prototype.applyAuthToRequest = function(request, authNames) {
exports.prototype.applyAuthToRequest = function (requestConfig, authNames) {
var _this = this;
authNames.forEach(function(authName) {
authNames.forEach(function (authName) {
var auth = _this.authentications[authName];
switch (auth.type) {
case 'basic':
case "basic":
if (auth.username || auth.password) {
request.auth(auth.username || '', auth.password || '');
requestConfig.auth = {
username: auth.username || "",
password: auth.password || "",
};
}
break;
case 'apiKey':
case "apiKey":
if (auth.apiKey) {
var data = {};
if (auth.apiKeyPrefix) {
data[auth.name] = auth.apiKeyPrefix + ' ' + auth.apiKey;
data[auth.name] = auth.apiKeyPrefix + " " + auth.apiKey;
} else {
data[auth.name] = auth.apiKey;
}
if (auth['in'] === 'header') {
request.set(data);
if (auth["in"] === "header") {
requestConfig.headers = {
...requestConfig.headers,
...data,
};
} else {
request.query(data);
requestConfig.params = { ...requestConfig.params, ...data };
}
}
break;
case 'oauth2':
case "oauth2":
if (auth.accessToken) {
request.set({'Authorization': 'Bearer ' + auth.accessToken});
requestConfig.headers = {
...requestConfig.headers,
Authorization: "Bearer " + auth.accessToken,
};
}
break;
default:
throw new Error('Unknown authentication type: ' + auth.type);
throw new Error("Unknown authentication type: " + auth.type);
}

@@ -459,3 +560,3 @@ });

* Deserializes an HTTP response body into a value of the specified type.
* @param {Object} response A SuperAgent response object.
* @param {Object} response An Axios response object.
* @param {(String|Array.<String>|Object.<String, Object>|Function)} returnType The type to return. Pass a string for simple types

@@ -471,9 +572,5 @@ * or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To

}
// Rely on SuperAgent for parsing response body.
// See http://visionmedia.github.io/superagent/#parsing-response-bodies
var data = response.body || (response.res && response.res.data);
if (data == null || !Object.keys(data).length) {
// SuperAgent does not always produce a body; use the unparsed response as a fallback
data = response.text;
}
// Rely on Axios Response Schema.
// See https://axios-http.com/docs/res_schema
var data = response.data;
return exports.convertToType(data, returnType);

@@ -505,53 +602,93 @@ };

* @param {module:ApiClient~callApiCallback} callback The callback function. If this is left undefined, this method will return a promise instead.
* @returns {Object} The SuperAgent request object if a callback is specified, else {Promise} A {@link https://www.promisejs.org/|Promise} object.
* @returns {Object} The Axios request object if a callback is specified, else {Promise} A {@link https://www.promisejs.org/|Promise} object.
*/
exports.prototype.callApi = function callApi(path, httpMethod, pathParams,
queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, accepts,
returnType, callback) {
exports.prototype.callApi = function callApi(
path,
httpMethod,
pathParams,
queryParams,
headerParams,
formParams,
bodyParam,
authNames,
contentTypes,
accepts,
returnType,
callback
) {
const conf = require("./Configuration");
var _this = this;
var url = this.buildUrl(path, pathParams);
var request = superagent(httpMethod, url);
const requestConfig = {
method: httpMethod,
url,
timeout: this.timeout,
paramsSerializer: {
indexes: null,
},
};
if (this.proxy) {
const proxyObj = parseProxy(this.proxy);
requestConfig.proxy = proxyObj[0];
}
var _formParams = this.normalizeParams(formParams);
var body =
httpMethod.toUpperCase() === "GET" && !bodyParam
? undefined
: bodyParam || {};
// apply authentications
this.applyAuthToRequest(request, authNames);
this.applyAuthToRequest(requestConfig, authNames);
// set query parameters
if (httpMethod.toUpperCase() === 'GET' && this.cache === false) {
queryParams['_'] = new Date().getTime();
if (httpMethod.toUpperCase() === "GET" && this.cache === false) {
queryParams["_"] = new Date().getTime();
}
request.query(this.normalizeParams(queryParams));
const _queryParams = this.normalizeParams(queryParams);
requestConfig.params = { ...requestConfig.params, ..._queryParams };
// set header parameters
request.set(this.defaultHeaders).set(this.normalizeParams(headerParams));
const _headerParams = this.normalizeParams(headerParams);
requestConfig.headers = {
...requestConfig.headers,
...defaultHeaders,
..._headerParams,
};
// set request timeout
request.timeout(this.timeout);
requestConfig.timeout = this.timeout;
var contentType = this.jsonPreferredMime(contentTypes);
if (contentType) {
// Issue with superagent and multipart/form-data (https://github.com/visionmedia/superagent/issues/746)
if(contentType != 'multipart/form-data') {
request.type(contentType);
if (contentType != "multipart/form-data") {
requestConfig.headers = {
...requestConfig.headers,
"Content-Type": contentType,
};
}
} else if (!request.header['Content-Type']) {
request.type('application/json');
} else if (!requestConfig.headers["Content-Type"]) {
requestConfig.headers = {
...requestConfig.headers,
"Content-Type": "application/json",
};
}
if (contentType === 'application/x-www-form-urlencoded') {
request.send(this.normalizeParams(formParams));
} else if (contentType == 'multipart/form-data') {
if (contentType === "application/x-www-form-urlencoded") {
//automatic serialization happens with axios. ref: https://axios-http.com/docs/urlencoded
requestConfig.data = this.normalizeParams(formParams);
} else if (contentType == "multipart/form-data") {
requestConfig.headers = {
...requestConfig.headers,
"Content-Type": "multipart/form-data",
};
//automatic serialization for formData is supported in axios as of 0.27.0. ref: https://axios-http.com/docs/multipart
var _formParams = this.normalizeParams(formParams);
for (var key in _formParams) {
if (_formParams.hasOwnProperty(key)) {
if (this.isFileParam(_formParams[key])) {
// file field
request.attach(key, _formParams[key]);
} else {
request.field(key, _formParams[key]);
}
}
}
} else if (bodyParam) {
request.send(removeNulls(bodyParam));
requestConfig.data = _formParams;
} else if (body) {
requestConfig.data = removeNulls(body);
}

@@ -561,56 +698,63 @@

if (accept) {
request.accept(accept);
requestConfig.headers = { ...requestConfig.headers, Accept: accept };
}
var data;
if (request.header['Accept'] === 'application/pdf') {
request.buffer();
data = '';
} else {
data = '';
if (requestConfig.headers["Accept"] === "application/pdf") {
requestConfig.responseType = "stream";
}
if (request.header['Accept'] === 'application/pdf') {
request.parse( function (res, fn) {
res.data = '';
res.setEncoding('binary');
res.on( 'data', function (chunk) { res.data += chunk; } );
res.on( 'end', function () {
try {
fn( null, res.data );
} catch ( err ) {
fn( err );
}
});
})
}
const request = axios.request(requestConfig);
var data = null;
if (!callback) {
return new Promise(function(resolve, reject){
request.end(function(error, data) {
if (error) {
reject(error);
} else {
return new Promise(function (resolve, reject) {
request
.then((response) => {
try {
data = _this.deserialize(data, returnType);
resolve(data);
} catch(error) {
reject(error);
let streamData;
if (requestConfig.headers["Accept"] === "application/pdf") {
response.data.on("data", (chunks) => {
streamData += chunks;
});
response.data.on("end", () => {
resolve(streamData);
});
} else {
data = _this.deserialize(response, returnType);
resolve(data);
}
} catch (err) {
reject(err);
}
}
})
})
.catch((err) => {
const stdErrResponse = normalizeResponseFormat(err.response);
reject(stdErrResponse);
});
});
} else {
request.end(function(error, response) {
if (!error) {
request
.then((response) => {
try {
data = _this.deserialize(response, returnType);
let streamData;
const stdResponse = normalizeResponseFormat(response);
if (requestConfig.headers["Accept"] === "application/pdf") {
response.data.on("data", (chunks) => {
streamData += chunks;
});
response.data.on("end", () => {
callback(null, streamData, stdResponse);
});
} else {
data = _this.deserialize(response, returnType);
callback(null, data, stdResponse);
}
} catch (err) {
error = err;
callback(err);
}
}
callback(error, data, response);
});
})
.catch((err) => {
const stdErrResponse = normalizeResponseFormat(err.response);
callback(stdErrResponse);
});
return request;

@@ -625,4 +769,4 @@ }

*/
exports.parseDate = function(str) {
return new Date(str.replace(/T/i, ' '));
exports.parseDate = function (str) {
return new Date(str.replace(/T/i, " "));
};

@@ -639,13 +783,13 @@

*/
exports.convertToType = function(data, type) {
exports.convertToType = function (data, type) {
switch (type) {
case 'Boolean':
case "Boolean":
return Boolean(data);
case 'Integer':
case "Integer":
return parseInt(data, 10);
case 'Number':
case "Number":
return parseFloat(data);
case 'String':
case "String":
return String(data);
case 'Date':
case "Date":
return this.parseDate(String(data));

@@ -656,3 +800,3 @@ default:

return data;
} else if (typeof type === 'function') {
} else if (typeof type === "function") {
// for model type like: User

@@ -663,6 +807,6 @@ return type.constructFromObject(data);

var itemType = type[0];
return data.map(function(item) {
return data.map(function (item) {
return exports.convertToType(item, itemType);
});
} else if (typeof type === 'object') {
} else if (typeof type === "object") {
// for plain object type like: {'String': 'Integer'}

@@ -698,3 +842,3 @@ var keyType, valueType;

*/
exports.constructFromObject = function(data, obj, itemType) {
exports.constructFromObject = function (data, obj, itemType) {
if (Array.isArray(data)) {

@@ -726,19 +870,32 @@ for (var i = 0; i < data.length; i++) {

*/
exports.prototype.getAuthorizationUri = function(clientId, scopes, redirectUri, responseType, state) {
if (!clientId) throw new Error('Error clientId is required');
if (!scopes) throw new Error('Error scopes is required');
if (!scopes) throw new Error('Error scopes is required');
if (!this.hasNoInvalidScopes(scopes)) throw new Error('Error invalid scope detected');
if (!redirectUri) throw new Error('Error redirectUri is required');
if (!responseType) throw new Error('Error responseType is required');
exports.prototype.getAuthorizationUri = function (
clientId,
scopes,
redirectUri,
responseType,
state
) {
if (!clientId) throw new Error("Error clientId is required");
if (!scopes) throw new Error("Error scopes is required");
if (!scopes) throw new Error("Error scopes is required");
if (!this.hasNoInvalidScopes(scopes))
throw new Error("Error invalid scope detected");
if (!redirectUri) throw new Error("Error redirectUri is required");
if (!responseType) throw new Error("Error responseType is required");
var formattedScopes = scopes.join(encodeURI(' '));
return "https://" +
var formattedScopes = scopes.join(encodeURI(" "));
return (
"https://" +
this.getOAuthBasePath() +
"/oauth/auth"+
"?response_type=" + responseType +
"&scope=" + formattedScopes +
"&client_id="+ clientId +
"&redirect_uri=" + encodeURIComponent(redirectUri) +
(state ? "&state=" + state : '');
"/oauth/auth" +
"?response_type=" +
responseType +
"&scope=" +
formattedScopes +
"&client_id=" +
clientId +
"&redirect_uri=" +
encodeURIComponent(redirectUri) +
(state ? "&state=" + state : "")
);
};

@@ -753,43 +910,63 @@

*/
exports.prototype.generateAccessToken = function(clientId, clientSecret, code, callback) {
if (!clientId) throw new Error('Error clientId is required', null);
if (!clientSecret) throw new Error('Error clientSecret is required', null);
if (!code) throw new Error('Error code is required', null);
exports.prototype.generateAccessToken = function (
clientId,
clientSecret,
code,
callback
) {
if (!clientId) throw new Error("Error clientId is required", null);
if (!clientSecret) throw new Error("Error clientSecret is required", null);
if (!code) throw new Error("Error code is required", null);
var clientString = clientId + ":" + clientSecret,
postData = {
"grant_type": "authorization_code",
grant_type: "authorization_code",
code: code,
},
headers = {
"Authorization": "Basic " + (new Buffer(clientString).toString('base64')),
Authorization: "Basic " + new Buffer(clientString).toString("base64"),
"Cache-Control": "no-store",
"Pragma": "no-cache"
Pragma: "no-cache",
...defaultHeaders,
},
OAuthToken = require('./OAuth').OAuthToken,
request = superagent.post("https://" + this.getOAuthBasePath() + "/oauth/token")
.send(postData)
.set(headers)
.type("application/x-www-form-urlencoded");
OAuthToken = require("./OAuth").OAuthToken;
const requestConfig = {
baseURL: `https://${oAuthBasePath}`,
method: "post",
url: "/oauth/token",
headers: {
...headers,
"Content-Type": "application/x-www-form-urlencoded",
},
data: postData,
};
const request = axios.request(requestConfig);
if (!callback) {
return new Promise(function (resolve, reject) {
request.end(function (err, res) {
if (err) {
reject(err);
} else {
resolve(OAuthToken.constructFromObject(res.body))
}
});
request
.then((response) => {
resolve(OAuthToken.constructFromObject(response.data));
})
.catch((err) => {
const stdErrResponse = normalizeResponseFormat(err.response);
reject(stdErrResponse);
});
});
} else {
request.end(function (err, res) {
var OAuthToken;
if (err) {
return callback(err, res);
} else {
OAuthToken = require('./OAuth').OAuthToken;
return callback(err, OAuthToken.constructFromObject(res.body))
}
});
request
.then((response) => {
let OAuthToken = require("./OAuth").OAuthToken;
const stdResponse = normalizeResponseFormat(response);
return callback(
null,
OAuthToken.constructFromObject(response.data),
stdResponse
);
})
.catch((err) => {
const stdErrResponse = normalizeResponseFormat(err.response);
return callback(stdErrResponse);
});
}

@@ -802,26 +979,35 @@ };

*/
exports.prototype.getUserInfo = function(accessToken, callback) {
if(!accessToken) throw new Error('Error accessToken is required',null);
exports.prototype.getUserInfo = function (accessToken, callback) {
if (!accessToken) throw new Error("Error accessToken is required", null);
var headers = {
"Authorization": "Bearer " + accessToken,
Authorization: "Bearer " + accessToken,
"Cache-Control": "no-store",
"Pragma": "no-cache"
Pragma: "no-cache",
...defaultHeaders,
};
const requestConfig = {
baseURL: `https://${this.oAuthBasePath}`,
method: "get",
url: "/oauth/userinfo",
headers: headers,
};
if (this.proxy) {
const proxyObj = parseProxy(this.proxy);
requestConfig.proxy = proxyObj[0];
}
var request = superagent.get("https://" + this.getOAuthBasePath() + "/oauth/userinfo").set(headers);
var UserInfo = require('./OAuth').UserInfo;
const request = axios.request(requestConfig);
var UserInfo = require("./OAuth").UserInfo;
if(!callback) {
if (!callback) {
try {
return new Promise(function (resolve, reject) {
request.end(function (err, res) {
if (err) {
reject(err);
} else {
try {
resolve(UserInfo.constructFromObject(res.body));
} catch (error) {
reject(error);
}
request.then((response) => {
try {
return resolve(UserInfo.constructFromObject(response.data));
} catch (error) {
throw error;
}

@@ -831,13 +1017,19 @@ });

} catch (err) {
console.log(err)
throw(err)
console.log(err);
reject(err);
}
} else {
request.end(function (err, res) {
if (err) {
return callback(err, res);
} else {
return callback(err, UserInfo.constructFromObject(res.body));
}
});
request
.then((response) => {
const stdResponse = normalizeResponseFormat(response);
return callback(
null,
UserInfo.constructFromObject(response.data),
stdResponse
);
})
.catch((err) => {
const stdErrResponse = normalizeResponseFormat(err.response);
return callback(stdErrResponse);
});
}

@@ -854,8 +1046,24 @@ };

*/
exports.prototype.getJWTUri = function(clientId, redirectURI, oAuthBasePath) {
return "https://" + oAuthBasePath + "/oauth/auth" + "?" +
exports.prototype.getJWTUri = function (
clientId,
redirectURI,
oAuthBasePath
) {
return (
"https://" +
oAuthBasePath +
"/oauth/auth" +
"?" +
"response_type=code&" +
"client_id=" + encodeURIComponent(clientId) + "&" +
"scope=" + encodeURIComponent("signature impersonation dtr.company.write dtr.company.read dtr.rooms.write dtr.rooms.read") + "&" +
"redirect_uri=" + encodeURIComponent(redirectURI);
"client_id=" +
encodeURIComponent(clientId) +
"&" +
"scope=" +
encodeURIComponent(
"signature impersonation dtr.company.write dtr.company.read dtr.rooms.write dtr.rooms.read"
) +
"&" +
"redirect_uri=" +
encodeURIComponent(redirectURI)
);
};

@@ -874,10 +1082,19 @@

*/
exports.prototype.configureJWTAuthorizationFlow = function(privateKeyFilename, oAuthBasePath, clientId, userId, expiresIn, callback) {
console.warn('configureJWTAuthorizationFlow is a deprecated function! Please use requestJWTUserToken()')
exports.prototype.configureJWTAuthorizationFlow = function (
privateKeyFilename,
oAuthBasePath,
clientId,
userId,
expiresIn,
callback
) {
console.warn(
"configureJWTAuthorizationFlow is a deprecated function! Please use requestJWTUserToken()"
);
var _this = this;
var jwt = require('jsonwebtoken')
, fs = require('fs')
, private_key = fs.readFileSync(privateKeyFilename)
, now = Math.floor(Date.now() / 1000)
, later = now + expiresIn;
var jwt = require("jsonwebtoken"),
fs = require("fs"),
private_key = fs.readFileSync(privateKeyFilename),
now = Math.floor(Date.now() / 1000),
later = now + expiresIn;

@@ -890,36 +1107,57 @@ var jwt_payload = {

exp: later,
scope: "signature"
scope: SCOPE_SIGNATURE,
};
var assertion = jwt.sign(jwt_payload, private_key, {algorithm: 'RS256'});
var assertion = jwt.sign(jwt_payload, private_key, { algorithm: "RS256" });
superagent('post', 'https://' + this.getOAuthBasePath() + '/oauth/token')
.timeout(this.timeout)
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Cache-Control', 'no-store')
.set('Pragma', 'no-cache')
.send({
'assertion': assertion,
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer'
})
.end(function(err, res) {
if (callback) {
if (!err && res.body && res.body.access_token) {
_this.addDefaultHeader('Authorization', 'Bearer ' + res.body.access_token);
}
callback(err, res);
const requestConfig = {
baseURL: `https://${oAuthBasePath}`,
method: "post",
url: "/oauth/token",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-store",
Pragma: "no-cache",
...defaultHeaders,
},
timeout: this.timeout,
data: {
assertion: assertion,
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
},
};
const request = axios.request(requestConfig);
const onSuccess = (response) => {
if (callback) {
if (response.data && response.data.access_token) {
_this.addDefaultHeader(
"Authorization",
"Bearer " + response.data.access_token
);
}
});
const stdResponse = normalizeResponseFormat(response);
callback(null, stdResponse.body, stdResponse);
}
};
const onFailure = (err) => {
if (callback) {
const stdErrResponse = normalizeResponseFormat(err.response);
callback(stdErrResponse);
}
};
request.then(onSuccess, onFailure);
};
exports.prototype.hasNoInvalidScopes = function(scopes) {
var validScopes = require('./oauth/Scope');
exports.prototype.hasNoInvalidScopes = function (scopes) {
var validScopes = require("./oauth/Scope");
return (
Array.isArray(scopes)
&& scopes.length > 0
&& scopes.every(function(scope){
return Object.keys(validScopes).some(function(key){
Array.isArray(scopes) &&
scopes.length > 0 &&
scopes.every(function (scope) {
return Object.keys(validScopes).some(function (key) {
return validScopes[key] === scope;
})
});
})

@@ -929,18 +1167,63 @@ );

exports.prototype.requestJWTUserToken = function(clientId, userId, scopes, rsaPrivateKey, expiresIn, callback) {
exports.prototype.sendJWTTokenRequest = function (assertion, callback) {
return sendJWTTokenRequest(
assertion,
this.oAuthBasePath,
this.proxy,
callback
);
};
exports.prototype.requestJWTUserToken = function (
clientId,
userId,
scopes,
rsaPrivateKey,
expiresIn,
callback
) {
var privateKey = rsaPrivateKey,
assertion = generateAndSignJWTAssertion(clientId, scopes, privateKey, this.getOAuthBasePath(), expiresIn, userId);
assertion = generateAndSignJWTAssertion(
clientId,
scopes,
privateKey,
this.getOAuthBasePath(),
expiresIn,
userId
);
return sendJWTTokenRequest(assertion, this.oAuthBasePath, callback);
return sendJWTTokenRequest(
assertion,
this.oAuthBasePath,
this.proxy,
callback
);
};
exports.prototype.requestJWTApplicationToken = function(clientId, scopes, rsaPrivateKey, expiresIn, callback) {
exports.prototype.requestJWTApplicationToken = function (
clientId,
scopes,
rsaPrivateKey,
expiresIn,
callback
) {
var privateKey = rsaPrivateKey,
assertion = generateAndSignJWTAssertion(clientId, scopes, privateKey, this.getOAuthBasePath(), expiresIn);
assertion = generateAndSignJWTAssertion(
clientId,
scopes,
privateKey,
this.getOAuthBasePath(),
expiresIn
);
return sendJWTTokenRequest(assertion, this.oAuthBasePath, callback);
return sendJWTTokenRequest(
assertion,
this.oAuthBasePath,
this.proxy,
callback
);
};
exports.prototype.OAuth = require('./OAuth');
exports.prototype.RestApi = require('./RestApi');
exports.prototype.OAuth = require("./OAuth");
exports.prototype.RestApi = require("./RestApi");
/**

@@ -953,5 +1236,5 @@ * The default API client implementation.

return exports;
}));
});
module.exports.OAuth = require('./OAuth');
module.exports.RestApi = require('./RestApi');
module.exports.OAuth = require("./OAuth");
module.exports.RestApi = require("./RestApi");
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc