-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgateway.js
160 lines (146 loc) · 6.08 KB
/
gateway.js
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
const request = (process.type === 'renderer') ? require('ut-browser-request') : require('request');
const [httpPost] = [request.post].map(require('util').promisify);
const decode = (result, method, unpack) => unpack ? result : [result, {method, mtid: 'response'}];
// required by other modules with require('ut-bus/gateway')
module.exports = ({serverInfo, mleClient, errors, get}) => {
const localCache = {};
const localKeys = mleClient.keys.sign && mleClient.keys.encrypt && {mlsk: mleClient.keys.sign, mlek: mleClient.keys.encrypt};
function tokenInfo(auth) {
const now = Date.now() - 5000; // latency tolerance of 5 seconds
return {
tokenExpire: now + auth.expires_in * 1000,
refreshTokenExpire: now + auth.refresh_token_expires_in * 1000
};
}
async function login(cache, url, username, password, channel) {
const {sign, encrypt} = (localKeys && (cache.auth || cache.remoteKeys)) || {};
if (sign && encrypt) {
const {body: {result, error}} = await httpPost({
url: `${url}/rpc/login/identity/exchange`,
body: {
jsonrpc: '2.0',
method: 'login.identity.exchange',
id: 1,
params: await mleClient.signEncrypt({username, password, channel}, encrypt, localKeys)
},
json: true
});
if (error) throw Object.assign(new Error(), await mleClient.decryptVerify(error, sign));
else if (result) cache.auth = await mleClient.decryptVerify(result, sign);
else throw errors['bus.jsonRpcEmpty']();
} else {
const {body: {result, error}} = await httpPost({
url: `${url}/rpc/login/identity/check`,
body: {
jsonrpc: '2.0',
method: 'login.identity.check',
id: 1,
params: {username, password, channel}
},
json: true
});
if (error) throw Object.assign(new Error(), error);
else if (result) cache.auth = result;
else throw errors['bus.jsonRpcEmpty']();
}
cache.tokenInfo = tokenInfo(cache.auth);
}
return async function gateway({
username,
password,
channel = 'web',
protocol = serverInfo('protocol'),
host: hostname = 'localhost',
port = serverInfo('port'),
url,
tls,
auth,
encrypt = true,
method
}) {
// don't put a default value for uri in arguments as it can be empty string or null
if (url) {
const parsed = new URL(url);
hostname = parsed.hostname;
port = parsed.port;
protocol = parsed.protocol.split(':')[0];
if (parsed.username) username = parsed.username;
if (parsed.password) password = parsed.password;
} else {
protocol = protocol && protocol.split(':')[0];
url = `${protocol}://${hostname}:${port}`;
}
const codec = {
requestParams: {
protocol,
hostname,
port,
path: `/rpc/${method.replace(/\./g, '/')}`
}
};
const cache = localCache[url] = localCache[url] || {};
if (localKeys && !cache.remoteKeys) {
const body = await get(
`${url}/rpc/login/.well-known/mle`,
errors['bus.jsonRpcHttp'],
errors['bus.jsonRpcEmpty']
);
if (body.sign && body.encrypt) cache.remoteKeys = body;
}
if (auth) {
cache.auth = auth;
cache.tokenInfo = tokenInfo(auth);
}
if (!cache.auth && !(username && password)) {
if (cache.remoteKeys) {
codec.encode = async params => ({
params: await mleClient.signEncrypt(params, cache.remoteKeys.encrypt, localKeys),
method
});
codec.decode = async(result, unpack) => decode(await mleClient.decryptVerify(result, cache.remoteKeys.sign), method, unpack);
} else {
codec.encode = params => ({params, method});
codec.decode = (result, unpack) => decode(result, method, unpack);
}
return codec;
}
if (!cache.auth) await login(cache, url, username, password, channel);
const exp = Date.now();
if (exp > cache.tokenInfo.tokenExpire) {
if (exp > cache.tokenInfo.refreshTokenExpire) {
await login(cache, url, username, password, channel);
} else {
const {body} = await httpPost({
url: `${url}/rpc/login/token`,
body: {
grant_type: 'refresh_token',
refresh_token: cache.auth.refresh_token
},
json: true
});
Object.assign(cache.auth, body);
cache.tokenInfo = tokenInfo(body);
}
}
if (cache.auth.sign && cache.auth.encrypt) {
codec.encode = async params => ({
params: await mleClient.signEncrypt(params, cache.auth.encrypt),
headers: {
authorization: 'Bearer ' + cache.auth.access_token
},
method
});
codec.decode = async(result, unpack) => decode(await mleClient.decryptVerify(result, cache.auth.sign), method, unpack);
} else {
codec.encode = params => ({
params,
headers: {
authorization: 'Bearer ' + cache.auth.access_token
},
method
});
codec.decode = (result, unpack) => decode(result, method, unpack);
}
return codec;
};
};