@commercetools/connect-payments-sdk 0.4.4 → 0.5.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 (42) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/api/hooks/authorize.hook.d.ts +15 -0
  3. package/dist/api/hooks/authorize.hook.js +17 -1
  4. package/dist/api/hooks/jwt-auth.hook.d.ts +14 -0
  5. package/dist/api/hooks/jwt-auth.hook.js +13 -0
  6. package/dist/api/hooks/oauth2-auth.hook.d.ts +3 -0
  7. package/dist/api/hooks/oauth2-auth.hook.js +2 -0
  8. package/dist/api/hooks/session-header-auth.hook.d.ts +3 -0
  9. package/dist/api/hooks/session-header-auth.hook.js +2 -0
  10. package/dist/api/hooks/session-query-param-auth.hook.d.ts +3 -0
  11. package/dist/api/hooks/session-query-param-auth.hook.js +2 -0
  12. package/dist/commercetools/api/root-api.d.ts +3 -0
  13. package/dist/commercetools/api/root-api.js +2 -0
  14. package/dist/commercetools/services/ct-authorization.service.d.ts +2 -2
  15. package/dist/commercetools/services/ct-cart.service.d.ts +1 -0
  16. package/dist/commercetools/services/ct-cart.service.js +2 -0
  17. package/dist/commercetools/services/ct-payment.service.d.ts +4 -3
  18. package/dist/commercetools/services/ct-payment.service.js +24 -6
  19. package/dist/commercetools/services/ct-session.service.d.ts +3 -0
  20. package/dist/commercetools/services/ct-session.service.js +2 -0
  21. package/dist/commercetools/types/cart.type.d.ts +2 -0
  22. package/dist/commercetools/types/payment.type.d.ts +2 -0
  23. package/dist/index.js +30 -4
  24. package/dist/logger/commercetools-logger.d.ts +17 -0
  25. package/dist/logger/commercetools-logger.js +57 -0
  26. package/dist/logger/index.d.ts +1 -0
  27. package/dist/logger/index.js +1 -0
  28. package/dist/security/authn/jwt-authn-manager.d.ts +3 -0
  29. package/dist/security/authn/jwt-authn-manager.js +2 -0
  30. package/dist/security/authn/oauth2-authn-manager.d.ts +3 -0
  31. package/dist/security/authn/oauth2-authn-manager.js +2 -0
  32. package/dist/security/authn/session-header-authn-manager.d.ts +3 -0
  33. package/dist/security/authn/session-header-authn-manager.js +2 -0
  34. package/dist/security/authn/session-query-param-authn-manager.d.ts +3 -0
  35. package/dist/security/authn/session-query-param-authn-manager.js +2 -0
  36. package/dist/security/authz/authorization-manager.d.ts +5 -0
  37. package/dist/security/authz/authorization-manager.js +4 -0
  38. package/dist/security/services/jwt.service.d.ts +3 -0
  39. package/dist/security/services/jwt.service.js +2 -0
  40. package/dist/security/services/oauth2.service.d.ts +5 -0
  41. package/dist/security/services/oauth2.service.js +4 -0
  42. package/package.json +5 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @commercetools/connect-payments-sdk
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 67c0581: added a common logger
8
+
3
9
  ## 0.4.4
4
10
 
5
11
  ### Patch Changes
@@ -1,12 +1,27 @@
1
+ import { Logger } from '../..';
1
2
  import { AuthorityAuthorizationManager } from '../../security/authz/authorization-manager';
2
3
  import { ContextProvider, RequestContextData } from '../context/types/request-context.type';
3
4
  import { AuthorizationHook } from './types/hook.type';
5
+ /**
6
+ * Represents an authorization hook that verifies the authority of a request.
7
+ */
4
8
  export declare class AuthorityAuthorizationHook implements AuthorizationHook {
5
9
  private authorizationManager;
6
10
  private contextProvider;
11
+ private logger;
12
+ /**
13
+ * Constructs a new instance of the AuthorityAuthorizationHook class.
14
+ * @param opts - The options for configuring the hook.
15
+ */
7
16
  constructor(opts: {
8
17
  authorizationManager: AuthorityAuthorizationManager;
9
18
  contextProvider: ContextProvider<RequestContextData>;
19
+ logger: Logger;
10
20
  });
21
+ /**
22
+ * Authorizes the request based on the provided authorities.
23
+ * @param authorities - The authorities to verify.
24
+ * @returns A function that performs the authorization check.
25
+ */
11
26
  authorize(...authorities: string[]): () => Promise<void>;
12
27
  }
@@ -2,18 +2,34 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AuthorityAuthorizationHook = void 0;
4
4
  const errorx_1 = require("../../errorx");
5
+ /**
6
+ * Represents an authorization hook that verifies the authority of a request.
7
+ */
5
8
  class AuthorityAuthorizationHook {
6
9
  authorizationManager;
7
10
  contextProvider;
11
+ logger;
12
+ /**
13
+ * Constructs a new instance of the AuthorityAuthorizationHook class.
14
+ * @param opts - The options for configuring the hook.
15
+ */
8
16
  constructor(opts) {
9
17
  this.authorizationManager = opts.authorizationManager;
10
18
  this.contextProvider = opts.contextProvider;
19
+ this.logger = opts.logger;
11
20
  }
21
+ /**
22
+ * Authorizes the request based on the provided authorities.
23
+ * @param authorities - The authorities to verify.
24
+ * @returns A function that performs the authorization check.
25
+ */
12
26
  authorize(...authorities) {
13
27
  return async () => {
14
28
  const authn = this.contextProvider.getContextData().authentication;
15
29
  if (!authn) {
16
- throw new errorx_1.ErrorAuthErrorResponse('Authentication is required.');
30
+ throw new errorx_1.ErrorAuthErrorResponse('Authentication is required.', {
31
+ privateMessage: 'Not able to authenticate the request. Missing authentication information in context.',
32
+ });
17
33
  }
18
34
  this.authorizationManager.verify(authn, authorities);
19
35
  };
@@ -3,13 +3,27 @@ import { IncomingHttpHeaders } from 'node:http';
3
3
  import { JWTAuthenticationManager } from '../../security/authn/jwt-authn-manager';
4
4
  import { ContextProvider, RequestContextData } from '../context/types/request-context.type';
5
5
  import { AuthenticationHook } from './types/hook.type';
6
+ import { Logger } from '../..';
7
+ /**
8
+ * Represents a JWT Authentication Hook.
9
+ */
6
10
  export declare class JWTAuthenticationHook implements AuthenticationHook {
7
11
  private authenticationManager;
8
12
  private contextProvider;
13
+ private logger;
14
+ /**
15
+ * Constructs a new instance of the JWTAuthenticationHook class.
16
+ * @param opts - The options for the JWTAuthenticationHook.
17
+ */
9
18
  constructor(opts: {
10
19
  authenticationManager: JWTAuthenticationManager;
11
20
  contextProvider: ContextProvider<RequestContextData>;
21
+ logger: Logger;
12
22
  });
23
+ /**
24
+ * Authenticates the request.
25
+ * @returns A function that performs the authentication.
26
+ */
13
27
  authenticate(): (request: {
14
28
  headers: IncomingHttpHeaders;
15
29
  query?: any;
@@ -2,13 +2,26 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.JWTAuthenticationHook = void 0;
4
4
  const security_1 = require("../../security");
5
+ /**
6
+ * Represents a JWT Authentication Hook.
7
+ */
5
8
  class JWTAuthenticationHook {
6
9
  authenticationManager;
7
10
  contextProvider;
11
+ logger;
12
+ /**
13
+ * Constructs a new instance of the JWTAuthenticationHook class.
14
+ * @param opts - The options for the JWTAuthenticationHook.
15
+ */
8
16
  constructor(opts) {
9
17
  this.authenticationManager = opts.authenticationManager;
10
18
  this.contextProvider = opts.contextProvider;
19
+ this.logger = opts.logger;
11
20
  }
21
+ /**
22
+ * Authenticates the request.
23
+ * @returns A function that performs the authentication.
24
+ */
12
25
  authenticate() {
13
26
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
27
  return async (request) => {
@@ -3,12 +3,15 @@ import { IncomingHttpHeaders } from 'node:http';
3
3
  import { Oauth2AuthenticationManager } from '../../security/authn/oauth2-authn-manager';
4
4
  import { ContextProvider, RequestContextData } from '../context/types/request-context.type';
5
5
  import { AuthenticationHook } from './types/hook.type';
6
+ import { Logger } from '../..';
6
7
  export declare class Oauth2AuthenticationHook implements AuthenticationHook {
7
8
  private authenticationManager;
8
9
  private contextProvider;
10
+ private logger;
9
11
  constructor(opts: {
10
12
  authenticationManager: Oauth2AuthenticationManager;
11
13
  contextProvider: ContextProvider<RequestContextData>;
14
+ logger: Logger;
12
15
  });
13
16
  authenticate(): (request: {
14
17
  headers: IncomingHttpHeaders;
@@ -5,9 +5,11 @@ const security_1 = require("../../security");
5
5
  class Oauth2AuthenticationHook {
6
6
  authenticationManager;
7
7
  contextProvider;
8
+ logger;
8
9
  constructor(opts) {
9
10
  this.authenticationManager = opts.authenticationManager;
10
11
  this.contextProvider = opts.contextProvider;
12
+ this.logger = opts.logger;
11
13
  }
12
14
  authenticate() {
13
15
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -3,12 +3,15 @@ import { IncomingHttpHeaders } from 'node:http';
3
3
  import { ContextProvider, RequestContextData } from '../context/types/request-context.type';
4
4
  import { SessionHeaderAuthenticationManager } from '../../security';
5
5
  import { AuthenticationHook } from './types/hook.type';
6
+ import { Logger } from '../..';
6
7
  export declare class SessionHeaderAuthenticationHook implements AuthenticationHook {
7
8
  private authenticationManager;
8
9
  private contextProvider;
10
+ private logger;
9
11
  constructor(opts: {
10
12
  authenticationManager: SessionHeaderAuthenticationManager;
11
13
  contextProvider: ContextProvider<RequestContextData>;
14
+ logger: Logger;
12
15
  });
13
16
  authenticate(): (request: {
14
17
  headers: IncomingHttpHeaders;
@@ -5,9 +5,11 @@ const security_1 = require("../../security");
5
5
  class SessionHeaderAuthenticationHook {
6
6
  authenticationManager;
7
7
  contextProvider;
8
+ logger;
8
9
  constructor(opts) {
9
10
  this.authenticationManager = opts.authenticationManager;
10
11
  this.contextProvider = opts.contextProvider;
12
+ this.logger = opts.logger;
11
13
  }
12
14
  authenticate() {
13
15
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -3,12 +3,15 @@ import { IncomingHttpHeaders } from 'node:http';
3
3
  import { ContextProvider, RequestContextData } from '../context/types/request-context.type';
4
4
  import { SessionQueryParamAuthenticationManager } from '../../security';
5
5
  import { AuthenticationHook } from './types/hook.type';
6
+ import { Logger } from '../..';
6
7
  export declare class SessionQueryParamAuthenticationHook implements AuthenticationHook {
7
8
  private authenticationManager;
8
9
  private contextProvider;
10
+ private logger;
9
11
  constructor(opts: {
10
12
  authenticationManager: SessionQueryParamAuthenticationManager;
11
13
  contextProvider: ContextProvider<RequestContextData>;
14
+ logger: Logger;
12
15
  });
13
16
  authenticate(): (request: {
14
17
  headers: IncomingHttpHeaders;
@@ -5,9 +5,11 @@ const security_1 = require("../../security");
5
5
  class SessionQueryParamAuthenticationHook {
6
6
  authenticationManager;
7
7
  contextProvider;
8
+ logger;
8
9
  constructor(opts) {
9
10
  this.authenticationManager = opts.authenticationManager;
10
11
  this.contextProvider = opts.contextProvider;
12
+ this.logger = opts.logger;
11
13
  }
12
14
  authenticate() {
13
15
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -1,9 +1,11 @@
1
1
  import { ContextProvider, RequestContextData } from '../../api';
2
2
  import { CartAPI, CommercetoolsAPI, CommercetoolsClient, PaymentAPI } from '../types/api.type';
3
+ import { Logger } from '../..';
3
4
  export declare class DefaultCommercetoolsAPI implements CommercetoolsAPI {
4
5
  client: CommercetoolsClient;
5
6
  cart: CartAPI;
6
7
  payment: PaymentAPI;
8
+ private logger;
7
9
  constructor(opts: {
8
10
  clientId: string;
9
11
  clientSecret: string;
@@ -11,5 +13,6 @@ export declare class DefaultCommercetoolsAPI implements CommercetoolsAPI {
11
13
  apiUrl: string;
12
14
  projectKey: string;
13
15
  contextProvider: ContextProvider<RequestContextData>;
16
+ logger: Logger;
14
17
  });
15
18
  }
@@ -9,10 +9,12 @@ class DefaultCommercetoolsAPI {
9
9
  client;
10
10
  cart;
11
11
  payment;
12
+ logger;
12
13
  constructor(opts) {
13
14
  this.client = createClient(opts);
14
15
  this.cart = new cart_api_1.CommercetoolsCartAPI({ client: this.client });
15
16
  this.payment = new payment_api_1.CommercetoolsPaymentAPI({ client: this.client });
17
+ this.logger = opts.logger;
16
18
  }
17
19
  }
18
20
  exports.DefaultCommercetoolsAPI = DefaultCommercetoolsAPI;
@@ -6,13 +6,13 @@ export declare class DefaultAuthorizationService implements AuthorizationService
6
6
  private clientId;
7
7
  private clientSecret;
8
8
  private fetch;
9
- private logger?;
9
+ private logger;
10
10
  constructor(opts: {
11
11
  authUrl: string;
12
12
  clientId: string;
13
13
  clientSecret: string;
14
14
  fetch: Fetch;
15
- logger?: Logger;
15
+ logger: Logger;
16
16
  });
17
17
  getAccessToken(): Promise<CommercetoolsToken>;
18
18
  }
@@ -7,6 +7,7 @@ import { AddPayment } from '../types/api.type';
7
7
  */
8
8
  export declare class DefaultCartService implements CartService {
9
9
  private ctAPI;
10
+ private logger;
10
11
  constructor(opts: CartServiceOptions);
11
12
  getCart(opts: GetCart): Promise<Cart>;
12
13
  getPaymentAmount(opts: GetPaymentAmount): Promise<PaymentAmount>;
@@ -8,8 +8,10 @@ const __1 = require("../..");
8
8
  */
9
9
  class DefaultCartService {
10
10
  ctAPI;
11
+ logger;
11
12
  constructor(opts) {
12
13
  this.ctAPI = opts.ctAPI;
14
+ this.logger = opts.logger;
13
15
  }
14
16
  async getCart(opts) {
15
17
  return await this.ctAPI.cart.getCartById(opts.id);
@@ -1,10 +1,11 @@
1
- import { Payment, PaymentDraft } from '@commercetools/platform-sdk';
2
- import { GetPayment, PaymentCancelAuthorizationValidation, PaymentChargeValidation, PaymentModificationValidationResult, PaymentRefundValidation, PaymentService, PaymentServiceOptions, UpdatePayment } from '../types/payment.type';
1
+ import { Payment, PaymentDraft, Transaction } from '@commercetools/platform-sdk';
2
+ import { GetPayment, PaymentCancelAuthorizationValidation, PaymentChargeValidation, PaymentModificationValidationResult, PaymentRefundValidation, PaymentService, PaymentServiceOptions, TransactionData, UpdatePayment } from '../types/payment.type';
3
3
  /**
4
4
  * This is the default implementation of the PaymentService interface.
5
5
  */
6
6
  export declare class DefaultPaymentService implements PaymentService {
7
7
  private ctAPI;
8
+ private logger;
8
9
  constructor(opts: PaymentServiceOptions);
9
10
  getPayment(opts: GetPayment): Promise<Payment>;
10
11
  createPayment(draft: PaymentDraft): Promise<Payment>;
@@ -18,7 +19,7 @@ export declare class DefaultPaymentService implements PaymentService {
18
19
  private populateAddTransactionAction;
19
20
  private populateChangeTransactionState;
20
21
  private populateSetPaymentMethod;
21
- private findMatchingTransactions;
22
+ findMatchingTransactions(payment: Payment, transaction: TransactionData): Transaction[];
22
23
  private consolidateTransactionChanges;
23
24
  private hasTransactionWithState;
24
25
  private calculateTotalAmount;
@@ -7,8 +7,10 @@ const ct_api_error_1 = require("../errors/ct-api.error");
7
7
  */
8
8
  class DefaultPaymentService {
9
9
  ctAPI;
10
+ logger;
10
11
  constructor(opts) {
11
12
  this.ctAPI = opts.ctAPI;
13
+ this.logger = opts.logger;
12
14
  }
13
15
  async getPayment(opts) {
14
16
  return await this.ctAPI.payment.getPaymentById(opts.id);
@@ -22,6 +24,7 @@ class DefaultPaymentService {
22
24
  for (let retries = 0; retries < maxRetries; retries++) {
23
25
  const payment = await this.getPayment({ id: opts.id });
24
26
  const actions = this.consolidateUpdateActions(payment, opts);
27
+ this.logger.info({ paymentId: payment.id, actions }, 'Updating payment with actions');
25
28
  try {
26
29
  const updatedPayment = await this.ctAPI.payment.updatePayment({
27
30
  resource: {
@@ -48,12 +51,18 @@ class DefaultPaymentService {
48
51
  if (!this.hasTransactionWithState(opts.payment, 'Authorization', ['Success'])) {
49
52
  return { isValid: false, reason: `No authorization transaction found for resource ${opts.payment.id}.` };
50
53
  }
51
- if (this.hasTransactionWithState(opts.payment, 'CancelAuthorization', ['Success', 'Pending'])) {
54
+ if (this.hasTransactionWithState(opts.payment, 'CancelAuthorization', ['Success'])) {
52
55
  return { isValid: false, reason: `Resource ${opts.payment.id} has already been cancelled.` };
53
56
  }
57
+ if (this.hasTransactionWithState(opts.payment, 'CancelAuthorization', ['Pending'])) {
58
+ return { isValid: false, reason: `Resource ${opts.payment.id} is pending to be cancelled.` };
59
+ }
54
60
  if (this.hasTransactionWithState(opts.payment, 'Charge', ['Success'])) {
55
61
  return { isValid: false, reason: `Resource ${opts.payment.id} has already been charged.` };
56
62
  }
63
+ if (this.hasTransactionWithState(opts.payment, 'Charge', ['Pending'])) {
64
+ return { isValid: false, reason: `Resource ${opts.payment.id} is pending to be charged.` };
65
+ }
57
66
  return { isValid: true };
58
67
  }
59
68
  validatePaymentCharge(opts) {
@@ -67,9 +76,12 @@ class DefaultPaymentService {
67
76
  if (totalAuthorized === 0) {
68
77
  return { isValid: false, reason: `No authorization transaction found for resource ${opts.payment.id}.` };
69
78
  }
70
- if (this.hasTransactionWithState(opts.payment, 'CancelAuthorization', ['Success', 'Pending'])) {
79
+ if (this.hasTransactionWithState(opts.payment, 'CancelAuthorization', ['Success'])) {
71
80
  return { isValid: false, reason: `Resource ${opts.payment.id} has already been cancelled.` };
72
81
  }
82
+ if (this.hasTransactionWithState(opts.payment, 'CancelAuthorization', ['Pending'])) {
83
+ return { isValid: false, reason: `Resource ${opts.payment.id} is pending to be cancelled.` };
84
+ }
73
85
  const totalCaptured = this.calculateTotalAmount(opts.payment, 'Charge', opts.amount.currencyCode);
74
86
  const allowedAmount = totalAuthorized - totalCaptured;
75
87
  if (opts.amount.centAmount > allowedAmount) {
@@ -87,9 +99,12 @@ class DefaultPaymentService {
87
99
  reason: `Invalid currency ${opts.amount.currencyCode} for resource ${opts.payment.id}, expected ${opts.payment.amountPlanned.currencyCode}`,
88
100
  };
89
101
  }
90
- if (this.hasTransactionWithState(opts.payment, 'CancelAuthorization', ['Success', 'Pending'])) {
102
+ if (this.hasTransactionWithState(opts.payment, 'CancelAuthorization', ['Success'])) {
91
103
  return { isValid: false, reason: `Resource ${opts.payment.id} has already been cancelled.` };
92
104
  }
105
+ if (this.hasTransactionWithState(opts.payment, 'CancelAuthorization', ['Pending'])) {
106
+ return { isValid: false, reason: `Resource ${opts.payment.id} is pending to be cancelled.` };
107
+ }
93
108
  const totalCaptured = this.calculateTotalAmount(opts.payment, 'Charge', opts.amount.currencyCode);
94
109
  if (totalCaptured === 0) {
95
110
  return { isValid: false, reason: `No charge transaction found for resource ${opts.payment.id}.` };
@@ -158,10 +173,12 @@ class DefaultPaymentService {
158
173
  findMatchingTransactions(payment, transaction) {
159
174
  return payment.transactions.filter((tx) => {
160
175
  return (tx.type === transaction.type &&
161
- tx.amount.centAmount === transaction.amount.centAmount &&
162
- tx.amount.currencyCode === transaction.amount.currencyCode &&
163
176
  transaction.interactionId &&
164
- (tx.interactionId || (!tx.interactionId && tx.state === 'Initial')));
177
+ (tx.interactionId === transaction.interactionId ||
178
+ (tx.amount.centAmount === transaction.amount.centAmount &&
179
+ tx.amount.currencyCode === transaction.amount.currencyCode &&
180
+ !tx.interactionId &&
181
+ tx.state === 'Initial')));
165
182
  });
166
183
  }
167
184
  consolidateTransactionChanges(payment, transaction) {
@@ -186,6 +203,7 @@ class DefaultPaymentService {
186
203
  }
187
204
  }
188
205
  else {
206
+ this.logger.error({ paymentId: payment.id, transaction }, 'Multiple transactions found when consolidating payment changes');
189
207
  throw new Error('Multiple transactions found');
190
208
  }
191
209
  }
@@ -1,3 +1,4 @@
1
+ import { Logger } from '../..';
1
2
  import { AuthorizationService, CommercetoolsToken } from '../types/authorization.type';
2
3
  import { Session, SessionService } from '../types/session.type';
3
4
  export declare class DefaultSessionService implements SessionService {
@@ -5,10 +6,12 @@ export declare class DefaultSessionService implements SessionService {
5
6
  private sessionUrl;
6
7
  private projectKey;
7
8
  protected token: CommercetoolsToken;
9
+ private logger;
8
10
  constructor(opts: {
9
11
  authorizationService: AuthorizationService;
10
12
  sessionUrl: string;
11
13
  projectKey: string;
14
+ logger: Logger;
12
15
  });
13
16
  verifySession(sessionId: string): Promise<Session>;
14
17
  getCartFromSession(session: Session): string;
@@ -7,10 +7,12 @@ class DefaultSessionService {
7
7
  sessionUrl;
8
8
  projectKey;
9
9
  token;
10
+ logger;
10
11
  constructor(opts) {
11
12
  this.authorizationService = opts.authorizationService;
12
13
  this.sessionUrl = opts.sessionUrl;
13
14
  this.projectKey = opts.projectKey;
15
+ this.logger = opts.logger;
14
16
  }
15
17
  async verifySession(sessionId) {
16
18
  if (!this.token) {
@@ -1,6 +1,7 @@
1
1
  import { Cart } from '@commercetools/platform-sdk';
2
2
  import { AddPayment, CommercetoolsAPI } from './api.type';
3
3
  import { PaymentAmount } from './payment.type';
4
+ import { Logger } from '../../logger';
4
5
  export type GetCart = {
5
6
  id: string;
6
7
  version?: number;
@@ -10,6 +11,7 @@ export type GetPaymentAmount = {
10
11
  };
11
12
  export type CartServiceOptions = {
12
13
  ctAPI: CommercetoolsAPI;
14
+ logger: Logger;
13
15
  };
14
16
  /**
15
17
  * Cart service interface exposes methods to interact with the commercetools platform API.
@@ -1,11 +1,13 @@
1
1
  import { Money, Payment, PaymentDraft, TransactionState, TransactionType } from '@commercetools/platform-sdk';
2
2
  import { CommercetoolsAPI } from './api.type';
3
+ import { Logger } from '../../logger';
3
4
  export type PaymentAmount = {
4
5
  centAmount: number;
5
6
  currencyCode: string;
6
7
  };
7
8
  export type PaymentServiceOptions = {
8
9
  ctAPI: CommercetoolsAPI;
10
+ logger: Logger;
9
11
  };
10
12
  export type GetPayment = {
11
13
  id: string;
package/dist/index.js CHANGED
@@ -23,6 +23,7 @@ const ct_payment_service_1 = require("./commercetools/services/ct-payment.servic
23
23
  const ct_session_service_1 = require("./commercetools/services/ct-session.service");
24
24
  const base_decorator_1 = require("./fetch/decorators/base.decorator");
25
25
  const monitoring_decorator_1 = require("./fetch/decorators/monitoring.decorator");
26
+ const logger_1 = require("./logger");
26
27
  const security_1 = require("./security");
27
28
  __exportStar(require("./api"), exports);
28
29
  __exportStar(require("./commercetools"), exports);
@@ -34,6 +35,7 @@ const setupPaymentSDK = (opts) => {
34
35
  getContextFn: opts.getContextFn,
35
36
  updateContextFn: opts.updateContextFn,
36
37
  });
38
+ const logger = opts.logger || new logger_1.CommercetoolsLogger({ contextProvider, projectKey: opts.projectKey });
37
39
  const fetcher = new monitoring_decorator_1.MonitoringFetcherDecorator(new base_decorator_1.BasicFetcher(), contextProvider);
38
40
  const decoratedFetch = fetcher.run.bind(fetcher);
39
41
  const ctAPI = new root_api_1.DefaultCommercetoolsAPI({
@@ -43,62 +45,86 @@ const setupPaymentSDK = (opts) => {
43
45
  clientSecret: opts.clientSecret,
44
46
  projectKey: opts.projectKey,
45
47
  contextProvider,
48
+ logger,
46
49
  });
47
- const ctCartService = new ct_cart_service_1.DefaultCartService({ ctAPI });
48
- const ctPaymentService = new ct_payment_service_1.DefaultPaymentService({ ctAPI });
50
+ const ctCartService = new ct_cart_service_1.DefaultCartService({ ctAPI, logger });
51
+ const ctPaymentService = new ct_payment_service_1.DefaultPaymentService({ ctAPI, logger });
49
52
  const ctAuthorizationService = new ct_authorization_service_1.DefaultAuthorizationService({
50
53
  authUrl: opts.authUrl,
51
54
  clientId: opts.clientId,
52
55
  clientSecret: opts.clientSecret,
53
56
  fetch: decoratedFetch,
57
+ logger,
54
58
  });
55
59
  const sessionService = new ct_session_service_1.DefaultSessionService({
56
60
  authorizationService: ctAuthorizationService,
57
61
  sessionUrl: opts.sessionUrl,
58
62
  projectKey: opts.projectKey,
63
+ logger,
59
64
  });
60
- const oauth2Service = new security_1.DefaultOauth2Service();
65
+ const oauth2Service = new security_1.DefaultOauth2Service({ logger });
61
66
  const jwtService = new security_1.DefaultJWTService({
62
67
  jwksUrl: opts.jwksUrl,
68
+ logger,
63
69
  });
64
70
  const sessionHeaderAuthenticationManager = new security_1.SessionHeaderAuthenticationManager({
65
71
  sessionService,
72
+ logger,
66
73
  });
67
74
  const sessionQueryParamAuthenticationManager = new security_1.SessionQueryParamAuthenticationManager({
68
75
  sessionService,
76
+ logger,
69
77
  });
70
78
  const oauth2AuthenticationManager = new security_1.Oauth2AuthenticationManager({
71
79
  oauth2Service,
72
80
  clientId: opts.clientId,
73
81
  clientSecret: opts.clientSecret,
74
82
  authUrl: opts.authUrl,
83
+ logger,
84
+ });
85
+ const authorityAuthorizationManager = new security_1.AuthorityAuthorizationManager({
86
+ logger,
75
87
  });
76
- const authorityAuthorizationManager = new security_1.AuthorityAuthorizationManager();
77
88
  const jwtAuthenticationManager = new security_1.JWTAuthenticationManager({
78
89
  jwtService,
79
90
  iss: opts.jwtIssuer,
80
91
  projectKey: opts.projectKey,
92
+ logger,
81
93
  });
82
94
  const sessionHeaderAuthHookFn = new api_1.SessionHeaderAuthenticationHook({
83
95
  authenticationManager: sessionHeaderAuthenticationManager,
84
96
  contextProvider,
97
+ logger,
85
98
  });
86
99
  const sessionQueryParamAuthHookFn = new api_1.SessionQueryParamAuthenticationHook({
87
100
  authenticationManager: sessionQueryParamAuthenticationManager,
88
101
  contextProvider,
102
+ logger,
89
103
  });
90
104
  const jwtAuthHookFn = new api_1.JWTAuthenticationHook({
91
105
  authenticationManager: jwtAuthenticationManager,
92
106
  contextProvider,
107
+ logger,
93
108
  });
94
109
  const oauth2AuthHookFn = new api_1.Oauth2AuthenticationHook({
95
110
  authenticationManager: oauth2AuthenticationManager,
96
111
  contextProvider,
112
+ logger,
97
113
  });
98
114
  const authorityAuthorizationHookFn = new api_1.AuthorityAuthorizationHook({
99
115
  authorizationManager: authorityAuthorizationManager,
100
116
  contextProvider,
117
+ logger,
101
118
  });
119
+ logger.info({
120
+ projectKey: opts.projectKey,
121
+ apiUrl: opts.apiUrl,
122
+ authUrl: opts.authUrl,
123
+ sessionUrl: opts.sessionUrl,
124
+ jwksUrl: opts.jwksUrl,
125
+ jwtIssuer: opts.jwtIssuer,
126
+ clientId: opts.clientId,
127
+ }, 'payment-sdk initialized');
102
128
  return {
103
129
  ctAPI,
104
130
  ctCartService,
@@ -0,0 +1,17 @@
1
+ import { RequestContextProvider } from '..';
2
+ type DefaultFields = {
3
+ [key: string]: undefined | string | object | (() => object | string | undefined);
4
+ };
5
+ export declare const defaultFieldsFormatter: (defaults: DefaultFields) => import("logform").Format;
6
+ export declare class CommercetoolsLogger {
7
+ private logger;
8
+ constructor(opts: {
9
+ contextProvider: RequestContextProvider;
10
+ projectKey: string;
11
+ });
12
+ debug(obj: object, message: string): void;
13
+ info(obj: object, message: string): void;
14
+ warn(obj: object, message: string): void;
15
+ error(obj: object, message: string): void;
16
+ }
17
+ export {};
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CommercetoolsLogger = exports.defaultFieldsFormatter = void 0;
7
+ const cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
8
+ const set_1 = __importDefault(require("lodash/set"));
9
+ const logform_1 = require("logform");
10
+ const loggers_1 = require("@commercetools-backend/loggers");
11
+ const defaultFieldsFormatter = (defaults) => {
12
+ return (0, logform_1.format)((info) => {
13
+ const clone = (0, cloneDeep_1.default)(info);
14
+ Object.entries(defaults).forEach(([key, value]) => {
15
+ if (value === undefined) {
16
+ // Do nothing
17
+ }
18
+ else if (typeof value === 'object' || typeof value === 'string') {
19
+ (0, set_1.default)(clone, key, value);
20
+ }
21
+ else if (typeof value === 'function') {
22
+ const evaluated = value();
23
+ if (evaluated !== undefined) {
24
+ (0, set_1.default)(clone, key, evaluated);
25
+ }
26
+ }
27
+ });
28
+ return clone;
29
+ })(defaults);
30
+ };
31
+ exports.defaultFieldsFormatter = defaultFieldsFormatter;
32
+ class CommercetoolsLogger {
33
+ logger;
34
+ constructor(opts) {
35
+ this.logger = (0, loggers_1.createApplicationLogger)({
36
+ formatters: [
37
+ (0, exports.defaultFieldsFormatter)({
38
+ projectKey: opts.projectKey,
39
+ correlationId: () => opts.contextProvider.getContextData().correlationId,
40
+ }),
41
+ ],
42
+ });
43
+ }
44
+ debug(obj, message) {
45
+ this.logger.debug(message, obj);
46
+ }
47
+ info(obj, message) {
48
+ this.logger.info(message, obj);
49
+ }
50
+ warn(obj, message) {
51
+ this.logger.warn(message, obj);
52
+ }
53
+ error(obj, message) {
54
+ this.logger.error(message, obj);
55
+ }
56
+ }
57
+ exports.CommercetoolsLogger = CommercetoolsLogger;
@@ -1 +1,2 @@
1
1
  export * from './logger';
2
+ export * from './commercetools-logger';
@@ -15,3 +15,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./logger"), exports);
18
+ __exportStar(require("./commercetools-logger"), exports);
@@ -1,3 +1,4 @@
1
+ import { Logger } from '../..';
1
2
  import { JWTService } from '../services/types/jwt.type';
2
3
  import { HeaderBasedAuthentication, JWTAuthentication } from './authns';
3
4
  import { AuthenticationManager } from './types/authn.type';
@@ -5,10 +6,12 @@ export declare class JWTAuthenticationManager implements AuthenticationManager {
5
6
  private jwtService;
6
7
  private iss;
7
8
  private projectKey;
9
+ private logger;
8
10
  constructor(opts: {
9
11
  jwtService: JWTService;
10
12
  iss: string;
11
13
  projectKey: string;
14
+ logger: Logger;
12
15
  });
13
16
  authenticate(authentication: HeaderBasedAuthentication): Promise<JWTAuthentication>;
14
17
  }
@@ -8,10 +8,12 @@ class JWTAuthenticationManager {
8
8
  jwtService;
9
9
  iss;
10
10
  projectKey;
11
+ logger;
11
12
  constructor(opts) {
12
13
  this.jwtService = opts.jwtService;
13
14
  this.iss = opts.iss;
14
15
  this.projectKey = opts.projectKey;
16
+ this.logger = opts.logger;
15
17
  }
16
18
  async authenticate(authentication) {
17
19
  const principal = authentication.getPrincipal();
@@ -1,3 +1,4 @@
1
+ import { Logger } from '../..';
1
2
  import { Oauth2Service } from '../services/types/oauth2.type';
2
3
  import { HeaderBasedAuthentication, Oauth2Authentication } from './authns';
3
4
  import { AuthenticationManager } from './types/authn.type';
@@ -6,11 +7,13 @@ export declare class Oauth2AuthenticationManager implements AuthenticationManage
6
7
  private clientId;
7
8
  private clientSecret;
8
9
  private authUrl;
10
+ private logger;
9
11
  constructor(opts: {
10
12
  oauth2Service: Oauth2Service;
11
13
  clientId: string;
12
14
  clientSecret: string;
13
15
  authUrl: string;
16
+ logger: Logger;
14
17
  });
15
18
  authenticate(authentication: HeaderBasedAuthentication): Promise<Oauth2Authentication>;
16
19
  private searchPermission;
@@ -9,11 +9,13 @@ class Oauth2AuthenticationManager {
9
9
  clientId;
10
10
  clientSecret;
11
11
  authUrl;
12
+ logger;
12
13
  constructor(opts) {
13
14
  this.oauth2Service = opts.oauth2Service;
14
15
  this.clientId = opts.clientId;
15
16
  this.clientSecret = opts.clientSecret;
16
17
  this.authUrl = opts.authUrl;
18
+ this.logger = opts.logger;
17
19
  }
18
20
  async authenticate(authentication) {
19
21
  const principal = authentication.getPrincipal();
@@ -1,10 +1,13 @@
1
1
  import { AuthenticationManager } from './types/authn.type';
2
2
  import { HeaderBasedAuthentication, SessionAuthentication } from './authns';
3
3
  import { CommercetoolsSessionService } from '../../commercetools';
4
+ import { Logger } from '../..';
4
5
  export declare class SessionHeaderAuthenticationManager implements AuthenticationManager {
5
6
  private sessionService;
7
+ private logger;
6
8
  constructor(opts: {
7
9
  sessionService: CommercetoolsSessionService;
10
+ logger: Logger;
8
11
  });
9
12
  authenticate(authentication: HeaderBasedAuthentication): Promise<SessionAuthentication>;
10
13
  }
@@ -5,8 +5,10 @@ const authns_1 = require("./authns");
5
5
  const errorx_1 = require("../../errorx");
6
6
  class SessionHeaderAuthenticationManager {
7
7
  sessionService;
8
+ logger;
8
9
  constructor(opts) {
9
10
  this.sessionService = opts.sessionService;
11
+ this.logger = opts.logger;
10
12
  }
11
13
  async authenticate(authentication) {
12
14
  const principal = authentication.getPrincipal();
@@ -1,10 +1,13 @@
1
1
  import { AuthenticationManager } from './types/authn.type';
2
2
  import { QueryParamBasedAuthentication, SessionAuthentication } from './authns';
3
3
  import { CommercetoolsSessionService } from '../../commercetools';
4
+ import { Logger } from '../..';
4
5
  export declare class SessionQueryParamAuthenticationManager implements AuthenticationManager {
5
6
  private sessionService;
7
+ private logger;
6
8
  constructor(opts: {
7
9
  sessionService: CommercetoolsSessionService;
10
+ logger: Logger;
8
11
  });
9
12
  authenticate(authentication: QueryParamBasedAuthentication): Promise<SessionAuthentication>;
10
13
  }
@@ -5,8 +5,10 @@ const authns_1 = require("./authns");
5
5
  const errorx_1 = require("../../errorx");
6
6
  class SessionQueryParamAuthenticationManager {
7
7
  sessionService;
8
+ logger;
8
9
  constructor(opts) {
9
10
  this.sessionService = opts.sessionService;
11
+ this.logger = opts.logger;
10
12
  }
11
13
  async authenticate(authentication) {
12
14
  const principal = authentication.getPrincipal();
@@ -1,6 +1,11 @@
1
+ import { Logger } from '../..';
1
2
  import { Authentication } from '../authn/types/authn.type';
2
3
  import { AuthorizationManager } from './types/authz.type';
3
4
  export declare class AuthorityAuthorizationManager implements AuthorizationManager<string[]> {
5
+ private logger;
6
+ constructor(opts: {
7
+ logger: Logger;
8
+ });
4
9
  verify(authentication: Authentication, authorities: string[]): void;
5
10
  check(authentication: Authentication, authorities: string[]): boolean;
6
11
  }
@@ -3,6 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AuthorityAuthorizationManager = void 0;
4
4
  const errorx_1 = require("../../errorx");
5
5
  class AuthorityAuthorizationManager {
6
+ logger;
7
+ constructor(opts) {
8
+ this.logger = opts.logger;
9
+ }
6
10
  verify(authentication, authorities) {
7
11
  const isAuthorized = this.check(authentication, authorities);
8
12
  if (!isAuthorized) {
@@ -1,8 +1,11 @@
1
1
  import { JWTService } from './types/jwt.type';
2
+ import { Logger } from '../..';
2
3
  export declare class DefaultJWTService implements JWTService {
3
4
  private client;
5
+ private logger;
4
6
  constructor(opts: {
5
7
  jwksUrl: string;
8
+ logger: Logger;
6
9
  });
7
10
  verify(opts: {
8
11
  token: string | undefined;
@@ -9,10 +9,12 @@ const jwks_rsa_1 = __importDefault(require("jwks-rsa"));
9
9
  const errorx_1 = require("../../errorx");
10
10
  class DefaultJWTService {
11
11
  client;
12
+ logger;
12
13
  constructor(opts) {
13
14
  this.client = (0, jwks_rsa_1.default)({
14
15
  jwksUri: opts.jwksUrl,
15
16
  });
17
+ this.logger = opts.logger;
16
18
  }
17
19
  async verify(opts) {
18
20
  const getKey = (header, callback) => {
@@ -1,5 +1,10 @@
1
+ import { Logger } from '../..';
1
2
  import { Oauth2Service, TokenInfo } from './types/oauth2.type';
2
3
  export declare class DefaultOauth2Service implements Oauth2Service {
4
+ private logger;
5
+ constructor(opts: {
6
+ logger: Logger;
7
+ });
3
8
  introspectToken(opts: {
4
9
  url: string;
5
10
  clientId: string;
@@ -3,6 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DefaultOauth2Service = void 0;
4
4
  const errorx_1 = require("../../errorx");
5
5
  class DefaultOauth2Service {
6
+ logger;
7
+ constructor(opts) {
8
+ this.logger = opts.logger;
9
+ }
6
10
  async introspectToken(opts) {
7
11
  const urlencoded = new URLSearchParams();
8
12
  urlencoded.append('token', opts.token);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercetools/connect-payments-sdk",
3
- "version": "0.4.4",
3
+ "version": "0.5.0",
4
4
  "description": "Payment SDK for commercetools payment connectors",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -15,9 +15,12 @@
15
15
  ],
16
16
  "license": "ISC",
17
17
  "dependencies": {
18
+ "@commercetools-backend/loggers": "22.23.3",
18
19
  "@commercetools/platform-sdk": "7.7.0",
19
20
  "@commercetools/sdk-client-v2": "2.4.1",
20
21
  "jsonwebtoken": "9.0.2",
21
- "jwks-rsa": "3.1.0"
22
+ "jwks-rsa": "3.1.0",
23
+ "lodash": "4.17.21",
24
+ "logform": "2.6.0"
22
25
  }
23
26
  }