forked from SuperMap/iClient-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncryptRequest.js
More file actions
201 lines (196 loc) · 6.28 KB
/
EncryptRequest.js
File metadata and controls
201 lines (196 loc) · 6.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import { FetchRequest } from './FetchRequest';
import {
RSAEncrypt,
AESGCMEncrypt,
AESGCMDecrypt,
generateAESRandomKey,
generateAESRandomIV
} from './RequestcryptUtil';
import URI from 'urijs';
/**
* @class EncryptRequest
* @category iServer Core
* @classdesc 加密请求地址
* @param {string} serverUrl - iServer 服务地址。如:http://127.0.0.1:8090/iserver。
* @version 11.2.0
* @usage
*/
export class EncryptRequest {
constructor(serverUrl) {
this.serverUrl = serverUrl;
this.tunnelUrl = undefined;
this.blockedUrlRegex = {
HEAD: [],
POST: [],
GET: [],
PUT: [],
DELETE: []
};
this.encryptAESKey = generateAESRandomKey();
this.encryptAESIV = generateAESRandomIV();
}
/**
* @function EncryptRequest.prototype.request
* @description 加密请求地址。
* @param {Object} config - 加密请求参数。
* @param {string} config.method - 请求方法。
* @param {string} config.url - 请求地址。
* @param {string} config.params - 请求参数。
* @param {Object} config.options - 请求的配置属性。
* @returns {Promise} Promise 对象。
*/
async request(options) {
if (!this.serverUrl) {
throw 'serverUrl can not be empty.';
}
const config = Object.assign({ baseURL: '' }, options);
const tunnelUrl = await this._createTunnel();
if (!tunnelUrl) {
return;
}
for (const pattern of this.blockedUrlRegex[config.method.toUpperCase()]) {
const regex = new RegExp(pattern);
if (regex.test(config.baseURL + config.url)) {
const data = {
url: config.baseURL + (config.url.startsWith('/') ? config.url.substring(1, config.url.length) : config.url),
method: config.method,
timeout: config.timeout,
headers: config.headers,
body: config.data
};
// 替换请求
config.method = 'post';
config.data = AESGCMEncrypt(this.encryptAESKey, this.encryptAESIV, JSON.stringify(data));
if (!config.data) {
throw 'encrypt failed';
}
config.url = this.tunnelUrl;
break;
}
}
const response = await FetchRequest.commit(config.method, config.url, config.data, config.options);
if (config.url === this.tunnelUrl) {
const result = await response.text();
const decryptResult = AESGCMDecrypt(this.encryptAESKey, this.encryptAESIV, result);
if (!decryptResult) {
console.debug('解密请求响应失败');
return;
}
const resultData = JSON.parse(decryptResult);
const resData = Object.create({
json: function () {
return Promise.resolve(resultData.data);
}
});
return Object.assign(resData, resultData);
}
return response;
}
/**
* @private
* @description 获取RSA public key
* @function EncryptRequest.prototype._getRSAPublicKey
*/
async _getRSAPublicKey() {
try {
const response = await FetchRequest.get(URI(this.serverUrl).segment('services/security/tunnel/v1/publickey').toString());
// 解析publicKey
const publicKeyObj = await response.json();
// 生成AES密钥
const aesKeyObj = {
key: this.encryptAESKey,
iv: this.encryptAESIV,
mode: 'GCM',
padding: 'NoPadding'
};
// 将AES密钥使用RSA公钥加密
const aesCipherText = RSAEncrypt(publicKeyObj.publicKey, aesKeyObj.key + aesKeyObj.iv);
return aesCipherText;
} catch (error) {
console.debug('RSA公钥获取失败,错误详情:' + error);
}
}
/**
* @private
* @description 创建隧道
* @function EncryptRequest.prototype._createTunnel
*/
async _createTunnel() {
if (!this.tunnelUrl) {
try {
const data = await this._getRSAPublicKey();
if (!data) {
throw 'fetch RSA publicKey failed';
}
// 创建隧道
const response = await FetchRequest.post(URI(this.serverUrl).segment('services/security/tunnel/v1/tunnels').toString(), data);
const result = await response.json();
Object.assign(this, {
tunnelUrl: result.tunnelUrl,
blockedUrlRegex: Object.assign({}, this.blockedUrlRegex, result.blockedUrlRegex)
});
} catch (error) {
console.debug('安全隧道创建失败,错误详情:' + error);
}
}
return this.tunnelUrl;
}
}
/**
* @function getServiceKey
* @version 11.2.0
* @category iServer Core
* @description 获取矢量瓦片解密密钥
* @param {string} serviceUrl - iServer 服务地址。例如:http://127.0.0.1:8090/iserver/services/xxx、http://127.0.0.1:8090/iserver/services/xxx/rest/maps、http://127.0.0.1:8090/iserver/services/xxx/restjsr/v1/vectortile。
* @return {Promise} options - 矢量瓦片密钥和加密算法类型。例如 { serviceKey, algorithm }。
* @usage
* ```
* // 浏览器
* <script type="text/javascript" src="{cdn}"></script>
* <script>
* const result = {namespace}.getServiceKey(serviceUrl);
*
* </script>
*
* // ES6 Import
* import { getServiceKey } from '{npm}';
*
* const result = getServiceKey(serviceUrl);
* ```
*/
export async function getServiceKey(serviceUrl) {
try {
const workspaceServerUrl = ((serviceUrl &&
serviceUrl.match(/.+(?=(\/restjsr\/v1\/vectortile\/|\/rest\/maps\/|\/rest\/data\/))/)) ||
[])[0];
if (!workspaceServerUrl) {
return;
}
const servicesResponse = await FetchRequest.get(workspaceServerUrl);
const servicesResult = await servicesResponse.json();
const matchRestData = (servicesResult || []).find(
(item) => serviceUrl.includes(item.name) && item.serviceEncryptInfo
);
if (!matchRestData) {
return;
}
const iserverHost = workspaceServerUrl.split('/services/')[0];
const encryptRequest = new EncryptRequest(iserverHost);
const svckeyUrl =
matchRestData && `${iserverHost}/services/security/svckeys/${matchRestData.serviceEncryptInfo.encrptKeyID}.json`;
const svcReponse = await encryptRequest.request({
method: 'get',
url: svckeyUrl
});
const serviceKey = await svcReponse.json();
if (!serviceKey) {
return;
}
return {
serviceKey,
algorithm: matchRestData.serviceEncryptInfo.encrptSpec.algorithm
};
} catch (error) {
console.error(error);
}
}