n8n/packages/nodes-base/nodes/Wise/GenericFunctions.ts

209 lines
5.6 KiB
TypeScript
Raw Normal View History

2022-03-06 02:41:01 -08:00
import {
createSign,
} from 'crypto';
import {
IExecuteFunctions,
IHookFunctions,
} from 'n8n-core';
import {
IDataObject,
2022-03-06 02:41:01 -08:00
IHttpRequestOptions,
ILoadOptionsFunctions,
INodeExecutionData,
:sparkles: Improve node error handling (#1309) * Add path mapping and response error interfaces * Add error handling and throwing functionality * Refactor error handling into a single function * Re-implement error handling in Hacker News node * Fix linting details * Re-implement error handling in Spotify node * Re-implement error handling in G Suite Admin node * :construction: create basic setup NodeError * :construction: add httpCodes * :construction: add path priolist * :construction: handle statusCode in error, adjust interfaces * :construction: fixing type issues w/Ivan * :construction: add error exploration * 👔 fix linter issues * :wrench: improve object check * :construction: remove path passing from NodeApiError * :construction: add multi error + refactor findProperty method * 👔 allow any * :wrench: handle multi error message callback * :zap: change return type of callback * :zap: add customCallback to MultiError * :construction: refactor to use INode * :hammer: handle arrays, continue search after first null property found * 🚫 refactor method access * :construction: setup NodeErrorView * :zap: change timestamp to Date.now * :books: Add documentation for methods and constants * :construction: change message setting * 🚚 move NodeErrors to workflow * :sparkles: add new ErrorView for Nodes * :art: improve error notification * :art: refactor interfaces * :zap: add WorkflowOperationError, refactor error throwing * 👕 fix linter issues * :art: rename param * :bug: fix handling normal errors * :zap: add usage of NodeApiError * :art: fix throw new error instead of constructor * :art: remove unnecessary code/comments * :art: adjusted spacing + updated status messages * :art: fix tab indentation * ✨ Replace current errors with custom errors (#1576) * :zap: Introduce NodeApiError in catch blocks * :zap: Introduce NodeOperationError in nodes * :zap: Add missing errors and remove incompatible * :zap: Fix NodeOperationError in incompatible nodes * :wrench: Adjust error handling in missed nodes PayPal, FileMaker, Reddit, Taiga and Facebook Graph API nodes * :hammer: Adjust Strava Trigger node error handling * :hammer: Adjust AWS nodes error handling * :hammer: Remove duplicate instantiation of NodeApiError * :bug: fix strava trigger node error handling * Add XML parsing to NodeApiError constructor (#1633) * :bug: Remove type annotation from catch variable * :sparkles: Add XML parsing to NodeApiError * :zap: Simplify error handling in Rekognition node * :zap: Pass in XML flag in generic functions * :fire: Remove try/catch wrappers at call sites * :hammer: Refactor setting description from XML * :hammer: Refactor let to const in resource loaders * :zap: Find property in parsed XML * :zap: Change let to const * :fire: Remove unneeded try/catch block * :shirt: Fix linting issues * :bug: Fix errors from merge conflict resolution * :zap: Add custom errors to latest contributions * :shirt: Fix linting issues * :zap: Refactor MongoDB helpers for custom errors * :bug: Correct custom error type * :zap: Apply feedback to A nodes * :zap: Apply feedback to missed A node * :zap: Apply feedback to B-D nodes * :zap: Apply feedback to E-F nodes * :zap: Apply feedback to G nodes * :zap: Apply feedback to H-L nodes * :zap: Apply feedback to M nodes * :zap: Apply feedback to P nodes * :zap: Apply feedback to R nodes * :zap: Apply feedback to S nodes * :zap: Apply feedback to T nodes * :zap: Apply feedback to V-Z nodes * :zap: Add HTTP code to iterable node error * :hammer: Standardize e as error * :hammer: Standardize err as error * :zap: Fix error handling for non-standard nodes Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <1849459+BHesseldieck@users.noreply.github.com>
2021-04-16 09:33:36 -07:00
NodeApiError,
} from 'n8n-workflow';
/**
* Make an authenticated API request to Wise.
*/
export async function wiseApiRequest(
this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions,
2022-03-06 02:41:01 -08:00
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'PATCH',
endpoint: string,
body: IDataObject = {},
qs: IDataObject = {},
option: IDataObject = {},
) {
2022-03-06 02:41:01 -08:00
const { apiToken, environment, privateKey } = await this.getCredentials('wiseApi') as {
apiToken: string,
environment: 'live' | 'test',
2022-03-06 02:41:01 -08:00
privateKey?: string,
};
const rootUrl = environment === 'live'
? 'https://api.transferwise.com/'
: 'https://api.sandbox.transferwise.tech/';
2022-03-06 02:41:01 -08:00
const options: IHttpRequestOptions = {
headers: {
'user-agent': 'n8n',
'Authorization': `Bearer ${apiToken}`,
},
method,
2022-03-06 02:41:01 -08:00
url: `${rootUrl}${endpoint}`,
qs,
body,
json: true,
2022-03-06 02:41:01 -08:00
returnFullResponse: true,
ignoreHttpStatusErrors: true,
};
if (!Object.keys(body).length) {
delete options.body;
}
if (!Object.keys(qs).length) {
delete options.qs;
}
if (Object.keys(option)) {
Object.assign(options, option);
}
2022-03-06 02:41:01 -08:00
let response;
try {
2022-03-06 02:41:01 -08:00
response = await this.helpers.httpRequest!(options);
} catch (error) {
2022-03-06 02:41:01 -08:00
delete error.config;
:sparkles: Improve node error handling (#1309) * Add path mapping and response error interfaces * Add error handling and throwing functionality * Refactor error handling into a single function * Re-implement error handling in Hacker News node * Fix linting details * Re-implement error handling in Spotify node * Re-implement error handling in G Suite Admin node * :construction: create basic setup NodeError * :construction: add httpCodes * :construction: add path priolist * :construction: handle statusCode in error, adjust interfaces * :construction: fixing type issues w/Ivan * :construction: add error exploration * 👔 fix linter issues * :wrench: improve object check * :construction: remove path passing from NodeApiError * :construction: add multi error + refactor findProperty method * 👔 allow any * :wrench: handle multi error message callback * :zap: change return type of callback * :zap: add customCallback to MultiError * :construction: refactor to use INode * :hammer: handle arrays, continue search after first null property found * 🚫 refactor method access * :construction: setup NodeErrorView * :zap: change timestamp to Date.now * :books: Add documentation for methods and constants * :construction: change message setting * 🚚 move NodeErrors to workflow * :sparkles: add new ErrorView for Nodes * :art: improve error notification * :art: refactor interfaces * :zap: add WorkflowOperationError, refactor error throwing * 👕 fix linter issues * :art: rename param * :bug: fix handling normal errors * :zap: add usage of NodeApiError * :art: fix throw new error instead of constructor * :art: remove unnecessary code/comments * :art: adjusted spacing + updated status messages * :art: fix tab indentation * ✨ Replace current errors with custom errors (#1576) * :zap: Introduce NodeApiError in catch blocks * :zap: Introduce NodeOperationError in nodes * :zap: Add missing errors and remove incompatible * :zap: Fix NodeOperationError in incompatible nodes * :wrench: Adjust error handling in missed nodes PayPal, FileMaker, Reddit, Taiga and Facebook Graph API nodes * :hammer: Adjust Strava Trigger node error handling * :hammer: Adjust AWS nodes error handling * :hammer: Remove duplicate instantiation of NodeApiError * :bug: fix strava trigger node error handling * Add XML parsing to NodeApiError constructor (#1633) * :bug: Remove type annotation from catch variable * :sparkles: Add XML parsing to NodeApiError * :zap: Simplify error handling in Rekognition node * :zap: Pass in XML flag in generic functions * :fire: Remove try/catch wrappers at call sites * :hammer: Refactor setting description from XML * :hammer: Refactor let to const in resource loaders * :zap: Find property in parsed XML * :zap: Change let to const * :fire: Remove unneeded try/catch block * :shirt: Fix linting issues * :bug: Fix errors from merge conflict resolution * :zap: Add custom errors to latest contributions * :shirt: Fix linting issues * :zap: Refactor MongoDB helpers for custom errors * :bug: Correct custom error type * :zap: Apply feedback to A nodes * :zap: Apply feedback to missed A node * :zap: Apply feedback to B-D nodes * :zap: Apply feedback to E-F nodes * :zap: Apply feedback to G nodes * :zap: Apply feedback to H-L nodes * :zap: Apply feedback to M nodes * :zap: Apply feedback to P nodes * :zap: Apply feedback to R nodes * :zap: Apply feedback to S nodes * :zap: Apply feedback to T nodes * :zap: Apply feedback to V-Z nodes * :zap: Add HTTP code to iterable node error * :hammer: Standardize e as error * :hammer: Standardize err as error * :zap: Fix error handling for non-standard nodes Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <1849459+BHesseldieck@users.noreply.github.com>
2021-04-16 09:33:36 -07:00
throw new NodeApiError(this.getNode(), error);
}
2022-03-06 02:41:01 -08:00
if (response.statusCode >= 200 && response.statusCode < 300) {
2022-03-06 02:41:01 -08:00
return response.body;
}
// Request requires SCA approval
if (response.statusCode === 403 && response.headers['x-2fa-approval']) {
if (!privateKey) {
throw new NodeApiError(this.getNode(), {
message: 'This request requires Strong Customer Authentication (SCA). Please add a key pair to your account and n8n credentials. See https://api-docs.transferwise.com/#strong-customer-authentication-personal-token',
headers: response.headers,
body: response.body,
});
}
// Sign the x-2fa-approval
const oneTimeToken = response.headers['x-2fa-approval'] as string;
const signerObject = createSign('RSA-SHA256').update(oneTimeToken);
try {
const signature = signerObject.sign(
privateKey,
'base64',
);
delete option.ignoreHttpStatusErrors;
options.headers = {
...options.headers,
'X-Signature': signature,
'x-2fa-approval': oneTimeToken,
};
} catch (error) {
throw new NodeApiError(this.getNode(), {message: 'Error signing SCA request, check your private key', ...error});
}
// Retry the request with signed token
try {
response = await this.helpers.httpRequest!(options);
return response.body;
} catch (error) {
throw new NodeApiError(this.getNode(), {message: 'SCA request failed, check your private key is valid'});
}
} else {
throw new NodeApiError(this.getNode(), { ...response, message: response.statusMessage });
2022-03-06 02:41:01 -08:00
}
}
/**
* Populate the binary property of node items with binary data for a PDF file.
*/
export async function handleBinaryData(
this: IExecuteFunctions,
items: INodeExecutionData[],
i: number,
endpoint: string,
) {
const data = await wiseApiRequest.call(this, 'GET', endpoint, {}, {}, { encoding: null });
const binaryProperty = this.getNodeParameter('binaryProperty', i) as string;
items[i].binary = items[i].binary ?? {};
items[i].binary![binaryProperty] = await this.helpers.prepareBinaryData(data);
items[i].binary![binaryProperty].fileName = this.getNodeParameter('fileName', i) as string;
items[i].binary![binaryProperty].fileExtension = 'pdf';
return items;
}
export function getTriggerName(eventName: string) {
const events: IDataObject = {
'tranferStateChange': 'transfers#state-change',
'transferActiveCases': 'transfers#active-cases',
'balanceCredit': 'balances#credit',
};
return events[eventName];
}
export type BorderlessAccount = {
id: number,
balances: Array<{ currency: string }>
};
export type ExchangeRateAdditionalFields = {
interval: 'day' | 'hour' | 'minute',
range: {
rangeProperties: { from: string, to: string }
},
time: string,
};
export type Profile = {
id: number,
type: 'business' | 'personal',
};
export type Recipient = {
2022-03-06 02:41:01 -08:00
active: boolean,
id: number,
2022-03-06 02:41:01 -08:00
accountHolderName: string,
country: string | null,
currency: string,
type: string,
};
export type StatementAdditionalFields = {
lineStyle: 'COMPACT' | 'FLAT',
range: {
rangeProperties: { intervalStart: string, intervalEnd: string }
},
};
export type TransferFilters = {
[key: string]: string | IDataObject;
range: {
rangeProperties: { createdDateStart: string, createdDateEnd: string }
},
sourceCurrency: string,
status: string,
targetCurrency: string,
};
export const livePublicKey = `
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvO8vXV+JksBzZAY6GhSO
XdoTCfhXaaiZ+qAbtaDBiu2AGkGVpmEygFmWP4Li9m5+Ni85BhVvZOodM9epgW3F
bA5Q1SexvAF1PPjX4JpMstak/QhAgl1qMSqEevL8cmUeTgcMuVWCJmlge9h7B1CS
D4rtlimGZozG39rUBDg6Qt2K+P4wBfLblL0k4C4YUdLnpGYEDIth+i8XsRpFlogx
CAFyH9+knYsDbR43UJ9shtc42Ybd40Afihj8KnYKXzchyQ42aC8aZ/h5hyZ28yVy
Oj3Vos0VdBIs/gAyJ/4yyQFCXYte64I7ssrlbGRaco4nKF3HmaNhxwyKyJafz19e
HwIDAQAB
-----END PUBLIC KEY-----`;
export const testPublicKey = `
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwpb91cEYuyJNQepZAVfP
ZIlPZfNUefH+n6w9SW3fykqKu938cR7WadQv87oF2VuT+fDt7kqeRziTmPSUhqPU
ys/V2Q1rlfJuXbE+Gga37t7zwd0egQ+KyOEHQOpcTwKmtZ81ieGHynAQzsn1We3j
wt760MsCPJ7GMT141ByQM+yW1Bx+4SG3IGjXWyqOWrcXsxAvIXkpUD/jK/L958Cg
nZEgz0BSEh0QxYLITnW1lLokSx/dTianWPFEhMC9BgijempgNXHNfcVirg1lPSyg
z7KqoKUN0oHqWLr2U1A+7kqrl6O2nx3CKs1bj1hToT1+p4kcMoHXA7kA+VBLUpEs
VwIDAQAB
-----END PUBLIC KEY-----`;