@commercetools/connect-payments-sdk 0.0.1 → 0.0.4

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 (63) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/api/context/types/request-context.type.d.ts +2 -2
  3. package/dist/api/handlers/config.handler.d.ts +1 -1
  4. package/dist/api/handlers/status.handler.d.ts +12 -6
  5. package/dist/api/handlers/status.handler.js +4 -7
  6. package/dist/api/handlers/types/handler.type.d.ts +2 -2
  7. package/dist/api/hooks/jwt-auth.hook.d.ts +16 -0
  8. package/dist/api/hooks/jwt-auth.hook.js +22 -0
  9. package/dist/api/hooks/oauth2-auth.hook.d.ts +16 -0
  10. package/dist/api/hooks/oauth2-auth.hook.js +22 -0
  11. package/dist/api/hooks/session-auth.hook.d.ts +14 -13
  12. package/dist/api/hooks/session-auth.hook.js +18 -27
  13. package/dist/api/hooks/types/hook.type.d.ts +10 -0
  14. package/dist/api/index.d.ts +3 -0
  15. package/dist/api/index.js +3 -0
  16. package/dist/commercetools/index.d.ts +2 -0
  17. package/dist/commercetools/services/ct-authorization.service.d.ts +18 -0
  18. package/dist/commercetools/services/ct-authorization.service.js +42 -0
  19. package/dist/commercetools/services/ct-payment.service.d.ts +6 -1
  20. package/dist/commercetools/services/ct-payment.service.js +72 -0
  21. package/dist/commercetools/services/ct-session.service.d.ts +16 -0
  22. package/dist/commercetools/services/ct-session.service.js +45 -0
  23. package/dist/commercetools/types/api.type.d.ts +11 -0
  24. package/dist/commercetools/types/authorization.type.d.ts +9 -0
  25. package/dist/commercetools/types/payment.type.d.ts +10 -0
  26. package/dist/commercetools/types/session.type.d.ts +28 -0
  27. package/dist/commercetools/types/session.type.js +2 -0
  28. package/dist/errorx/errorx.d.ts +4 -1
  29. package/dist/errorx/errorx.js +15 -4
  30. package/dist/index.d.ts +8 -8
  31. package/dist/index.js +38 -12
  32. package/dist/security/authn/authns.d.ts +49 -0
  33. package/dist/security/authn/authns.js +123 -0
  34. package/dist/security/authn/bearer-utils.d.ts +1 -0
  35. package/dist/security/authn/bearer-utils.js +19 -0
  36. package/dist/security/authn/jwt-authn-manager.d.ts +12 -0
  37. package/dist/security/authn/jwt-authn-manager.js +33 -0
  38. package/dist/security/authn/oauth2-authn-manager.d.ts +17 -0
  39. package/dist/security/authn/oauth2-authn-manager.js +65 -0
  40. package/dist/security/authn/session-authn-manager.d.ts +10 -0
  41. package/dist/security/authn/session-authn-manager.js +25 -0
  42. package/dist/security/authn/types/authn.type.d.ts +27 -0
  43. package/dist/security/authn/types/authn.type.js +2 -0
  44. package/dist/security/index.d.ts +6 -2
  45. package/dist/security/index.js +6 -2
  46. package/dist/security/services/jwt.service.d.ts +10 -0
  47. package/dist/security/services/jwt.service.js +40 -0
  48. package/dist/security/services/oauth2.service.d.ts +7 -14
  49. package/dist/security/services/oauth2.service.js +22 -35
  50. package/dist/security/services/types/jwt.type.d.ts +5 -0
  51. package/dist/security/services/types/jwt.type.js +2 -0
  52. package/dist/security/services/types/oauth2.type.d.ts +14 -0
  53. package/dist/security/services/types/oauth2.type.js +2 -0
  54. package/package.json +5 -3
  55. package/.github/workflows/ci.yml +0 -34
  56. package/.github/workflows/release.yml +0 -46
  57. package/.husky/pre-commit +0 -4
  58. package/dist/security/auth/session.auth.d.ts +0 -20
  59. package/dist/security/auth/session.auth.js +0 -54
  60. package/dist/security/types/oauth2.type.d.ts +0 -13
  61. package/dist/security/types/session.type.d.ts +0 -10
  62. /package/dist/{security/types/oauth2.type.js → api/hooks/types/hook.type.js} +0 -0
  63. /package/dist/{security/types/session.type.js → commercetools/types/authorization.type.js} +0 -0
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ErrorConcurrentModification = exports.ErrorResourceNotFound = exports.ErrorSyntaxError = exports.ErrorRequiredField = exports.ErrorReferencedResourceNotFound = exports.ErrorReferenceExists = exports.ErrorObjectNotFound = exports.ErrorMoneyOverflow = exports.ErrorInternalConstraintViolated = exports.ErrorInvalidField = exports.ErrorInvalidOperation = exports.ErrorInvalidJsonInput = exports.ErrorMissingProjectKey = exports.ErrorGeneral = exports.ErrorAuthErrorResponse = exports.MultiErrorx = exports.Errorx = void 0;
3
+ exports.ErrorMissingAuthenticationInfo = exports.ErrorConcurrentModification = exports.ErrorResourceNotFound = exports.ErrorSyntaxError = exports.ErrorRequiredField = exports.ErrorReferencedResourceNotFound = exports.ErrorReferenceExists = exports.ErrorObjectNotFound = exports.ErrorMoneyOverflow = exports.ErrorInternalConstraintViolated = exports.ErrorInvalidField = exports.ErrorInvalidOperation = exports.ErrorInvalidJsonInput = exports.ErrorMissingProjectKey = exports.ErrorGeneral = exports.ErrorAuthErrorResponse = exports.MultiErrorx = exports.Errorx = void 0;
4
4
  /**
5
5
  * Errorx is a custom error class that extends the native Error class.
6
6
  */
@@ -59,11 +59,11 @@ exports.MultiErrorx = MultiErrorx;
59
59
  * }
60
60
  */
61
61
  class ErrorAuthErrorResponse extends Errorx {
62
- constructor(additionalOpts) {
62
+ constructor(message, additionalOpts, code) {
63
63
  super({
64
- code: 'AuthErrorResponse',
64
+ code: code || 'invalid_token',
65
65
  httpErrorStatus: 401,
66
- message: 'Authentication error.',
66
+ message: message || 'Authentication error.',
67
67
  ...additionalOpts,
68
68
  });
69
69
  }
@@ -324,3 +324,14 @@ class ErrorConcurrentModification extends Errorx {
324
324
  }
325
325
  }
326
326
  exports.ErrorConcurrentModification = ErrorConcurrentModification;
327
+ class ErrorMissingAuthenticationInfo extends Errorx {
328
+ constructor(additionalOpts) {
329
+ super({
330
+ code: 'MissingAuthenticationInfo',
331
+ httpErrorStatus: 400,
332
+ message: 'Not able to identify the user',
333
+ ...additionalOpts,
334
+ });
335
+ }
336
+ }
337
+ exports.ErrorMissingAuthenticationInfo = ErrorMissingAuthenticationInfo;
package/dist/index.d.ts CHANGED
@@ -1,10 +1,9 @@
1
- /// <reference types="node" />
2
- import { RequestContextData, RequestContextProvider } from './api';
1
+ import { JWTAuthenticationHook, Oauth2AuthenticationHook, RequestContextData, RequestContextProvider, SessionAuthenticationHook } from './api';
3
2
  import { DefaultCommercetoolsAPI } from './commercetools/api/root-api';
3
+ import { DefaultAuthorizationService } from './commercetools/services/ct-authorization.service';
4
4
  import { DefaultCartService } from './commercetools/services/ct-cart.service';
5
5
  import { DefaultPaymentService } from './commercetools/services/ct-payment.service';
6
6
  import { Logger } from './logger';
7
- import { DefaultOauth2Service, DefaultSessionAuthenticator } from './security';
8
7
  export * from './api';
9
8
  export * from './commercetools';
10
9
  export * from './errorx';
@@ -14,9 +13,11 @@ export declare const setupPaymentSDK: (opts: {
14
13
  authUrl: string;
15
14
  apiUrl: string;
16
15
  sessionUrl: string;
16
+ jwksUrl: string;
17
17
  clientId: string;
18
18
  clientSecret: string;
19
19
  projectKey: string;
20
+ jwtIssuer: string;
20
21
  getContextFn: () => RequestContextData;
21
22
  updateContextFn: (ctx: Partial<RequestContextData>) => void;
22
23
  logger?: Logger | undefined;
@@ -24,10 +25,9 @@ export declare const setupPaymentSDK: (opts: {
24
25
  ctAPI: DefaultCommercetoolsAPI;
25
26
  ctCartService: DefaultCartService;
26
27
  ctPaymentService: DefaultPaymentService;
27
- oauth2Service: DefaultOauth2Service;
28
- sessionAuthenticator: DefaultSessionAuthenticator;
28
+ ctAuthorizationService: DefaultAuthorizationService;
29
29
  contextProvider: RequestContextProvider;
30
- sessionAuthHookFn: (req: {
31
- headers: import("http").IncomingHttpHeaders;
32
- }) => Promise<void>;
30
+ sessionAuthHookFn: SessionAuthenticationHook;
31
+ jwtAuthHookFn: JWTAuthenticationHook;
32
+ oauth2AuthHookFn: Oauth2AuthenticationHook;
33
33
  };
package/dist/index.js CHANGED
@@ -17,8 +17,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.setupPaymentSDK = void 0;
18
18
  const api_1 = require("./api");
19
19
  const root_api_1 = require("./commercetools/api/root-api");
20
+ const ct_authorization_service_1 = require("./commercetools/services/ct-authorization.service");
20
21
  const ct_cart_service_1 = require("./commercetools/services/ct-cart.service");
21
22
  const ct_payment_service_1 = require("./commercetools/services/ct-payment.service");
23
+ const ct_session_service_1 = require("./commercetools/services/ct-session.service");
22
24
  const base_decorator_1 = require("./fetch/decorators/base.decorator");
23
25
  const monitoring_decorator_1 = require("./fetch/decorators/monitoring.decorator");
24
26
  const security_1 = require("./security");
@@ -32,6 +34,8 @@ const setupPaymentSDK = (opts) => {
32
34
  getContextFn: opts.getContextFn,
33
35
  updateContextFn: opts.updateContextFn,
34
36
  });
37
+ const fetcher = new monitoring_decorator_1.MonitoringFetcherDecorator(new base_decorator_1.BasicFetcher(), contextProvider);
38
+ const decoratedFetch = fetcher.run.bind(fetcher);
35
39
  const ctAPI = new root_api_1.DefaultCommercetoolsAPI({
36
40
  apiUrl: opts.apiUrl,
37
41
  authUrl: opts.authUrl,
@@ -42,33 +46,55 @@ const setupPaymentSDK = (opts) => {
42
46
  });
43
47
  const ctCartService = new ct_cart_service_1.DefaultCartService({ ctAPI });
44
48
  const ctPaymentService = new ct_payment_service_1.DefaultPaymentService({ ctAPI });
45
- const fetcher = new monitoring_decorator_1.MonitoringFetcherDecorator(new base_decorator_1.BasicFetcher(), contextProvider);
46
- const decoratedFetch = fetcher.run.bind(fetcher);
47
- const oauth2Service = new security_1.DefaultOauth2Service({
49
+ const ctAuthorizationService = new ct_authorization_service_1.DefaultAuthorizationService({
48
50
  authUrl: opts.authUrl,
51
+ clientId: opts.clientId,
52
+ clientSecret: opts.clientSecret,
49
53
  fetch: decoratedFetch,
50
- logger: opts.logger,
51
54
  });
52
- const sessionAuthenticator = new security_1.DefaultSessionAuthenticator({
55
+ const sessionService = new ct_session_service_1.DefaultSessionService({
56
+ authorizationService: ctAuthorizationService,
57
+ sessionUrl: opts.sessionUrl,
58
+ projectKey: opts.projectKey,
59
+ });
60
+ const oauth2Service = new security_1.DefaultOauth2Service();
61
+ const jwtService = new security_1.DefaultJWTService({
62
+ jwksUrl: opts.jwksUrl,
63
+ });
64
+ const sessionAuthenticationManager = new security_1.SessionAuthenticationManager({
65
+ sessionService,
66
+ });
67
+ const oauth2AuthenticationManager = new security_1.Oauth2AuthenticationManager({
53
68
  oauth2Service,
54
69
  clientId: opts.clientId,
55
70
  clientSecret: opts.clientSecret,
56
- projectKey: opts.projectKey,
57
- sessionUrl: opts.sessionUrl,
58
- fetch: decoratedFetch,
71
+ authUrl: opts.authUrl,
72
+ });
73
+ const jwtAuthenticationManager = new security_1.JWTAuthenticationManager({
74
+ jwtService,
75
+ iss: opts.jwtIssuer,
59
76
  });
60
- const sessionAuthHookFn = (0, api_1.sessionAuthHook)({
77
+ const sessionAuthHookFn = new api_1.SessionAuthenticationHook({
78
+ authenticationManager: sessionAuthenticationManager,
79
+ contextProvider,
80
+ });
81
+ const jwtAuthHookFn = new api_1.JWTAuthenticationHook({
82
+ authenticationManager: jwtAuthenticationManager,
83
+ contextProvider,
84
+ });
85
+ const oauth2AuthHookFn = new api_1.Oauth2AuthenticationHook({
86
+ authenticationManager: oauth2AuthenticationManager,
61
87
  contextProvider,
62
- sessionAuthenticator,
63
88
  });
64
89
  return {
65
90
  ctAPI,
66
91
  ctCartService,
67
92
  ctPaymentService,
68
- oauth2Service,
69
- sessionAuthenticator,
93
+ ctAuthorizationService,
70
94
  contextProvider,
71
95
  sessionAuthHookFn,
96
+ jwtAuthHookFn,
97
+ oauth2AuthHookFn,
72
98
  };
73
99
  };
74
100
  exports.setupPaymentSDK = setupPaymentSDK;
@@ -0,0 +1,49 @@
1
+ import { Authentication, HeaderPrincipal, JWTPrincipal, Oauth2Principal, SessionPrincipal } from './types/authn.type';
2
+ export declare class SessionAuthentication implements Authentication<SessionPrincipal, string> {
3
+ private principal;
4
+ private authorities;
5
+ private sessionId;
6
+ private authenticated;
7
+ constructor(sessionId: string, principal: SessionPrincipal);
8
+ hasPrincipal(): boolean;
9
+ getAuthorities(): string[];
10
+ hasCredentials(): boolean;
11
+ getPrincipal(): SessionPrincipal;
12
+ getCredentials(): string;
13
+ isAuthenticated(): boolean;
14
+ }
15
+ export declare class HeaderBasedAuthentication implements Authentication<HeaderPrincipal, string> {
16
+ private authHeader;
17
+ constructor(authHeader: string);
18
+ hasPrincipal(): boolean;
19
+ getAuthorities(): string[];
20
+ hasCredentials(): boolean;
21
+ getCredentials(): string;
22
+ getPrincipal(): HeaderPrincipal;
23
+ isAuthenticated(): boolean;
24
+ }
25
+ export declare class Oauth2Authentication implements Authentication<Oauth2Principal, string> {
26
+ private principal;
27
+ private authorities;
28
+ private authenticated;
29
+ private accessToken;
30
+ constructor(accessToken: string, principal: Oauth2Principal);
31
+ hasPrincipal(): boolean;
32
+ getAuthorities(): string[];
33
+ hasCredentials(): boolean;
34
+ getPrincipal(): Oauth2Principal;
35
+ getCredentials(): string;
36
+ isAuthenticated(): boolean;
37
+ }
38
+ export declare class JWTAuthentication implements Authentication<JWTPrincipal, string> {
39
+ private principal;
40
+ private authenticated;
41
+ private jwt;
42
+ constructor(jwt: string, principal: JWTPrincipal);
43
+ hasPrincipal(): boolean;
44
+ getAuthorities(): string[];
45
+ hasCredentials(): boolean;
46
+ getPrincipal(): JWTPrincipal;
47
+ getCredentials(): string;
48
+ isAuthenticated(): boolean;
49
+ }
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JWTAuthentication = exports.Oauth2Authentication = exports.HeaderBasedAuthentication = exports.SessionAuthentication = void 0;
4
+ class SessionAuthentication {
5
+ principal;
6
+ authorities;
7
+ sessionId;
8
+ authenticated;
9
+ constructor(sessionId, principal) {
10
+ this.principal = principal;
11
+ this.sessionId = sessionId;
12
+ this.authenticated = true;
13
+ }
14
+ hasPrincipal() {
15
+ return this.getPrincipal() !== undefined;
16
+ }
17
+ getAuthorities() {
18
+ return this.authorities;
19
+ }
20
+ hasCredentials() {
21
+ return this.getCredentials() !== undefined;
22
+ }
23
+ getPrincipal() {
24
+ return this.principal;
25
+ }
26
+ getCredentials() {
27
+ return this.sessionId;
28
+ }
29
+ isAuthenticated() {
30
+ return this.authenticated;
31
+ }
32
+ }
33
+ exports.SessionAuthentication = SessionAuthentication;
34
+ class HeaderBasedAuthentication {
35
+ authHeader;
36
+ constructor(authHeader) {
37
+ this.authHeader = authHeader;
38
+ }
39
+ hasPrincipal() {
40
+ return this.getPrincipal() != undefined;
41
+ }
42
+ getAuthorities() {
43
+ return [];
44
+ }
45
+ hasCredentials() {
46
+ return this.getCredentials() != undefined;
47
+ }
48
+ getCredentials() {
49
+ return this.authHeader;
50
+ }
51
+ getPrincipal() {
52
+ return {
53
+ authHeader: this.authHeader,
54
+ };
55
+ }
56
+ isAuthenticated() {
57
+ return false;
58
+ }
59
+ }
60
+ exports.HeaderBasedAuthentication = HeaderBasedAuthentication;
61
+ class Oauth2Authentication {
62
+ principal;
63
+ authorities;
64
+ authenticated;
65
+ accessToken;
66
+ constructor(accessToken, principal) {
67
+ this.principal = principal;
68
+ this.authorities = principal.scope
69
+ .split(' ')
70
+ .map((scope) => scope.split(':')[0])
71
+ .filter((scope) => scope !== '');
72
+ this.authenticated = true;
73
+ this.accessToken = accessToken;
74
+ }
75
+ hasPrincipal() {
76
+ return this.getPrincipal() !== undefined;
77
+ }
78
+ getAuthorities() {
79
+ return this.authorities;
80
+ }
81
+ hasCredentials() {
82
+ return this.getCredentials() !== undefined;
83
+ }
84
+ getPrincipal() {
85
+ return this.principal;
86
+ }
87
+ getCredentials() {
88
+ return this.accessToken;
89
+ }
90
+ isAuthenticated() {
91
+ return this.authenticated;
92
+ }
93
+ }
94
+ exports.Oauth2Authentication = Oauth2Authentication;
95
+ class JWTAuthentication {
96
+ principal;
97
+ authenticated;
98
+ jwt;
99
+ constructor(jwt, principal) {
100
+ this.principal = principal;
101
+ this.authenticated = true;
102
+ this.jwt = jwt;
103
+ }
104
+ hasPrincipal() {
105
+ return this.getPrincipal() !== undefined;
106
+ }
107
+ getAuthorities() {
108
+ return [];
109
+ }
110
+ hasCredentials() {
111
+ return this.getCredentials() !== undefined;
112
+ }
113
+ getPrincipal() {
114
+ return this.principal;
115
+ }
116
+ getCredentials() {
117
+ return this.jwt;
118
+ }
119
+ isAuthenticated() {
120
+ return this.authenticated;
121
+ }
122
+ }
123
+ exports.JWTAuthentication = JWTAuthentication;
@@ -0,0 +1 @@
1
+ export declare const validateBearerAuthorization: (authorization: string | undefined) => string;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateBearerAuthorization = void 0;
4
+ const errorx_1 = require("../../errorx");
5
+ const validateBearerAuthorization = (authorization) => {
6
+ if (!authorization) {
7
+ throw new errorx_1.ErrorAuthErrorResponse('This endpoint requires the authorization header.', {
8
+ skipLog: true,
9
+ }, 'access_denied');
10
+ }
11
+ const authorizationParts = authorization.split(' ');
12
+ if (authorizationParts.length !== 2 || authorizationParts[0] !== 'Bearer') {
13
+ throw new errorx_1.ErrorAuthErrorResponse(`Authorization header must have the format 'Bearer <token>'`, {
14
+ skipLog: true,
15
+ }, 'invalid_request');
16
+ }
17
+ return authorizationParts[1];
18
+ };
19
+ exports.validateBearerAuthorization = validateBearerAuthorization;
@@ -0,0 +1,12 @@
1
+ import { JWTService } from '../services/types/jwt.type';
2
+ import { HeaderBasedAuthentication, JWTAuthentication } from './authns';
3
+ import { AuthenticationManager } from './types/authn.type';
4
+ export declare class JWTAuthenticationManager implements AuthenticationManager {
5
+ private jwtService;
6
+ private iss;
7
+ constructor(opts: {
8
+ jwtService: JWTService;
9
+ iss: string;
10
+ });
11
+ authenticate(authentication: HeaderBasedAuthentication): Promise<JWTAuthentication>;
12
+ }
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JWTAuthenticationManager = void 0;
4
+ const errorx_1 = require("../../errorx");
5
+ const authns_1 = require("./authns");
6
+ const bearer_utils_1 = require("./bearer-utils");
7
+ class JWTAuthenticationManager {
8
+ jwtService;
9
+ iss;
10
+ constructor(opts) {
11
+ this.jwtService = opts.jwtService;
12
+ this.iss = opts.iss;
13
+ }
14
+ async authenticate(authentication) {
15
+ const principal = authentication.getPrincipal();
16
+ const token = (0, bearer_utils_1.validateBearerAuthorization)(principal.authHeader);
17
+ const decodedToken = (await this.jwtService.verify({
18
+ token,
19
+ }));
20
+ if (decodedToken.iss !== this.iss) {
21
+ throw new errorx_1.ErrorAuthErrorResponse('Issuer in the token does not match the expected issuer', {
22
+ privateFields: {
23
+ expectedIssuer: this.iss,
24
+ actualIssuer: decodedToken['iss'],
25
+ },
26
+ });
27
+ }
28
+ return new authns_1.JWTAuthentication(token, {
29
+ mcCustomerId: decodedToken['sub'],
30
+ });
31
+ }
32
+ }
33
+ exports.JWTAuthenticationManager = JWTAuthenticationManager;
@@ -0,0 +1,17 @@
1
+ import { Oauth2Service } from '../services/types/oauth2.type';
2
+ import { HeaderBasedAuthentication, Oauth2Authentication } from './authns';
3
+ import { AuthenticationManager } from './types/authn.type';
4
+ export declare class Oauth2AuthenticationManager implements AuthenticationManager {
5
+ private oauth2Service;
6
+ private clientId;
7
+ private clientSecret;
8
+ private authUrl;
9
+ constructor(opts: {
10
+ oauth2Service: Oauth2Service;
11
+ clientId: string;
12
+ clientSecret: string;
13
+ authUrl: string;
14
+ });
15
+ authenticate(authentication: HeaderBasedAuthentication): Promise<Oauth2Authentication>;
16
+ private searchPermission;
17
+ }
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Oauth2AuthenticationManager = void 0;
4
+ const errorx_1 = require("../../errorx");
5
+ const authns_1 = require("./authns");
6
+ const bearer_utils_1 = require("./bearer-utils");
7
+ class Oauth2AuthenticationManager {
8
+ oauth2Service;
9
+ clientId;
10
+ clientSecret;
11
+ authUrl;
12
+ constructor(opts) {
13
+ this.oauth2Service = opts.oauth2Service;
14
+ this.clientId = opts.clientId;
15
+ this.clientSecret = opts.clientSecret;
16
+ this.authUrl = opts.authUrl;
17
+ }
18
+ async authenticate(authentication) {
19
+ const principal = authentication.getPrincipal();
20
+ const authorizationHeader = principal.authHeader;
21
+ const token = (0, bearer_utils_1.validateBearerAuthorization)(authorizationHeader);
22
+ const tokenIntrospectionResponseData = await this.oauth2Service.introspectToken({
23
+ url: `${this.authUrl}/oauth/introspect`,
24
+ clientId: this.clientId,
25
+ clientSecret: this.clientSecret,
26
+ token,
27
+ });
28
+ if (!tokenIntrospectionResponseData.active) {
29
+ throw new errorx_1.ErrorAuthErrorResponse('invalid_token', {
30
+ skipLog: true,
31
+ });
32
+ }
33
+ const scopes = tokenIntrospectionResponseData.scope?.split(' ') ?? null;
34
+ if (!scopes) {
35
+ throw new errorx_1.ErrorAuthErrorResponse('Token has no scopes.', {
36
+ skipLog: true,
37
+ });
38
+ }
39
+ // Search for customer_id:<customer> scope
40
+ const customerPermission = this.searchPermission(scopes, 'customer_id');
41
+ // Search for anonymous_id:<anonymous> scope
42
+ const anonymousPermission = this.searchPermission(scopes, 'anonymous_id');
43
+ return new authns_1.Oauth2Authentication(token, {
44
+ scope: tokenIntrospectionResponseData.scope,
45
+ clientId: tokenIntrospectionResponseData.client_id,
46
+ customerId: customerPermission?.principal,
47
+ anonymousId: anonymousPermission?.principal,
48
+ });
49
+ }
50
+ searchPermission(scopes, ...permissions) {
51
+ for (const permission of permissions) {
52
+ // Search for customer_id:<customer> scope
53
+ const permissionIndex = scopes.findIndex((element) => element.startsWith(`${permission}`));
54
+ if (permissionIndex >= 0) {
55
+ const splitPermission = scopes[permissionIndex].split(':');
56
+ return {
57
+ permission: splitPermission[0],
58
+ principal: splitPermission[1],
59
+ };
60
+ }
61
+ }
62
+ return undefined;
63
+ }
64
+ }
65
+ exports.Oauth2AuthenticationManager = Oauth2AuthenticationManager;
@@ -0,0 +1,10 @@
1
+ import { AuthenticationManager } from './types/authn.type';
2
+ import { HeaderBasedAuthentication, SessionAuthentication } from './authns';
3
+ import { CommercetoolsSessionService } from '../../commercetools';
4
+ export declare class SessionAuthenticationManager implements AuthenticationManager {
5
+ private sessionService;
6
+ constructor(opts: {
7
+ sessionService: CommercetoolsSessionService;
8
+ });
9
+ authenticate(authentication: HeaderBasedAuthentication): Promise<SessionAuthentication>;
10
+ }
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SessionAuthenticationManager = void 0;
4
+ const authns_1 = require("./authns");
5
+ const errorx_1 = require("../../errorx");
6
+ class SessionAuthenticationManager {
7
+ sessionService;
8
+ constructor(opts) {
9
+ this.sessionService = opts.sessionService;
10
+ }
11
+ async authenticate(authentication) {
12
+ const principal = authentication.getPrincipal();
13
+ try {
14
+ const session = await this.sessionService.verifySession(principal.authHeader);
15
+ return new authns_1.SessionAuthentication(principal.authHeader, {
16
+ cartId: this.sessionService.getCartFromSession(session),
17
+ allowedPaymentMethods: this.sessionService.getAllowedPaymentMethodsFromSession(session),
18
+ });
19
+ }
20
+ catch (e) {
21
+ throw new errorx_1.ErrorAuthErrorResponse('Session is not active');
22
+ }
23
+ }
24
+ }
25
+ exports.SessionAuthenticationManager = SessionAuthenticationManager;
@@ -0,0 +1,27 @@
1
+ export interface AuthenticationManager {
2
+ authenticate(authentication: Authentication): Promise<Authentication> | Authentication;
3
+ }
4
+ export interface Authentication<Principal = unknown, Credentials = unknown> {
5
+ hasPrincipal(): boolean;
6
+ getAuthorities(): string[];
7
+ hasCredentials(): boolean;
8
+ getPrincipal(): Principal;
9
+ getCredentials(): Credentials;
10
+ isAuthenticated(): boolean;
11
+ }
12
+ export type HeaderPrincipal = {
13
+ authHeader: string;
14
+ };
15
+ export type SessionPrincipal = {
16
+ cartId: string;
17
+ allowedPaymentMethods: string[];
18
+ };
19
+ export type Oauth2Principal = {
20
+ clientId: string;
21
+ scope: string;
22
+ customerId?: string;
23
+ anonymousId?: string;
24
+ };
25
+ export type JWTPrincipal = {
26
+ mcCustomerId?: string;
27
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,3 +1,7 @@
1
- export * from './auth/session.auth';
1
+ export * from './authn/authns';
2
+ export * from './authn/jwt-authn-manager';
3
+ export * from './authn/oauth2-authn-manager';
4
+ export * from './authn/session-authn-manager';
5
+ export * from './authn/types/authn.type';
6
+ export * from './services/jwt.service';
2
7
  export * from './services/oauth2.service';
3
- export * from './types/session.type';
@@ -14,6 +14,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./auth/session.auth"), exports);
17
+ __exportStar(require("./authn/authns"), exports);
18
+ __exportStar(require("./authn/jwt-authn-manager"), exports);
19
+ __exportStar(require("./authn/oauth2-authn-manager"), exports);
20
+ __exportStar(require("./authn/session-authn-manager"), exports);
21
+ __exportStar(require("./authn/types/authn.type"), exports);
22
+ __exportStar(require("./services/jwt.service"), exports);
18
23
  __exportStar(require("./services/oauth2.service"), exports);
19
- __exportStar(require("./types/session.type"), exports);
@@ -0,0 +1,10 @@
1
+ import { JWTService } from './types/jwt.type';
2
+ export declare class DefaultJWTService implements JWTService {
3
+ private client;
4
+ constructor(opts: {
5
+ jwksUrl: string;
6
+ });
7
+ verify(opts: {
8
+ token: string | undefined;
9
+ }): Promise<unknown>;
10
+ }
@@ -0,0 +1,40 @@
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.DefaultJWTService = void 0;
7
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
+ const jwks_rsa_1 = __importDefault(require("jwks-rsa"));
9
+ const errorx_1 = require("../../errorx");
10
+ class DefaultJWTService {
11
+ client;
12
+ constructor(opts) {
13
+ this.client = (0, jwks_rsa_1.default)({
14
+ jwksUri: opts.jwksUrl,
15
+ });
16
+ }
17
+ async verify(opts) {
18
+ const getKey = (header, callback) => {
19
+ this.client.getSigningKey(header.kid, function (err, key) {
20
+ if (err) {
21
+ return callback(err);
22
+ }
23
+ const signingKey = key.getPublicKey();
24
+ callback(null, signingKey);
25
+ });
26
+ };
27
+ return new Promise((resolve, reject) => {
28
+ if (!opts.token) {
29
+ throw new errorx_1.ErrorAuthErrorResponse('Token is missing');
30
+ }
31
+ jsonwebtoken_1.default.verify(opts.token, getKey, {}, function (err, decoded) {
32
+ if (err) {
33
+ return reject(new errorx_1.ErrorAuthErrorResponse(err.message, { privateMessage: err.message, cause: err }));
34
+ }
35
+ return resolve(decoded);
36
+ });
37
+ });
38
+ }
39
+ }
40
+ exports.DefaultJWTService = DefaultJWTService;
@@ -1,16 +1,9 @@
1
- import { Fetch } from '../../fetch/types/fetch.type';
2
- import { Logger } from '../../logger';
3
- import { GetAccessTokenParams, Oauth2Service, TokenResponse } from '../types/oauth2.type';
1
+ import { Oauth2Service, TokenInfo } from './types/oauth2.type';
4
2
  export declare class DefaultOauth2Service implements Oauth2Service {
5
- private authUrl;
6
- private fetch;
7
- private logger?;
8
- constructor(opts: {
9
- authUrl: string;
10
- fetch: Fetch;
11
- logger?: Logger;
12
- });
13
- private oauth2tokenCache;
14
- private oauth2tokenKey;
15
- getAccessToken(opts: GetAccessTokenParams): Promise<TokenResponse>;
3
+ introspectToken(opts: {
4
+ url: string;
5
+ clientId: string;
6
+ clientSecret: string;
7
+ token: string;
8
+ }): Promise<TokenInfo>;
16
9
  }