@mojaloop/sdk-scheme-adapter 12.2.2 → 13.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/.env.example +3 -0
  2. package/CHANGELOG.md +26 -0
  3. package/audit-resolve.json +71 -1
  4. package/docker/ml-testing-toolkit/spec_files/api_definitions/fspiop_1.1/trigger_templates/transaction_request_followup.json +2 -2
  5. package/docker/ml-testing-toolkit/spec_files/rules_callback/default.json +7 -7
  6. package/docker/ml-testing-toolkit/spec_files/rules_response/default.json +16 -16
  7. package/docker/ml-testing-toolkit/spec_files/rules_response/default_pisp_rules.json +5 -5
  8. package/docker/ml-testing-toolkit/spec_files/rules_validation/default.json +10 -10
  9. package/package.json +4 -1
  10. package/src/ControlAgent/index.js +2 -3
  11. package/src/ControlServer/index.js +2 -2
  12. package/src/InboundServer/handlers.js +114 -52
  13. package/src/InboundServer/index.js +7 -7
  14. package/src/InboundServer/middlewares.js +2 -2
  15. package/src/OutboundServer/api.yaml +54 -3
  16. package/src/OutboundServer/api_interfaces/openapi.d.ts +24 -3
  17. package/src/OutboundServer/api_template/components/schemas/accountsResponse.yaml +9 -0
  18. package/src/OutboundServer/api_template/components/schemas/transferRequest.yaml +3 -0
  19. package/src/OutboundServer/api_template/components/schemas/transferResponse.yaml +28 -2
  20. package/src/OutboundServer/api_template/components/schemas/transferStatusResponse.yaml +8 -1
  21. package/src/OutboundServer/handlers.js +4 -1
  22. package/src/OutboundServer/index.js +10 -11
  23. package/src/config.js +29 -12
  24. package/src/index.js +198 -10
  25. package/src/lib/cache.js +110 -52
  26. package/src/lib/metrics.js +148 -0
  27. package/src/lib/model/AccountsModel.js +17 -12
  28. package/src/lib/model/Async2SyncModel.js +4 -1
  29. package/src/lib/model/InboundTransfersModel.js +170 -25
  30. package/src/lib/model/OutboundBulkQuotesModel.js +4 -1
  31. package/src/lib/model/OutboundBulkTransfersModel.js +4 -1
  32. package/src/lib/model/OutboundRequestToPayModel.js +9 -7
  33. package/src/lib/model/OutboundRequestToPayTransferModel.js +6 -3
  34. package/src/lib/model/OutboundTransfersModel.js +318 -53
  35. package/src/lib/model/PartiesModel.js +1 -1
  36. package/src/lib/model/ProxyModel/index.js +4 -2
  37. package/src/lib/model/common/BackendError.js +28 -4
  38. package/src/lib/model/common/index.js +2 -1
  39. package/src/lib/validate.js +2 -2
  40. package/test/__mocks__/@mojaloop/sdk-standard-components.js +3 -2
  41. package/test/__mocks__/redis.js +4 -0
  42. package/test/config/integration.env +5 -0
  43. package/test/integration/lib/Outbound/parties.test.js +1 -1
  44. package/test/unit/ControlServer/index.js +3 -3
  45. package/test/unit/InboundServer.test.js +10 -10
  46. package/test/unit/TestServer.test.js +11 -13
  47. package/test/unit/api/accounts/data/postAccountsErrorMojaloopResponse.json +11 -3
  48. package/test/unit/api/accounts/data/postAccountsSuccessResponse.json +14 -0
  49. package/test/unit/api/accounts/data/postAccountsSuccessResponseWithError1.json +13 -0
  50. package/test/unit/api/accounts/data/postAccountsSuccessResponseWithError2.json +18 -0
  51. package/test/unit/api/accounts/utils.js +15 -1
  52. package/test/unit/api/transfers/data/getTransfersCommittedResponse.json +18 -15
  53. package/test/unit/api/transfers/data/getTransfersErrorNotFound.json +1 -0
  54. package/test/unit/api/transfers/data/postTransfersErrorMojaloopResponse.json +9 -0
  55. package/test/unit/api/transfers/data/postTransfersErrorTimeoutResponse.json +1 -0
  56. package/test/unit/api/transfers/data/postTransfersSuccessResponse.json +74 -47
  57. package/test/unit/api/transfers/utils.js +85 -4
  58. package/test/unit/api/utils.js +4 -1
  59. package/test/unit/config.test.js +2 -2
  60. package/test/unit/data/commonHttpHeaders.json +1 -0
  61. package/test/unit/data/defaultConfig.json +23 -7
  62. package/test/unit/inboundApi/handlers.test.js +45 -14
  63. package/test/unit/index.test.js +95 -4
  64. package/test/unit/lib/model/AccountsModel.test.js +9 -6
  65. package/test/unit/lib/model/InboundTransfersModel.test.js +210 -30
  66. package/test/unit/lib/model/OutboundRequestToPayModel.test.js +1 -1
  67. package/test/unit/lib/model/OutboundRequestToPayTransferModel.test.js +3 -3
  68. package/test/unit/lib/model/OutboundTransfersModel.test.js +863 -158
  69. package/test/unit/lib/model/data/defaultConfig.json +25 -10
  70. package/test/unit/lib/model/data/mockArguments.json +97 -40
  71. package/test/unit/lib/model/data/payeeParty.json +13 -11
  72. package/test/unit/lib/model/data/quoteResponse.json +36 -25
  73. package/test/unit/lib/model/data/transferFulfil.json +5 -3
  74. package/src/lib/api/index.js +0 -12
  75. package/src/lib/randomphrase/index.js +0 -21
  76. package/src/lib/randomphrase/words.json +0 -3397
@@ -10,6 +10,7 @@
10
10
 
11
11
  'use strict';
12
12
 
13
+ const util = require('util');
13
14
 
14
15
  const {
15
16
  BackendRequests,
@@ -21,6 +22,7 @@ const {
21
22
  Errors,
22
23
  } = require('@mojaloop/sdk-standard-components');
23
24
  const shared = require('./lib/shared');
25
+ const { TransferStateEnum } = require('./common');
24
26
 
25
27
  /**
26
28
  * Models the operations required for performing inbound transfers
@@ -46,7 +48,10 @@ class InboundTransfersModel {
46
48
  transactionRequestsEndpoint: config.transactionRequestsEndpoint,
47
49
  bulkQuotesEndpoint: config.bulkQuotesEndpoint,
48
50
  dfspId: config.dfspId,
49
- tls: config.tls,
51
+ tls: {
52
+ enabled: config.outbound.tls.mutualTLS.enabled,
53
+ creds: config.outbound.tls.creds,
54
+ },
50
55
  jwsSign: config.jwsSign,
51
56
  jwsSigningKey: config.jwsSigningKey,
52
57
  wso2: config.wso2,
@@ -67,6 +72,12 @@ class InboundTransfersModel {
67
72
  });
68
73
  }
69
74
 
75
+ updateStateWithError(err) {
76
+ this.data.lastError = err;
77
+ this.data.currentState = TransferStateEnum.ERROR_OCCURRED;
78
+ return this._save();
79
+ }
80
+
70
81
  /**
71
82
  * Queries the backend API for the specified party and makes a callback to the originator with the result
72
83
  */
@@ -159,7 +170,32 @@ class InboundTransfersModel {
159
170
  * Asks the backend for a response to an incoming quote request and makes a callback to the originator with
160
171
  * the result
161
172
  */
162
- async quoteRequest(quoteRequest, sourceFspId) {
173
+ async quoteRequest(request, sourceFspId) {
174
+ const quoteRequest = request.body;
175
+
176
+ // keep track of our state.
177
+ // note that instances of this model typically only live as long as it takes to
178
+ // handle an incoming request and send a response asynchronously, but we hold onto
179
+ // some state across async ops
180
+
181
+ this.data = {
182
+ // transferId: this follows the slightly dodgy assumption that transferId will be same as this transactionId.
183
+ // so far this has held in moja implementations but may not always be the case. regardless, future FSPIOP API
184
+ // versions MUST deal with this cleanly so we can expect to eliminate this assumption at some point.
185
+ transferId: quoteRequest.transactionId,
186
+ direction: 'INBOUND',
187
+ quoteRequest: {
188
+ headers: request.headers,
189
+ body: request.body
190
+ },
191
+ currentState: TransferStateEnum.QUOTE_REQUEST_RECEIVED,
192
+ initiatedTimestamp: new Date().toISOString(),
193
+ };
194
+
195
+ // persist the transfer record in the cache. if we crash after this at least we will
196
+ // have a record of the request in the cache.
197
+ await this._save();
198
+
163
199
  try {
164
200
  const internalForm = shared.mojaloopQuoteRequestToInternal(quoteRequest);
165
201
 
@@ -186,19 +222,24 @@ class InboundTransfersModel {
186
222
  mojaloopResponse.condition = condition;
187
223
 
188
224
  // now store the fulfilment and the quote data against the quoteId in our cache
189
- await this._cache.set(`quote_${quoteRequest.transactionId}`, {
225
+ this.data.quote = {
190
226
  request: quoteRequest,
191
227
  internalRequest: internalForm,
192
228
  response: response,
193
229
  mojaloopResponse: mojaloopResponse,
194
230
  fulfilment: fulfilment
195
- });
196
-
197
- // now store the quoteResponse data against the quoteId in our cache to be sent as a response to GET /quotes/{ID}
198
- await this._cache.set(`quoteResponse_${quoteRequest.quoteId}`, mojaloopResponse);
231
+ };
232
+ await this._save();
199
233
 
200
234
  // make a callback to the source fsp with the quote response
201
- return this._mojaloopRequests.putQuotes(quoteRequest.quoteId, mojaloopResponse, sourceFspId);
235
+ const res = await this._mojaloopRequests.putQuotes(quoteRequest.quoteId, mojaloopResponse, sourceFspId);
236
+ this.data.quoteResponse = {
237
+ headers: res.originalRequest.headers,
238
+ body: res.originalRequest.body,
239
+ };
240
+ this.data.currentState = TransferStateEnum.WAITING_FOR_QUOTE_ACCEPTANCE;
241
+ await this._save();
242
+ return res;
202
243
  }
203
244
  catch(err) {
204
245
  this._logger.push({ err }).log('Error in quoteRequest');
@@ -254,7 +295,7 @@ class InboundTransfersModel {
254
295
  return 'No response from backend';
255
296
  }
256
297
 
257
- // project our internal quote reponse into mojaloop quote response form
298
+ // project our internal quote response into mojaloop quote response form
258
299
  const mojaloopResponse = shared.internalTransactionRequestResponseToMojaloop(response);
259
300
 
260
301
  // make a callback to the source fsp with the quote response
@@ -274,25 +315,36 @@ class InboundTransfersModel {
274
315
  * Validates an incoming transfer prepare request and makes a callback to the originator with
275
316
  * the result
276
317
  */
277
- async prepareTransfer(prepareRequest, sourceFspId) {
318
+ async prepareTransfer(request, sourceFspId) {
319
+ const prepareRequest = request.body;
278
320
  try {
279
321
  // retrieve our quote data
280
- let quote;
281
-
282
322
  if (this._allowDifferentTransferTransactionId) {
283
323
  const transactionId = this._ilp.getTransactionObject(prepareRequest.ilpPacket).transactionId;
284
- quote = await this._cache.get(`quote_${transactionId}`);
324
+ this.data = await this._load(transactionId);
285
325
  } else {
286
- quote = await this._cache.get(`quote_${prepareRequest.transferId}`);
326
+ this.data = await this._load(prepareRequest.transferId);
287
327
  }
288
328
 
289
- if(!quote) {
329
+ const quote = this.data.quote;
330
+
331
+ if(!this.data || !quote) {
332
+ // If using the sdk-scheme-adapter in place of the deprecated `mojaloop-connector`
333
+ // make sure this is false. Scenarios that use `mojaloop-connector`
334
+ // absolutely requires a previous quote before allowing a transfer to proceed.
335
+ // This is a different to the a typical mojaloop sdk-scheme-adapter setup which allows this as an option.
336
+
290
337
  // Check whether to allow transfers without a previous quote.
291
338
  if(!this._allowTransferWithoutQuote) {
292
339
  throw new Error(`Corresponding quote not found for transfer ${prepareRequest.transferId}`);
293
340
  }
294
341
  }
295
342
 
343
+ // persist our state so we have a record if we crash during processing the prepare
344
+ this.data.prepare = request;
345
+ this.data.currentState = TransferStateEnum.PREPARE_RECEIVED;
346
+ await this._save();
347
+
296
348
  // Calculate or retrieve fulfilment and condition
297
349
  let fulfilment = null;
298
350
  let condition = null;
@@ -310,13 +362,13 @@ class InboundTransfersModel {
310
362
  throw new Error(`ILP condition in transfer prepare for ${prepareRequest.transferId} does not match quote`);
311
363
  }
312
364
 
313
-
314
- if (quote && this._rejectTransfersOnExpiredQuotes) {
365
+ if (this._rejectTransfersOnExpiredQuotes) {
315
366
  const now = new Date().toISOString();
316
367
  const expiration = quote.mojaloopResponse.expiration;
317
368
  if (now > expiration) {
318
369
  const error = Errors.MojaloopApiErrorObjectFromCode(Errors.MojaloopApiErrorCodes.QUOTE_EXPIRED);
319
370
  this._logger.error(`Error in prepareTransfer: quote expired for transfer ${prepareRequest.transferId}, system time=${now} > quote time=${expiration}`);
371
+ await this.updateStateWithError(error);
320
372
  return this._mojaloopRequests.putTransfersError(prepareRequest.transferId, error, sourceFspId);
321
373
  }
322
374
  }
@@ -333,6 +385,7 @@ class InboundTransfersModel {
333
385
  }
334
386
 
335
387
  this._logger.log(`Transfer accepted by backend returning homeTransactionId: ${response.homeTransactionId} for mojaloop transferId: ${prepareRequest.transferId}`);
388
+ this.data.homeTransactionId = response.homeTransactionId;
336
389
 
337
390
  // create a mojaloop transfer fulfil response
338
391
  const mojaloopResponse = {
@@ -347,10 +400,16 @@ class InboundTransfersModel {
347
400
  };
348
401
 
349
402
  // make a callback to the source fsp with the transfer fulfilment
350
- return this._mojaloopRequests.putTransfers(prepareRequest.transferId, mojaloopResponse,
403
+ const res = await this._mojaloopRequests.putTransfers(prepareRequest.transferId, mojaloopResponse,
351
404
  sourceFspId);
352
- }
353
- catch(err) {
405
+ this.data.fulfil = {
406
+ headers: res.originalRequest.headers,
407
+ body: res.originalRequest.body,
408
+ };
409
+ this.data.currentState = this._reserveNotification ? TransferStateEnum.RESERVED : TransferStateEnum.COMPLETED;
410
+ await this._save();
411
+ return res;
412
+ } catch(err) {
354
413
  this._logger.push({ err }).log('Error in prepareTransfer');
355
414
  const mojaloopError = await this._handleError(err);
356
415
  this._logger.push({ mojaloopError }).log(`Sending error response to ${sourceFspId}`);
@@ -714,22 +773,108 @@ class InboundTransfersModel {
714
773
  */
715
774
  async sendNotificationToPayee(body, transferId) {
716
775
  try {
717
- const res = await this._backendRequests.putTransfersNotification(body, transferId);
776
+ // load any cached state for this transfer e.g. quote request/response etc...
777
+ this.data = await this._load(transferId);
778
+
779
+ // if we didnt have anything cached, start from scratch
780
+ if(!this.data) {
781
+ this.data = {};
782
+ }
783
+
784
+ // tag the final notification body on to the state
785
+ this.data.finalNotification = body;
786
+
787
+ if(body.transferState === 'COMMITTED') {
788
+ // if the transfer was successful in the switch, set the overall transfer state to COMPLETED
789
+ this.data.currentState = TransferStateEnum.COMPLETED;
790
+ }
791
+ else {
792
+ // if the final notification has anything other than COMMITTED as the final state, set an error
793
+ // in the transfer state.
794
+ this.data.currentState == TransferStateEnum.ERROR_OCCURED;
795
+ this.data.lastError = 'Final notification state not COMMITTED';
796
+ }
797
+
798
+ await this._save();
799
+
800
+ const res = await this._backendRequests.putTransfersNotification(this.data, transferId);
718
801
  return res;
719
802
  } catch (err) {
720
- this._logger.push({ err }).log('Error in sendNotificationToPayee');
803
+ this._logger.push({ err }).log('Error notifying backend of final transfer state');
721
804
  }
722
805
  }
723
806
 
724
- async _handleError(err, mojaloopErrorCode = Errors.MojaloopApiErrorCodes.INTERNAL_SERVER_ERROR) {
807
+ async _handleError(err) {
808
+ // by default use a generic server error
809
+ let mojaloopError = (new Errors.MojaloopFSPIOPError(err, null, null, Errors.MojaloopApiErrorCodes.INTERNAL_SERVER_ERROR)).toApiErrorObject();
725
810
  if(err instanceof HTTPResponseError) {
811
+ // this is an http response error e.g. from calling DFSP backend
726
812
  const e = err.getData();
727
813
  if(e.res && e.res.data) {
728
- mojaloopErrorCode = Errors.MojaloopApiErrorCodeFromCode(`${e.res.data.statusCode}`);
814
+ // look for a standard mojaloop error that matches the statusCode
815
+ let mojaloopErrorCode = Errors.MojaloopApiErrorCodeFromCode(`${e.res.data.statusCode}`);
816
+ let errorDescription = e.res.data.message;
817
+ if(mojaloopErrorCode) {
818
+ // use the standard mojaloop error object
819
+ mojaloopError = (new Errors.MojaloopFSPIOPError(err, null, null, mojaloopErrorCode)).toApiErrorObject();
820
+ if(errorDescription) {
821
+ // if the error has a description, use that instead of the default mojaloop description
822
+ // note that the mojaloop API spec allows any string up to 128 utf8 characters to be sent
823
+ // in the errorDescription field.
824
+ mojaloopError.errorInformation.errorDescription = errorDescription;
825
+ }
826
+ }
827
+ else {
828
+ // this is a custom error, so construct a mojaloop spec body
829
+ mojaloopError = {
830
+ errorInformation: {
831
+ errorCode: e.res.data.statusCode,
832
+ errorDescription: e.res.data.message,
833
+ }
834
+ };
835
+ }
729
836
  }
730
837
  }
838
+ if(this.data) {
839
+ //we have persisted state so update that with this error
840
+ this.data.lastError = {
841
+ originalError: err.stack || util.inspect(err),
842
+ mojaloopError: mojaloopError,
843
+ };
844
+ this.data.currentState = TransferStateEnum.ERROR_OCCURRED;
845
+ await this._save();
846
+ }
847
+ return mojaloopError;
848
+ }
849
+
850
+ /**
851
+ * Persists the model state to cache for reinstantiation at a later point
852
+ */
853
+ async _save() {
854
+ try {
855
+ const res = await this._cache.set(`transferModel_in_${this.data.transferId}`, this.data);
856
+ this._logger.push({ res }).log('Persisted transfer model in cache');
857
+ }
858
+ catch(err) {
859
+ this._logger.push({ err }).log('Error saving transfer model');
860
+ throw err;
861
+ }
862
+ }
731
863
 
732
- return new Errors.MojaloopFSPIOPError(err, null, null, mojaloopErrorCode).toApiErrorObject();
864
+ /**
865
+ * Loads a transfer model from cache for resumption of the transfer process
866
+ *
867
+ * @param transferId {string} - UUID transferId of the model to load from cache
868
+ */
869
+ async _load(transferId) {
870
+ try {
871
+ const data = await this._cache.get(`transferModel_in_${transferId}`);
872
+ return data;
873
+ }
874
+ catch(err) {
875
+ this._logger.push({ err }).log('Error loading transfer model');
876
+ throw err;
877
+ }
733
878
  }
734
879
  }
735
880
 
@@ -40,7 +40,10 @@ class OutboundBulkQuotesModel {
40
40
  peerEndpoint: config.peerEndpoint,
41
41
  bulkQuotesEndpoint: config.bulkQuotesEndpoint,
42
42
  dfspId: config.dfspId,
43
- tls: config.tls,
43
+ tls: {
44
+ enabled: config.outbound.tls.mutualTLS.enabled,
45
+ creds: config.outbound.tls.creds,
46
+ },
44
47
  jwsSign: config.jwsSign,
45
48
  jwsSigningKey: config.jwsSigningKey,
46
49
  wso2: config.wso2,
@@ -38,7 +38,10 @@ class OutboundBulkTransfersModel {
38
38
  peerEndpoint: config.peerEndpoint,
39
39
  bulkTransfersEndpoint: config.bulkTransfersEndpoint,
40
40
  dfspId: config.dfspId,
41
- tls: config.tls,
41
+ tls: {
42
+ enabled: config.outbound.tls.mutualTLS.enabled,
43
+ creds: config.outbound.tls.creds,
44
+ },
42
45
  jwsSign: config.jwsSign,
43
46
  jwsSignPutParties: config.jwsSignPutParties,
44
47
  jwsSigningKey: config.jwsSigningKey,
@@ -39,7 +39,10 @@ class OutboundRequestToPayModel {
39
39
  peerEndpoint: config.peerEndpoint,
40
40
  alsEndpoint: config.alsEndpoint,
41
41
  dfspId: config.dfspId,
42
- tls: config.tls,
42
+ tls: {
43
+ enabled: config.outbound.tls.mutualTLS.enabled,
44
+ creds: config.outbound.tls.creds,
45
+ },
43
46
  jwsSign: config.jwsSign,
44
47
  jwsSignPutParties: config.jwsSignPutParties,
45
48
  jwsSigningKey: config.jwsSigningKey,
@@ -152,17 +155,16 @@ class OutboundRequestToPayModel {
152
155
  // hook up a subscriber to handle response messages
153
156
  const subId = await this._cache.subscribe(payeeKey, (cn, msg, subId) => {
154
157
  try {
155
- let payee = JSON.parse(msg);
156
-
157
- if(payee.errorInformation) {
158
+ this.data.getPartiesResponse = JSON.parse(msg);
159
+ if(this.data.getPartiesResponse.body.errorInformation) {
158
160
  // this is an error response to our GET /parties request
159
- const err = new BackendError(`Got an error response resolving party: ${util.inspect(payee)}`, 500);
160
- err.mojaloopError = payee;
161
-
161
+ const err = new BackendError(`Got an error response resolving party: ${util.inspect(this.data.getPartiesResponse.body, { depth: Infinity })}`, 500);
162
+ err.mojaloopError = this.data.getPartiesResponse.body;
162
163
  // cancel the timeout handler
163
164
  clearTimeout(timeout);
164
165
  return reject(err);
165
166
  }
167
+ let payee = this.data.getPartiesResponse.body;
166
168
 
167
169
  if(!payee.party) {
168
170
  // we should never get a non-error response without a party, but just in case...
@@ -52,7 +52,10 @@ class OutboundRequestToPayTransferModel {
52
52
  authorizationsEndpoint: config.authorizationsEndpoint,
53
53
  transfersEndpoint: config.transfersEndpoint,
54
54
  dfspId: config.dfspId,
55
- tls: config.tls,
55
+ tls: {
56
+ enabled: config.outbound.tls.mutualTLS.enabled,
57
+ creds: config.outbound.tls.creds,
58
+ },
56
59
  jwsSign: config.jwsSign,
57
60
  jwsSignPutParties: config.jwsSignPutParties,
58
61
  jwsSigningKey: config.jwsSigningKey,
@@ -424,8 +427,8 @@ class OutboundRequestToPayTransferModel {
424
427
  return reject(error);
425
428
  }
426
429
 
427
- const quoteResponseBody = message.data;
428
- const quoteResponseHeaders = message.headers;
430
+ const quoteResponseBody = message.data.body;
431
+ const quoteResponseHeaders = message.data.headers;
429
432
  this._logger.push({ quoteResponseBody }).log('Quote response received');
430
433
 
431
434
  this.data.quoteResponse = quoteResponseBody;