@labdigital/commercetools-mock 2.10.0 → 2.12.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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@labdigital/commercetools-mock",
3
3
  "author": "Michael van Tellingen",
4
- "version": "2.10.0",
4
+ "version": "2.12.0",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.cjs",
7
7
  "module": "dist/index.js",
package/src/exceptions.ts CHANGED
@@ -21,3 +21,10 @@ export interface InvalidRequestError {
21
21
  readonly code: 'invalid_request'
22
22
  readonly message: string
23
23
  }
24
+
25
+ export interface AuthError {
26
+ readonly statusCode: number
27
+ readonly message: string
28
+ readonly error: string
29
+ readonly error_description: string
30
+ }
@@ -0,0 +1,89 @@
1
+ import { describe, it, expect, beforeEach } from 'vitest'
2
+ import express from 'express'
3
+ import supertest from 'supertest'
4
+ import { OAuth2Server } from './server'
5
+
6
+ describe('OAuth2Server', () => {
7
+ let app: express.Express
8
+ let server: OAuth2Server
9
+
10
+ beforeEach(() => {
11
+ server = new OAuth2Server({ enabled: true, validate: false })
12
+ app = express()
13
+ app.use(server.createRouter())
14
+ })
15
+
16
+ describe('POST /token', () => {
17
+ it('should return a token for valid client credentials', async () => {
18
+ const response = await supertest(app)
19
+ .post('/token')
20
+ .auth('validClientId', 'validClientSecret')
21
+ .query({ grant_type: 'client_credentials' })
22
+ .send()
23
+
24
+ const body = await response.body
25
+
26
+ expect(response.status, JSON.stringify(body)).toBe(200)
27
+ expect(body).toHaveProperty('access_token')
28
+ })
29
+
30
+ it('should failed on invalid refresh token', async () => {
31
+ const response = await supertest(app)
32
+ .post('/token')
33
+ .auth('validClientId', 'validClientSecret')
34
+ .query({ grant_type: 'refresh_token', refresh_token: 'invalid' })
35
+ .send()
36
+
37
+ const body = await response.body
38
+
39
+ expect(response.status, JSON.stringify(body)).toBe(400)
40
+ })
41
+
42
+ it('should refresh a token', async () => {
43
+ const createResponse = await supertest(app)
44
+ .post(`/my-project/anonymous/token`)
45
+ .auth('validClientId', 'validClientSecret')
46
+ .query({ grant_type: 'client_credentials' })
47
+ .send()
48
+
49
+ const refreshToken = createResponse.body.refresh_token
50
+
51
+ const response = await supertest(app)
52
+ .post('/token')
53
+ .auth('validClientId', 'validClientSecret')
54
+ .query({ grant_type: 'refresh_token', refresh_token: refreshToken })
55
+ .send()
56
+
57
+ const body = await response.body
58
+
59
+ expect(response.status, JSON.stringify(body)).toBe(200)
60
+ expect(body.access_token).not.toBe(createResponse.body.access_token)
61
+ expect(body.refresh_token).toBeUndefined()
62
+ })
63
+ })
64
+
65
+ describe('POST /:projectKey/anonymous/token', () => {
66
+ it('should return a token for anonymous access', async () => {
67
+ const projectKey = 'test-project'
68
+
69
+ const response = await supertest(app)
70
+ .post(`/${projectKey}/anonymous/token`)
71
+ .auth('validClientId', 'validClientSecret')
72
+ .query({ grant_type: 'client_credentials' })
73
+ .send()
74
+
75
+ expect(response.status).toBe(200)
76
+ expect(response.body).toHaveProperty('access_token')
77
+
78
+ const matches = response.body.scope?.match(
79
+ /(customer_id|anonymous_id):([^\s]+)/
80
+ )
81
+ if (matches) {
82
+ expect(matches[1]).toBe('anonymous_id')
83
+ expect(matches[2]).toBeDefined()
84
+ } else {
85
+ expect(response.body.scope).toBe('')
86
+ }
87
+ })
88
+ })
89
+ })
@@ -6,7 +6,11 @@ import express, {
6
6
  type Response,
7
7
  } from 'express'
8
8
  import { InvalidTokenError } from '@commercetools/platform-sdk'
9
- import { CommercetoolsError, InvalidRequestError } from '../exceptions.js'
9
+ import {
10
+ AuthError,
11
+ CommercetoolsError,
12
+ InvalidRequestError,
13
+ } from '../exceptions.js'
10
14
  import { InvalidClientError, UnsupportedGrantType } from './errors.js'
11
15
  import { OAuth2Store } from './store.js'
12
16
  import { getBearerToken } from './helpers.js'
@@ -160,11 +164,37 @@ export class OAuth2Server {
160
164
  )
161
165
  return response.status(200).send(token)
162
166
  } else if (grantType === 'refresh_token') {
163
- const token = this.store.getClientToken(
167
+ const refreshToken = request.query.refresh_token?.toString()
168
+ if (!refreshToken) {
169
+ return next(
170
+ new CommercetoolsError<InvalidRequestError>(
171
+ {
172
+ code: 'invalid_request',
173
+ message: 'Missing required parameter: refresh_token.',
174
+ },
175
+ 400
176
+ )
177
+ )
178
+ }
179
+ const token = this.store.refreshToken(
164
180
  request.credentials.clientId,
165
181
  request.credentials.clientSecret,
166
- request.query.scope?.toString()
182
+ refreshToken
167
183
  )
184
+ if (!token) {
185
+ return next(
186
+ new CommercetoolsError<AuthError>(
187
+ {
188
+ statusCode: 400,
189
+ message: 'The refresh token was not found. It may have expired.',
190
+ error: 'invalid_grant',
191
+ error_description:
192
+ 'The refresh token was not found. It may have expired.',
193
+ },
194
+ 400
195
+ )
196
+ )
197
+ }
168
198
  return response.status(200).send(token)
169
199
  } else {
170
200
  return next(
@@ -250,14 +280,27 @@ export class OAuth2Server {
250
280
  response: Response,
251
281
  next: NextFunction
252
282
  ) {
253
- return next(
254
- new CommercetoolsError<InvalidClientError>(
255
- {
256
- code: 'invalid_client',
257
- message: 'Not implemented yet in commercetools-mock',
258
- },
259
- 401
283
+ const grantType = request.query.grant_type || request.body.grant_type
284
+ if (!grantType) {
285
+ return next(
286
+ new CommercetoolsError<InvalidRequestError>(
287
+ {
288
+ code: 'invalid_request',
289
+ message: 'Missing required parameter: grant_type.',
290
+ },
291
+ 400
292
+ )
260
293
  )
261
- )
294
+ }
295
+
296
+ if (grantType === 'client_credentials') {
297
+ const scope =
298
+ request.query.scope?.toString() || request.body.scope?.toString()
299
+
300
+ const anonymous_id = undefined
301
+
302
+ const token = this.store.getAnonymousToken(scope, anonymous_id)
303
+ return response.status(200).send(token)
304
+ }
262
305
  }
263
306
  }
@@ -1,10 +1,12 @@
1
1
  import { randomBytes } from 'crypto'
2
+ import { v4 as uuidv4 } from 'uuid'
2
3
 
3
4
  type Token = {
4
5
  access_token: string
5
6
  token_type: 'Bearer'
6
7
  expires_in: number
7
8
  scope: string
9
+ refresh_token?: string
8
10
  }
9
11
 
10
12
  export class OAuth2Store {
@@ -21,6 +23,24 @@ export class OAuth2Store {
21
23
  token_type: 'Bearer',
22
24
  expires_in: 172800,
23
25
  scope: scope || 'todo',
26
+ refresh_token: `my-project-${randomBytes(16).toString('base64')}`,
27
+ }
28
+ this.tokens.push(token)
29
+ return token
30
+ }
31
+
32
+ getAnonymousToken(scope: string, anonymousId: string | undefined) {
33
+ if (!anonymousId) {
34
+ anonymousId = uuidv4()
35
+ }
36
+ const token: Token = {
37
+ access_token: randomBytes(16).toString('base64'),
38
+ token_type: 'Bearer',
39
+ expires_in: 172800,
40
+ scope: scope
41
+ ? `${scope} anonymous_id:${anonymousId}`
42
+ : `anonymous_id:${anonymousId}`,
43
+ refresh_token: `my-project-${randomBytes(16).toString('base64')}`,
24
44
  }
25
45
  this.tokens.push(token)
26
46
  return token
@@ -32,13 +52,34 @@ export class OAuth2Store {
32
52
  token_type: 'Bearer',
33
53
  expires_in: 172800,
34
54
  scope: scope
35
- ? `${scope} custome_id:${customerId}`
36
- : `customer_id: ${customerId}`,
55
+ ? `${scope} customer_id:${customerId}`
56
+ : `customer_id:${customerId}`,
57
+ refresh_token: `my-project-${randomBytes(16).toString('base64')}`,
37
58
  }
38
59
  this.tokens.push(token)
39
60
  return token
40
61
  }
41
62
 
63
+ refreshToken(clientId: string, clientSecret: string, refreshToken: string) {
64
+ const existing = this.tokens.find((t) => t.refresh_token === refreshToken)
65
+ if (!existing) {
66
+ return undefined
67
+ }
68
+ const token: Token = {
69
+ ...existing,
70
+ access_token: randomBytes(16).toString('base64'),
71
+ }
72
+ this.tokens.push(token)
73
+
74
+ // We don't want to return the refresh_token again
75
+ return {
76
+ access_token: token.access_token,
77
+ token_type: token.token_type,
78
+ expires_in: token.expires_in,
79
+ scope: token.scope,
80
+ }
81
+ }
82
+
42
83
  validateToken(token: string) {
43
84
  if (!this.validate) return true
44
85