@barry.jiang/aiapp-apaas-infra 1.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.
package/README.md ADDED
@@ -0,0 +1,8 @@
1
+ # @barry.jiang/aiapp-apaas-infra
2
+
3
+ Express middleware that proxies requests from `/_gw_/api/**` to `/api/**` with automatic access token validation and standardization.
4
+
5
+ ## install
6
+
7
+ ```bash
8
+ npm install @barry.jiang/aiapp-apaas-infra
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@barry.jiang/aiapp-apaas-infra",
3
+ "version": "1.0.0",
4
+ "description": "apaas infra of aiapp",
5
+ "main": "src/gatewayMiddleware.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "keywords": ["aiapp","middleware","gateway"],
10
+ "author": "barry.jiang",
11
+ "license": "MIT",
12
+ "type": "commonjs",
13
+ "files": [
14
+ "src",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "engines": {
19
+ "node": ">=14"
20
+ }
21
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Gateway Middleware
3
+ *
4
+ * 拦截所有 /_gw_/api/**请求:
5
+ * 1. 从header中提取x-access-token
6
+ * 2. 若缺失,返回401
7
+ * 3. 若存在,重写路径为 /api/**,并设置标准 Authorization:Bear <token>
8
+ */
9
+ function createGatewayMiddleware() {
10
+ return (req, res, next) => {
11
+ if (!req.url.startsWith('/_gw_/api/')) {
12
+ return next();
13
+ }
14
+
15
+ let acessTokenHeader = 'x-access-token';
16
+ let token = null;
17
+ if (req.headers[acessTokenHeader]) {
18
+ token = req.headers[acessTokenHeader]
19
+ }
20
+
21
+ if (!token) {
22
+ return res.status(401).json({
23
+ error:'Unauthorized',
24
+ message:`Access token reuqired in header: '${accessTokenHeader}'`
25
+ })
26
+ }
27
+ const originalUrl = req.url;
28
+ req.url = originalUrl.replace(/^\/_gw_/,'');
29
+ req.headers.authorization = `Bearer ${token}`;
30
+ delete req.headers[acessTokenHeader];
31
+ console.log(`[Gateway] ${req.method} ${originalUrl} -> ${req.url}`);
32
+ next();
33
+ };
34
+ }
35
+
36
+ module.exports = { createGatewayMiddleware};