-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: introduce new package @commercetools-backend/express with utili…
…ties for working with Custom Applications (#1447) * feat: introduce new package server-express with utilities for working with Custom Applications * refactor: improve logic and constants * chore: move package to packages-backend folder * refactor: rename package * chore: remove build files * fix: tsconfig
- Loading branch information
Showing
19 changed files
with
606 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
_translations/ | ||
dist/ | ||
build/ | ||
node_modules/* | ||
**/node_modules/* | ||
packages/application-shell/test-utils/index.js | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,6 +3,7 @@ npm | |
linting | ||
serverless | ||
Node.js | ||
Express.js | ||
Webpack | ||
Transifex | ||
graphql | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
build |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2020 commercetools GmbH | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
# @commercetools-backend/express | ||
|
||
<p align="center"> | ||
<a href="https://www.npmjs.com/package/@commercetools-backend/express"><img src="https://badgen.net/npm/v/@commercetools-backend/express" alt="Latest release (latest dist-tag)" /></a> <a href="https://www.npmjs.com/package/@commercetools-backend/express"><img src="https://badgen.net/npm/v/@commercetools-backend/express/next" alt="Latest release (next dist-tag)" /></a> <a href="https://bundlephobia.com/result?p=@commercetools-backend/express"><img src="https://badgen.net/bundlephobia/minzip/@commercetools-backend/express" alt="Minified + GZipped size" /></a> <a href="https://github.com/commercetools/merchant-center-application-kit/blob/master/LICENSE"><img src="https://badgen.net/github/license/commercetools/merchant-center-application-kit" alt="GitHub license" /></a> | ||
</p> | ||
|
||
Zero-config HTTP server as Express.js to facilitate development. | ||
|
||
This package is primarily built for HTTP servers used by Custom Applications and it provides a set of components to facilitate the development of the HTTP server. | ||
|
||
## Install | ||
|
||
```bash | ||
$ npm install --save @commercetools-backend/express | ||
``` | ||
|
||
## Session middleware | ||
|
||
This middleware should be used to handle the authentication exchange between the server and the `/proxy/forward-to` endpoint of the Merchant Center API Gateway. | ||
|
||
> You can read more about the "Proxy to External API" concepts [here](https://docs.commercetools.com/custom-applications/main-concepts/proxy-to-external-api). | ||
```js | ||
const { | ||
createSessionMiddleware, | ||
CLOUD_IDENTIFIERS, | ||
} = require('@commercetools-backend/express'); | ||
|
||
app.use(createSessionMiddleware({ mcApiUrl: CLOUD_IDENTIFIERS.GCP_EU })); | ||
app.use((request, response, next) => { | ||
// `request.session` contains the useful information | ||
}); | ||
``` | ||
|
||
### Middleware options | ||
|
||
- `issuer` (_string_): either a cloud identifier or a valid URL to the Merchant Center API Gateway. The cloud identifier maps to the Merchant Center API URL of the related [cloud region](https://docs.commercetools.com/custom-applications/main-concepts/api-gateway#cloud-regions). | ||
|
||
- `gcp-au`: `https://mc-api.australia-southeast1.gcp.commercetools.com` | ||
- `gcp-eu`: `https://mc-api.europe-west1.gcp.commercetools.com` | ||
- `gcp-us`: `https://mc-api.us-central1.gcp.commercetools.com` | ||
- `aws-fra`: `https://mc-api.eu-central-1.aws.commercetools.com` | ||
- `aws-ohio`: `https://mc-api.us-east-2.aws.commercetools.com` | ||
|
||
- `inferIssuer` (_boolean_): determines whether the issuer should be inferred from the custom request HTTP header `x-mc-api-cloud-identifier` which is sent by the Merchant Center API Gateway when forwarding the request. This might be useful in case the server is used in multiple regions. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
{ | ||
"name": "@commercetools-backend/express", | ||
"version": "16.5.3", | ||
"description": "Zero-config HTTP server as Express.js to facilitate development", | ||
"bugs": "https://github.com/commercetools/merchant-center-application-kit/issues", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/commercetools/merchant-center-application-kit.git", | ||
"directory": "packages-backend/express" | ||
}, | ||
"homepage": "https://docs.commercetools.com/custom-applications", | ||
"keywords": [ | ||
"javascript", | ||
"nodejs", | ||
"express", | ||
"http", | ||
"server", | ||
"toolkit" | ||
], | ||
"license": "MIT", | ||
"private": false, | ||
"publishConfig": { | ||
"access": "public" | ||
}, | ||
"main": "./build/index.js", | ||
"typings": "./build/index.d.ts", | ||
"types": "./build/index.d.ts", | ||
"files": [ | ||
"build", | ||
"package.json", | ||
"LICENSE", | ||
"README.md" | ||
], | ||
"scripts": { | ||
"prebuild": "rimraf build/**", | ||
"build": "tsc -p tsconfig.build.json" | ||
}, | ||
"dependencies": { | ||
"@types/node": "12.12.29", | ||
"express": "4.17.1", | ||
"express-jwt": "5.3.3", | ||
"jwks-rsa": "1.7.0" | ||
}, | ||
"devDependencies": { | ||
"@panva/jose": "1.9.3", | ||
"nock": "12.0.3" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
export const CLOUD_IDENTIFIERS = { | ||
GCP_AU: 'gcp-au', | ||
GCP_EU: 'gcp-eu', | ||
GCP_US: 'gcp-us', | ||
AWS_FRA: 'aws-fra', | ||
AWS_OHIO: 'aws-ohio', | ||
} as const; | ||
|
||
export const MC_API_URLS = { | ||
GCP_AU: 'https://mc-api.australia-southeast1.gcp.commercetools.com', | ||
GCP_EU: 'https://mc-api.europe-west1.gcp.commercetools.com', | ||
GCP_US: 'https://mc-api.us-central1.gcp.commercetools.com', | ||
AWS_FRA: 'https://mc-api.eu-central-1.aws.commercetools.com', | ||
AWS_OHIO: 'https://mc-api.us-east-2.aws.commercetools.com', | ||
} as const; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
export * from './constants'; | ||
export { default as createSessionMiddleware } from './middlewares/session-middleware'; |
19 changes: 19 additions & 0 deletions
19
packages-backend/express/src/middlewares/fixtures/jwt-token.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import { JWT, JWK, JWKS } from '@panva/jose'; | ||
|
||
const keyRS256 = JWK.generateSync('RSA', 2048, { use: 'sig', alg: 'RS256' }); | ||
|
||
const jwksStore = new JWKS.KeyStore([keyRS256]); | ||
|
||
const createToken = (options: { issuer: string; audience: string }) => | ||
JWT.sign( | ||
{ | ||
sub: 'user-id', | ||
iss: options.issuer, | ||
aud: options.audience, | ||
[`${options.issuer}/claims/project_key`]: 'project-key', | ||
}, | ||
keyRS256, | ||
{ algorithm: 'RS256' } | ||
); | ||
|
||
export { jwksStore, createToken }; |
111 changes: 111 additions & 0 deletions
111
packages-backend/express/src/middlewares/session-middleware.spec.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
import nock from 'nock'; | ||
import createSessionMiddleware from './session-middleware'; | ||
import * as fixtureJWTToken from './fixtures/jwt-token'; | ||
|
||
describe.each` | ||
cloudIdentifier | issuer | ||
${'https://mc-api.ct-test.com'} | ${'https://mc-api.ct-test.com'} | ||
${'gcp-au'} | ${'https://mc-api.australia-southeast1.gcp.commercetools.com'} | ||
${'gcp-eu'} | ${'https://mc-api.europe-west1.gcp.commercetools.com'} | ||
${'gcp-us'} | ${'https://mc-api.us-central1.gcp.commercetools.com'} | ||
${'aws-fra'} | ${'https://mc-api.eu-central-1.aws.commercetools.com'} | ||
${'aws-ohio'} | ${'https://mc-api.us-east-2.aws.commercetools.com'} | ||
`( | ||
'when the middleware uses as "issuer": "$cloudIdentifier"', | ||
({ cloudIdentifier, issuer }) => { | ||
beforeEach(() => { | ||
nock(issuer) | ||
.get('/.well-known/jwks.json') | ||
.reply(200, fixtureJWTToken.jwksStore.toJWKS()); | ||
}); | ||
it('should verify the token and attach the session info to the request', async () => { | ||
const sessionMiddleware = createSessionMiddleware({ | ||
issuer: cloudIdentifier, | ||
}); | ||
const fakeRequest = { | ||
method: 'GET', | ||
header: jest.fn((key) => { | ||
switch (key) { | ||
case 'x-mc-api-cloud-identifier': | ||
return cloudIdentifier; | ||
default: | ||
return undefined; | ||
} | ||
}), | ||
headers: { | ||
authorization: `Bearer ${fixtureJWTToken.createToken({ | ||
issuer, | ||
audience: 'http://test-server/foo/bar', | ||
})}`, | ||
}, | ||
hostname: 'http://test-server', | ||
originalUrl: '/foo/bar', | ||
}; | ||
const fakeResponse = {}; | ||
await new Promise((resolve, reject) => { | ||
// @ts-ignore | ||
sessionMiddleware(fakeRequest, fakeResponse, (error) => { | ||
if (error) reject(error); | ||
else resolve(); | ||
}); | ||
}); | ||
|
||
expect(fakeRequest).toHaveProperty('session', { | ||
userId: 'user-id', | ||
projectKey: 'project-key', | ||
}); | ||
expect(fakeRequest).not.toHaveProperty('decoded_token'); | ||
}); | ||
if (!cloudIdentifier.startsWith('http')) { | ||
it('should infer cloud identifier from custom HTTP header instead of given "mcApiUrl"', async () => { | ||
const sessionMiddleware = createSessionMiddleware({ | ||
issuer: 'https://mc-api.another-ct-test.com', // This value should not matter | ||
inferIssuer: true, | ||
}); | ||
const fakeRequest = { | ||
method: 'GET', | ||
header: jest.fn((key) => { | ||
switch (key) { | ||
case 'x-mc-api-cloud-identifier': | ||
return cloudIdentifier; | ||
default: | ||
return undefined; | ||
} | ||
}), | ||
headers: { | ||
authorization: `Bearer ${fixtureJWTToken.createToken({ | ||
issuer, | ||
audience: 'http://test-server/foo/bar', | ||
})}`, | ||
}, | ||
hostname: 'http://test-server', | ||
originalUrl: '/foo/bar', | ||
}; | ||
const fakeResponse = {}; | ||
await new Promise((resolve, reject) => { | ||
// @ts-ignore | ||
sessionMiddleware(fakeRequest, fakeResponse, (error) => { | ||
if (error) reject(error); | ||
else resolve(); | ||
}); | ||
}); | ||
|
||
expect(fakeRequest).toHaveProperty('session', { | ||
userId: 'user-id', | ||
projectKey: 'project-key', | ||
}); | ||
expect(fakeRequest).not.toHaveProperty('decoded_token'); | ||
}); | ||
} | ||
} | ||
); | ||
|
||
describe('when issuer is not a valid URL', () => { | ||
it('should throw a validation error', () => { | ||
expect(() => | ||
createSessionMiddleware({ | ||
issuer: 'invalid url', | ||
}) | ||
).toThrowError('Invalid issuer URL'); | ||
}); | ||
}); |
Oops, something went wrong.
2bf72e8
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Successfully deployed to following URLs: