@tdxvolt/volt-client-grpc 0.1.0 → 0.1.2

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.
@@ -5,284 +5,313 @@ import bent from "bent";
5
5
  import forge from "node-forge";
6
6
  import lodash from "lodash";
7
7
  import VoltConnection from "./volt-connection.js";
8
- import {getServiceDescriptors} from "./proto-utils.js";
9
- import {createClient as createGrpcClient} from "./grpc-utils.js";
8
+ import { getServiceDescriptors } from "./proto-utils.js";
9
+ import { createClient as createGrpcClient } from "./grpc-utils.js";
10
10
  import * as voltUtils from "./utils.js";
11
- import {constants} from "./constants.js";
11
+ import { constants } from "./constants.js";
12
12
  import GRPCCall from "./grpc-call.js";
13
13
 
14
- const {pki} = forge;
15
- const {filter, pick} = lodash;
14
+ const { pki } = forge;
15
+ const { filter, pick } = lodash;
16
16
 
17
17
  const log = debug("volt-client-grpc:volt-client-internal");
18
18
  const voltServices = [
19
- constants.serviceType.voltAPI,
20
- constants.serviceType.fileAPI,
21
- constants.serviceType.sqliteServerAPI,
22
- constants.serviceType.ssiAPI,
23
- constants.serviceType.tunnelAPI,
24
- constants.serviceType.wireAPI,
19
+ constants.serviceType.voltAPI,
20
+ constants.serviceType.fileAPI,
21
+ constants.serviceType.sqliteDatabaseAPI,
22
+ constants.serviceType.sqliteServerAPI,
23
+ constants.serviceType.ssiAPI,
24
+ constants.serviceType.relayAPI,
25
+ constants.serviceType.wireAPI,
25
26
  ];
26
27
 
27
28
  function issueBind(bindRequest, ttl) {
28
- // eslint-disable-next-line no-use-before-define
29
- return unaryCall.call(this, "Bind", bindRequest).then((bindResponse) => {
30
- log("got binding request response %j", bindResponse);
31
- if (bindResponse.status && bindResponse.status.code) {
32
- log("error in bind response: %s", bindResponse.status.message);
33
- return Promise.reject(new Error(bindResponse.status.message));
34
- } else {
35
- switch (bindResponse.decision) {
36
- case "POLICY_DECISION_PERMIT":
37
- //
38
- // The request status is permit => cache the bind response info.
39
- //
40
-
41
- // This is the certificate assigned to us by the volt.
42
- this._crypto.cache.cert = bindResponse.cert;
43
-
44
- // This is the signing CA used by the volt (don't ov)
45
- this._crypto.cache.ca = bindResponse.chain;
46
-
47
- // Resource id is assigned by the volt.
48
- this._crypto.cache.client_id = bindResponse.identity_id;
49
- this._crypto.saveCache();
50
- break;
51
- case "POLICY_DECISION_DENY":
52
- log(">>>>>>>>>>>>>>> access request is DENIED <<<<<<<<<<<<<<<<<<<");
53
- break;
54
- case "POLICY_DECISION_PROMPT":
55
- case "POLICY_DECISION_PENDING":
56
- log("access pending approval - waiting...");
57
- break;
58
- default:
59
- log("ignoring unknown bind descision %s", bindResponse.status);
60
- break;
61
- }
62
- }
63
-
64
- return bindResponse.decision;
65
- });
29
+ // eslint-disable-next-line no-use-before-define
30
+ return unaryCall.call(this, "Bind", bindRequest).then((bindResponse) => {
31
+ log("got binding request response %j", bindResponse);
32
+ if (bindResponse.status?.code) {
33
+ log("error in bind response: %s", bindResponse.status.message);
34
+ return Promise.reject(new Error(bindResponse.status.message));
35
+ } else {
36
+ switch (bindResponse.decision) {
37
+ case "POLICY_DECISION_PERMIT": {
38
+ //
39
+ // The request status is permit => cache the bind response info.
40
+ //
41
+
42
+ // This is the certificate assigned to us by the volt.
43
+ this._credential.cache.cert = bindResponse.cert;
44
+
45
+ // This is the signing CA used by the volt (don't ov)
46
+ this._credential.cache.ca = bindResponse.chain;
47
+
48
+ // Resource id is assigned by the volt.
49
+ this._credential.cache.client_id = bindResponse.identity_id;
50
+ this._credential.saveCache();
51
+ break;
52
+ }
53
+ case "POLICY_DECISION_DENY": {
54
+ log(">>>>>>>>>>>>>>> access request is DENIED <<<<<<<<<<<<<<<<<<<");
55
+ break;
56
+ }
57
+ case "POLICY_DECISION_PROMPT":
58
+ case "POLICY_DECISION_PENDING": {
59
+ log("access pending approval - waiting...");
60
+ break;
61
+ }
62
+ default:
63
+ log("ignoring unknown bind descision %s", bindResponse.status);
64
+ break;
65
+ }
66
+ }
67
+
68
+ return bindResponse.decision;
69
+ });
66
70
  }
67
71
 
68
72
  function findDIDDocumentService(document, serviceType) {
69
- if (!document.service) {
70
- return [];
71
- }
73
+ if (!document.service) {
74
+ return [];
75
+ }
72
76
 
73
- const matches = filter(document.service, (svc) => svc.type === serviceType);
74
- return matches;
77
+ const matches = filter(document.service, (svc) => svc.type === serviceType);
78
+ return matches;
75
79
  }
76
80
 
77
81
  export async function bindInternal() {
78
- try {
79
- // Build grpc client info.
80
- if (this.isRemote) {
81
- const getJSON = bent("json");
82
- // @todo - currently Volt tunnel CA discovery is not secure.
83
- const protocol =
84
- this._config.tunnel_host?.startsWith("localhost:") || this._config.cloud_host?.startsWith("localhost:")
85
- ? "http"
86
- : "https";
87
- const tunnelURL = `${protocol}://${this._config.tunnel_host || this._config.cloud_host}/info`;
88
- log("attempting to retrieve tunnel information from %s", tunnelURL);
89
- const tunnelInfo = await getJSON(tunnelURL);
90
- if (!tunnelInfo.ca_pem) {
91
- throw new Error("Unable to fetch tunnel CA - cannot securely connect.");
92
- } else {
93
- log("Auto-fetched tunnel CA %s, remote address %s", tunnelInfo.ca_pem, tunnelInfo.local_address);
94
- this._crypto.cache.tunnel_ca_pem = tunnelInfo.ca_pem;
95
- this._crypto.cache.tunnel_address = tunnelInfo.local_address;
96
- }
97
- }
98
-
99
- if (!this._crypto.cache.ca) {
100
- this._crypto.cache.ca = this._options.ca_pem;
101
- }
102
-
103
- if (!this._crypto.cache.ca) {
104
- throw new Error("No certificate authority found in configuration for target Volt - check configuration");
105
- }
106
-
107
- const keyPair = this._crypto.getKey();
108
- const publicKeyPem = pki.publicKeyToPem(keyPair.publicKey);
109
-
110
- if (!this._crypto.cache.bindIp) {
111
- // Default the IP address if none is specified. This is used to set the SAN in the
112
- // certificate issued by the Volt.
113
- this._crypto.cache.bindIp = ip.address();
114
- }
115
-
116
- this._crypto.saveCache();
117
-
118
- // Form the request message.
119
- const bindRequest = {
120
- binding_name: this._config.client_name,
121
- public_key: publicKeyPem,
122
- host: this._crypto.cache.bindIp,
123
- x509_credential: [],
124
- };
125
-
126
- if (this._crypto.cache.cert) {
127
- bindRequest.x509_credential = [this._crypto.cache.cert + this._crypto.cache.ca];
128
- }
129
-
130
- if (this._options.challenge_code) {
131
- bindRequest.challenge = voltUtils.signBase64(keyPair.privateKey, this._options.challenge_code);
132
- } else {
133
- log("****no Volt challenge code available**** => not sending challenge signature");
134
- }
135
-
136
- // For remote connections, add our cloud-issued certificate as an additional credential.
137
- if (this._crypto.cache.tunnel_ca_pem && this._crypto.cache.cloud_cert) {
138
- bindRequest.x509_credential = bindRequest.x509_credential.concat(
139
- this._crypto.cache.cloud_cert + this._crypto.cache.tunnel_ca_pem
140
- );
141
- }
142
-
143
- log("sending %d x509 credentials", bindRequest.x509_credential.length);
144
- log("bind TTL is ", this._config.bindRequestTTL);
145
-
146
- // This will block while the request is pending.
147
- const pollInterval = 10000;
148
- let decision = "";
149
- do {
150
- if (decision) {
151
- // Wait a while before retrying.
152
- // eslint-disable-next-line no-await-in-loop
153
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
154
- }
155
- // eslint-disable-next-line no-await-in-loop
156
- decision = await issueBind.call(this, bindRequest, this._options.bindRequestTTL);
157
- log("binding decision: %s", decision);
158
- } while (decision === "POLICY_DECISION_PROMPT" || decision === "POLICY_DECISION_PENDING");
159
-
160
- return decision === "POLICY_DECISION_PERMIT";
161
- } catch (err) {
162
- log("failure binding to Volt [%s]", err.message);
163
- throw err;
164
- }
82
+ try {
83
+ // Check if we need to resolve a Relay volt.
84
+ if (
85
+ this._config?.relay?.discovery_url ||
86
+ typeof this._config?.relay === "string"
87
+ ) {
88
+ const relayURL = this._config.relay?.discovery_url || this._config.relay;
89
+ log("attempting to retrieve Relay information from %s", relayURL);
90
+ const voltConfig = await fetchVoltConfig.call(this, relayURL);
91
+ this._config.relay = voltConfig.volt;
92
+ this._config.relay.discovery_url = relayURL;
93
+ if (this._config.relay.ca_pem) {
94
+ log(
95
+ "Auto-fetched Relay CA %s, remote address %s",
96
+ this._config.relay.ca_pem,
97
+ this._config.relay.address,
98
+ );
99
+ } else {
100
+ throw new Error("Unable to fetch Relay CA - cannot securely connect.");
101
+ }
102
+ }
103
+
104
+ if (!this._credential.cache.ca) {
105
+ this._credential.cache.ca = this._voltConfig.ca_pem;
106
+ }
107
+
108
+ if (!this._credential.cache.ca) {
109
+ throw new Error(
110
+ "No certificate authority found in configuration for target Volt - check configuration",
111
+ );
112
+ }
113
+
114
+ const keyPair = this._credential.getKey();
115
+ const publicKeyPem = pki.publicKeyToPem(keyPair.publicKey);
116
+
117
+ if (!this._credential.cache.bindIp) {
118
+ // Default the IP address if none is specified. This is used to set the SAN in the
119
+ // certificate issued by the Volt.
120
+ this._credential.cache.bindIp = ip.address();
121
+ }
122
+
123
+ this._credential.saveCache();
124
+
125
+ // Form the request message.
126
+ const bindRequest = {
127
+ binding_name: this._config.client_name,
128
+ public_key: publicKeyPem,
129
+ host: this._credential.cache.bindIp,
130
+ x509_credential: [],
131
+ };
132
+
133
+ if (this._credential.cache.cert) {
134
+ bindRequest.x509_credential = [
135
+ this._credential.cache.cert + this._credential.cache.ca,
136
+ ];
137
+ }
138
+
139
+ if (this._voltConfig.challenge_code) {
140
+ bindRequest.challenge = voltUtils.signBase64(
141
+ keyPair.privateKey,
142
+ this._voltConfig.challenge_code,
143
+ );
144
+ } else {
145
+ log(
146
+ "****no Volt challenge code available**** => not sending challenge signature",
147
+ );
148
+ }
149
+
150
+ // For remote connections, add our cloud-issued certificate as an additional credential.
151
+ if (this._config?.relay?.ca_pem && this._credential.cache.cloud_cert) {
152
+ bindRequest.x509_credential = bindRequest.x509_credential.concat(
153
+ this._credential.cache.cloud_cert + this._config.relay.ca_pem,
154
+ );
155
+ }
156
+
157
+ log("sending %d x509 credentials", bindRequest.x509_credential.length);
158
+ log("bind TTL is ", this._config.bindRequestTTL);
159
+
160
+ // This will block while the request is pending.
161
+ const pollInterval = 10000;
162
+ let decision = "";
163
+ do {
164
+ if (decision) {
165
+ // Wait a while before retrying.
166
+ // eslint-disable-next-line no-await-in-loop
167
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
168
+ }
169
+ // eslint-disable-next-line no-await-in-loop
170
+ decision = await issueBind.call(
171
+ this,
172
+ bindRequest,
173
+ this._voltConfig.bindRequestTTL,
174
+ );
175
+ log("binding decision: %s", decision);
176
+ } while (
177
+ decision === "POLICY_DECISION_PROMPT" ||
178
+ decision === "POLICY_DECISION_PENDING"
179
+ );
180
+
181
+ return decision === "POLICY_DECISION_PERMIT";
182
+ } catch (err) {
183
+ log("failure binding to Volt [%s]", err.message);
184
+ throw err;
185
+ }
165
186
  }
166
187
 
167
188
  export function connectInternal() {
168
- try {
169
- if (this._voltConnection) {
170
- log("connectInternal - Volt connection already exists");
171
- return Promise.resolve();
172
- }
173
-
174
- const onDisconnected = () => {
175
- this._connected = false;
176
- this._session = null;
177
-
178
- if (this._cachedClient) {
179
- this._grpc.closeClient(this._cachedClient);
180
- this._cachedClient = null;
181
- }
182
-
183
- if (this._cachedRemoteClient) {
184
- this._grpc.closeClient(this._cachedRemoteClient);
185
- this._cachedRemoteClient = null;
186
- }
187
- };
188
-
189
- this._voltConnection = new VoltConnection(this, this._grpc, this._options);
190
-
191
- this._voltConnection.on("connected", (session) => {
192
- this._session = session;
193
- this._connected = !!session;
194
- if (!this._connected) {
195
- onDisconnected();
196
- }
197
- this.emit("connected", !!session);
198
- });
199
-
200
- this._voltConnection.on("error", (err) => {
201
- // Should auto-reconnect.
202
- log("Volt connection error [%s]", err.message);
203
- if (this._connected) {
204
- onDisconnected();
205
- this.emit("connected", false);
206
- }
207
- });
208
-
209
- this._voltConnection.on("evt", (evt) => {
210
- this.emit("evt", evt);
211
- });
212
-
213
- return this._voltConnection.connect();
214
- } catch (err) {
215
- log("connect - error [%s]", err.message);
216
- throw err;
217
- }
189
+ try {
190
+ if (this._voltConnection) {
191
+ log("connectInternal - Volt connection already exists");
192
+ return Promise.resolve();
193
+ }
194
+
195
+ const onDisconnected = () => {
196
+ this._connected = false;
197
+ this._session = null;
198
+
199
+ if (this._cachedClient) {
200
+ this._grpc.closeClient(this._cachedClient);
201
+ this._cachedClient = null;
202
+ }
203
+
204
+ if (this._cachedRemoteClient) {
205
+ this._grpc.closeClient(this._cachedRemoteClient);
206
+ this._cachedRemoteClient = null;
207
+ }
208
+ };
209
+
210
+ this._voltConnection = new VoltConnection(this, this._grpc);
211
+
212
+ this._voltConnection.on("connected", (session) => {
213
+ this._session = session;
214
+ this._connected = !!session;
215
+ if (!this._connected) {
216
+ onDisconnected();
217
+ }
218
+ this.emit("connected", !!session);
219
+ });
220
+
221
+ this._voltConnection.on("error", (err) => {
222
+ // Should auto-reconnect.
223
+ log("Volt connection error [%s]", err.message);
224
+ if (this._connected) {
225
+ onDisconnected();
226
+ this.emit("connected", false);
227
+ }
228
+ });
229
+
230
+ this._voltConnection.on("evt", (evt) => {
231
+ this.emit("evt", evt);
232
+ });
233
+
234
+ return this._voltConnection.connect();
235
+ } catch (err) {
236
+ log("connect - error [%s]", err.message);
237
+ throw err;
238
+ }
218
239
  }
219
240
 
220
241
  export function getVoltAPIClientInternal() {
221
- if (!this._cachedClient) {
222
- const serviceAddress = this.isRemote ? this._crypto.cache.tunnel_address : this._options.local_address;
223
- log("creating cached VoltAPI service client on %s", serviceAddress);
224
- let serviceDescriptors = {};
225
- voltServices.forEach((pkg) => {
226
- const packageDescriptors = getServiceDescriptors(this._grpc, pkg);
227
- serviceDescriptors = {...serviceDescriptors, ...packageDescriptors};
228
- });
229
-
230
- this._cachedClient = createGrpcClient(
231
- this._grpc,
232
- serviceDescriptors,
233
- serviceAddress,
234
- this._crypto.cache,
235
- this.isRemote && !this.isVoltTunnel,
236
- this._config.cloud_host ? this._options.id : "",
237
- this._config.cloud_host ? this._options.id : ""
238
- );
239
- }
240
-
241
- return this._cachedClient;
242
+ if (!this._cachedClient) {
243
+ const serviceAddress = this.isRemote
244
+ ? this._config.relay.address
245
+ : this._voltConfig.address;
246
+ log("creating cached VoltAPI service client on %s", serviceAddress);
247
+ let serviceDescriptors = {};
248
+ voltServices.forEach((pkg) => {
249
+ const packageDescriptors = getServiceDescriptors(this._grpc, pkg);
250
+ serviceDescriptors = { ...serviceDescriptors, ...packageDescriptors };
251
+ });
252
+
253
+ this._cachedClient = createGrpcClient(
254
+ this._grpc,
255
+ serviceDescriptors,
256
+ serviceAddress,
257
+ this._credential,
258
+ this.isRemote && !this.isVoltRelay,
259
+ this._config?.relay?.cloud_relay ? this._voltConfig.id : "",
260
+ this._config?.relay?.cloud_relay ? this._voltConfig.id : "",
261
+ );
262
+ }
263
+
264
+ return this._cachedClient;
242
265
  }
243
266
 
244
267
  export function unaryCall(method, request) {
245
- const grpcClient = this.getVoltAPIClient();
268
+ const grpcClient = this.getVoltAPIClient();
246
269
 
247
- const call = new GRPCCall(this, method, "METHOD_TYPE_UNARY");
248
- call.start(grpcClient, request);
249
- return call.wait();
270
+ const call = new GRPCCall(this, method, "METHOD_TYPE_UNARY");
271
+ call.start(grpcClient, request);
272
+ return call.wait();
250
273
  }
251
274
 
252
- export async function fetchVoltConfig(volt_did) {
253
- const didResolution = voltUtils.getDIDResolutionURL(volt_did);
254
- if (!didResolution) {
255
- throw new Error(`Invalid Volt DID: ${volt_did}`);
256
- }
257
-
258
- const getJSON = bent("json");
259
- const didDocument = await getJSON(didResolution);
260
- const voltConfigServices = findDIDDocumentService(didDocument, constants.didServiceType.voltConfig);
261
- if (voltConfigServices.length !== 1) {
262
- log(
263
- "Unexpected number of Volt configuration endpoints found in DID document for %s, services found: %d",
264
- volt_did,
265
- voltConfigServices.length
266
- );
267
- }
268
- const serviceEndpoint = voltConfigServices[0].serviceEndpoint;
269
- const resolvedConfig = await getJSON(serviceEndpoint);
270
-
271
- const voltConfig = pick(
272
- resolvedConfig,
273
- "id",
274
- "display_name",
275
- "public_key",
276
- "fingerprint",
277
- "local_address",
278
- "ca_pem",
279
- "challenge_code"
280
- );
281
-
282
- return {
283
- volt: voltConfig,
284
- tunnel_ca_pem: resolvedConfig.tunnel_ca_pem,
285
- tunnel_address: resolvedConfig.tunnel_address,
286
- cloud_host: resolvedConfig.tunnel_address.split(":")[0],
287
- };
275
+ export async function fetchVoltConfig(disovery_url) {
276
+ const getJSON = bent("json");
277
+ const resolvedConfig = await getJSON(disovery_url);
278
+
279
+ const voltConfig = pick(
280
+ resolvedConfig,
281
+ "id",
282
+ "display_name",
283
+ "public_key",
284
+ "fingerprint",
285
+ "address",
286
+ "ca_pem",
287
+ "challenge_code",
288
+ "cloud_relay",
289
+ );
290
+
291
+ const relayConfig = pick(resolvedConfig, "relay");
292
+
293
+ return { volt: voltConfig, ...relayConfig };
294
+ }
295
+
296
+ export async function fetchVoltConfigFromDID(volt_did) {
297
+ const didResolution = voltUtils.getDIDResolutionURL(volt_did);
298
+ if (!didResolution) {
299
+ throw new Error(`Invalid Volt DID: ${volt_did}`);
300
+ }
301
+
302
+ const getJSON = bent("json");
303
+ const didDocument = await getJSON(didResolution);
304
+ const voltConfigServices = findDIDDocumentService(
305
+ didDocument,
306
+ constants.didServiceType.voltConfig,
307
+ );
308
+ if (voltConfigServices.length !== 1) {
309
+ log(
310
+ "Unexpected number of Volt configuration endpoints found in DID document for %s, services found: %d",
311
+ volt_did,
312
+ voltConfigServices.length,
313
+ );
314
+ }
315
+ const serviceEndpoint = voltConfigServices[0].serviceEndpoint;
316
+ return await fetchVoltConfig.call(this, serviceEndpoint);
288
317
  }