@tdxvolt/volt-client-grpc 0.1.1 → 0.11.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/lib/index.cjs CHANGED
@@ -34,258 +34,270 @@ var bent__default = /*#__PURE__*/_interopDefaultLegacy(bent);
34
34
 
35
35
  // eslint-disable-next-line import/prefer-default-export
36
36
  const constants = {
37
- authTokenName: "tdx-token",
38
- collectionOperation: {
39
- add: "ADD",
40
- remove: "REMOVE",
41
- update: "UPDATE",
42
- },
43
- crypto: {
44
- subjectDefaults: [
45
- {
46
- name: "countryName",
47
- value: "GB",
48
- },
49
- {
50
- name: "localityName",
51
- value: "Southampton",
52
- },
53
- {
54
- name: "organizationName",
55
- value: "nquiringminds Ltd",
56
- },
57
- ],
58
- userIdOID: "0.9.2342.19200300.100.1.1",
59
- },
60
- defaultDIDHostName: "volt.tdxcloud.com",
61
- didServiceType: {
62
- voltConfig: "tdx-volt-config",
63
- },
64
- identityType: {
65
- did: "did",
66
- volt: "volt",
67
- },
68
- onlineStatus: {
69
- offline: "offline",
70
- online: "online",
71
- unknown: "unknown",
72
- },
73
- publicKeyPrefix: "-----BEGIN PUBLIC KEY-----",
74
- privateKeyPrefix: "-----BEGIN RSA PRIVATE KEY-----",
75
- privateEncryptedKeyPrefix: "-----BEGIN ENCRYPTED PRIVATE KEY-----",
76
- resource: {
77
- identity: "ident",
78
- identityView: "ident-view",
79
- proxy: "proxy",
80
- proxyView: "proxy-view",
81
- vc: "vc",
82
- vcView: "vc-view",
83
- },
84
- voltStatus: {
85
- pending: "",
86
- online: "online",
87
- offline: "offline",
88
- deleted: "deleted",
89
- revoked: "revoked",
90
- },
91
- /**
92
- * These top-level service types should map to a protobuf definition
93
- * in @tdxvolt/volt-proto.
94
- */
95
- serviceType: {
96
- fileAPI: "tdx.volt_api.volt.v1.FileAPI",
97
- sqliteServerAPI: "tdx.volt_api.data.v1.SqliteServerAPI",
98
- sqliteDatabaseAPI: "tdx.volt_api.data.v1.SqliteDatabaseAPI",
99
- ssiAPI: "tdx.volt_api.ssi.v1.SsiAPI",
100
- tunnelAPI: "tdx.volt_api.tunnel.v1.TunnelAPI",
101
- voltAPI: "tdx.volt_api.volt.v1.VoltAPI",
102
- wireAPI: "tdx.volt_api.volt.v1.WireAPI",
103
- },
104
- tunnelInvokeMethod: "/tdx.volt_api.volt.v1.VoltAPI/Invoke",
105
- tunnelPingInterval: 10000,
106
- tunnelPingTimeout: 2500,
107
- tunnelReconnectAfter: 30000,
108
- tunnelTimeoutInterval: 10000 * 2, // This must always be greater than `tunnelPingInterval`.
37
+ authTokenName: "tdx-token",
38
+ collectionOperation: {
39
+ add: "ADD",
40
+ remove: "REMOVE",
41
+ update: "UPDATE",
42
+ },
43
+ crypto: {
44
+ subjectDefaults: [
45
+ {
46
+ name: "countryName",
47
+ value: "GB",
48
+ },
49
+ {
50
+ name: "localityName",
51
+ value: "Southampton",
52
+ },
53
+ {
54
+ name: "organizationName",
55
+ value: "nquiringminds Ltd",
56
+ },
57
+ ],
58
+ userIdOID: "0.9.2342.19200300.100.1.1",
59
+ },
60
+ defaultDIDHostName: "cloud.tdxvolt.com",
61
+ didServiceType: {
62
+ voltConfig: "tdx-volt-config",
63
+ },
64
+ identityType: {
65
+ did: "did",
66
+ volt: "volt",
67
+ },
68
+ onlineStatus: {
69
+ offline: "offline",
70
+ online: "online",
71
+ unknown: "unknown",
72
+ },
73
+ publicKeyPrefix: "-----BEGIN PUBLIC KEY-----",
74
+ privateKeyPrefix: "-----BEGIN RSA PRIVATE KEY-----",
75
+ privateEncryptedKeyPrefix: "-----BEGIN ENCRYPTED PRIVATE KEY-----",
76
+ resource: {
77
+ identity: "ident",
78
+ identityView: "ident-view",
79
+ proxy: "proxy",
80
+ proxyView: "proxy-view",
81
+ vc: "vc",
82
+ vcView: "vc-view",
83
+ },
84
+ voltStatus: {
85
+ pending: "",
86
+ online: "online",
87
+ offline: "offline",
88
+ deleted: "deleted",
89
+ revoked: "revoked",
90
+ },
91
+ /**
92
+ * These top-level service types should map to a protobuf definition
93
+ * in @tdxvolt/volt-proto.
94
+ */
95
+ serviceType: {
96
+ fileAPI: "tdx.volt_api.volt.v1.FileAPI",
97
+ sqliteServerAPI: "tdx.volt_api.data.v1.SqliteServerAPI",
98
+ sqliteDatabaseAPI: "tdx.volt_api.data.v1.SqliteDatabaseAPI",
99
+ ssiAPI: "tdx.volt_api.ssi.v1.SsiAPI",
100
+ relayAPI: "tdx.volt_api.relay.v1.RelayAPI",
101
+ voltAPI: "tdx.volt_api.volt.v1.VoltAPI",
102
+ wireAPI: "tdx.volt_api.volt.v1.WireAPI",
103
+ },
104
+ tunnelInvokeMethod: "/tdx.volt_api.volt.v1.VoltAPI/Invoke",
105
+ tunnelPingInterval: 10000,
106
+ tunnelPingTimeout: 2500,
107
+ tunnelReconnectAfter: 30000,
108
+ tunnelTimeoutInterval: 10000 * 2, // This must always be greater than `tunnelPingInterval`.
109
109
  };
110
110
 
111
- const {pki: pki$2} = forge__default["default"];
111
+ const { pki: pki$2 } = forge__default["default"];
112
112
 
113
113
  const createSecureContextOptions = (cryptoOptions) => {
114
- const tlsOptions = {
115
- cert: Buffer.from(cryptoOptions.cert),
116
- ca: Buffer.from(cryptoOptions.ca),
117
- key: Buffer.from(cryptoOptions.key),
118
- };
119
- return tlsOptions;
114
+ const tlsOptions = {
115
+ cert: Buffer.from(cryptoOptions.cert),
116
+ ca: Buffer.from(cryptoOptions.ca),
117
+ key: Buffer.from(cryptoOptions.key),
118
+ };
119
+ return tlsOptions;
120
120
  };
121
121
 
122
122
  const getServiceAddress = (mdnsService) => {
123
- let address;
124
-
125
- if (mdnsService.txtRecord && mdnsService.txtRecord.ip) {
126
- // Use the advertised IP address if present.
127
- address = `${mdnsService.txtRecord.ip}:${mdnsService.port}`;
128
- } else {
129
- // Find a valid ipv4 address.
130
- const ipv4 = lodash__default["default"].find(mdnsService.addresses, (addy) => ip__default["default"].isV4Format(addy));
131
- const serviceDetails = {
132
- host: ipv4,
133
- port: mdnsService.port,
134
- };
135
-
136
- address = `${serviceDetails.host}:${serviceDetails.port}`;
137
- }
138
-
139
- return address;
123
+ let address;
124
+
125
+ if (mdnsService.txtRecord?.ip) {
126
+ // Use the advertised IP address if present.
127
+ address = `${mdnsService.txtRecord.ip}:${mdnsService.port}`;
128
+ } else {
129
+ // Find a valid ipv4 address.
130
+ const ipv4 = lodash__default["default"].find(mdnsService.addresses, (addy) => ip__default["default"].isV4Format(addy));
131
+ const serviceDetails = {
132
+ host: ipv4,
133
+ port: mdnsService.port,
134
+ };
135
+
136
+ address = `${serviceDetails.host}:${serviceDetails.port}`;
137
+ }
138
+
139
+ return address;
140
140
  };
141
141
 
142
142
  const privateKeyToPem = (keyPair) => {
143
- return pki$2.privateKeyToPem(keyPair.privateKey);
143
+ return pki$2.privateKeyToPem(keyPair.privateKey);
144
144
  };
145
145
 
146
146
  const publicKeyToPem = (keyPair) => {
147
- return pki$2.publicKeyToPem(keyPair.publicKey);
147
+ return pki$2.publicKeyToPem(keyPair.publicKey);
148
148
  };
149
149
 
150
150
  const deserialisePEM = (pem) => {
151
- return pem.replace(/\\r\\n/g, "\r\n");
151
+ return pem.replace(/\\r\\n/g, "\r\n");
152
152
  };
153
153
 
154
154
  const removeCarriageReturn = (inp) => {
155
- return inp.replace(/\r\n/g, "\n");
155
+ return inp.replace(/\r\n/g, "\n");
156
156
  };
157
157
 
158
158
  const createBase58Hash = (inp) => {
159
- const md = forge__default["default"].md.sha256.create();
160
- md.update(inp);
161
- const hashBuf = Buffer.from(md.digest().getBytes(), "binary");
162
- return bs58__default["default"].encode(hashBuf);
159
+ const md = forge__default["default"].md.sha256.create();
160
+ md.update(inp);
161
+ const hashBuf = Buffer.from(md.digest().getBytes(), "binary");
162
+ return bs58__default["default"].encode(hashBuf);
163
163
  };
164
164
 
165
165
  const createPublicKeyFingerprint = (key) => {
166
- // Remove carriage returns before creating hash to bring into line with openSSL / volt format.
167
- return createBase58Hash(removeCarriageReturn(key));
166
+ // Remove carriage returns before creating hash to bring into line with openSSL / volt format.
167
+ return createBase58Hash(removeCarriageReturn(key));
168
168
  };
169
169
 
170
170
  const signBase64 = (key, msg) => {
171
- const md = forge__default["default"].md.sha256.create();
172
- md.update(msg);
173
- const signature = key.sign(md);
174
- return forge__default["default"].util.encode64(signature);
171
+ const md = forge__default["default"].md.sha256.create();
172
+ md.update(msg);
173
+ const signature = key.sign(md);
174
+ return forge__default["default"].util.encode64(signature);
175
175
  };
176
176
 
177
177
  const verifyBase64 = (key, msg, signature) => {
178
- const md = forge__default["default"].md.sha256.create();
179
- md.update(msg);
180
- return key.verify(md.digest().bytes(), forge__default["default"].util.decode64(signature));
178
+ const md = forge__default["default"].md.sha256.create();
179
+ md.update(msg);
180
+ return key.verify(md.digest().bytes(), forge__default["default"].util.decode64(signature));
181
181
  };
182
182
 
183
183
  const getDIDResolutionURL = (didIn) => {
184
- const did = didIn.toLowerCase().split(":");
185
- if (did.length < 3) {
186
- return "";
187
- }
188
-
189
- if (did[0] !== "did") {
190
- return "";
191
- }
192
-
193
- if (did[1] !== "tdx") {
194
- return "";
195
- }
196
-
197
- let hostName;
198
- let didGUID;
199
- if (did.length === 3) {
200
- hostName = constants.defaultDIDHostName;
201
- didGUID = did[2];
202
- } else {
203
- hostName = did[2];
204
- didGUID = did[3];
205
- }
206
-
207
- return `https://${hostName}/api/identity/${didGUID}`;
184
+ const did = didIn.toLowerCase().split(":");
185
+ if (did.length < 3) {
186
+ return "";
187
+ }
188
+
189
+ if (did[0] !== "did") {
190
+ return "";
191
+ }
192
+
193
+ if (did[1] !== "tdx") {
194
+ return "";
195
+ }
196
+
197
+ let hostName;
198
+ let didGUID;
199
+ if (did.length === 3) {
200
+ hostName = constants.defaultDIDHostName;
201
+ didGUID = did[2];
202
+ } else {
203
+ hostName = did[2];
204
+ didGUID = did[3];
205
+ }
206
+
207
+ return `https://${hostName}/api/identity/${didGUID}`;
208
208
  };
209
209
 
210
210
  var utils = /*#__PURE__*/Object.freeze({
211
- __proto__: null,
212
- createSecureContextOptions: createSecureContextOptions,
213
- getServiceAddress: getServiceAddress,
214
- privateKeyToPem: privateKeyToPem,
215
- publicKeyToPem: publicKeyToPem,
216
- deserialisePEM: deserialisePEM,
217
- removeCarriageReturn: removeCarriageReturn,
218
- createBase58Hash: createBase58Hash,
219
- createPublicKeyFingerprint: createPublicKeyFingerprint,
220
- signBase64: signBase64,
221
- verifyBase64: verifyBase64,
222
- getDIDResolutionURL: getDIDResolutionURL
211
+ __proto__: null,
212
+ createSecureContextOptions: createSecureContextOptions,
213
+ getServiceAddress: getServiceAddress,
214
+ privateKeyToPem: privateKeyToPem,
215
+ publicKeyToPem: publicKeyToPem,
216
+ deserialisePEM: deserialisePEM,
217
+ removeCarriageReturn: removeCarriageReturn,
218
+ createBase58Hash: createBase58Hash,
219
+ createPublicKeyFingerprint: createPublicKeyFingerprint,
220
+ signBase64: signBase64,
221
+ verifyBase64: verifyBase64,
222
+ getDIDResolutionURL: getDIDResolutionURL
223
223
  });
224
224
 
225
225
  /* eslint-disable no-underscore-dangle */
226
226
 
227
- const {forEach, isEmpty} = lodash__default["default"];
227
+ const { forEach, isEmpty } = lodash__default["default"];
228
228
 
229
229
  const serialiseNOP = (arg) => {
230
- return arg;
230
+ return arg;
231
231
  };
232
232
 
233
- function createClient(grpc, serviceDescriptors, address, cryptoOptions, noSerialise, voltId, serviceId) {
234
- let credentials;
235
- if (cryptoOptions) {
236
- const ca = cryptoOptions.tunnel_ca_pem || cryptoOptions.ca;
237
- const cert = cryptoOptions.cloud_cert || cryptoOptions.cert;
238
- const {key} = cryptoOptions;
239
-
240
- if (key && cert) {
241
- const cryyptoOptions = {ca, cert, key};
242
- const tlsOptions = createSecureContextOptions(cryyptoOptions);
243
- credentials = grpc.credentials.createSsl(tlsOptions.ca, tlsOptions.key, tlsOptions.cert);
244
- } else {
245
- // Cache has no private key, this implies we are connecting without supplying a client certificate.
246
- // Simply connect using the CA certificate.
247
- credentials = grpc.credentials.createSsl(Buffer.from(ca));
248
- }
249
- } else {
250
- credentials = grpc.credentials.createInsecure();
251
- }
252
-
253
- // Force all methods to appear bi-directional, since we manually handle the call flow (see grpc-call.js).
254
- forEach(serviceDescriptors, (method) => {
255
- method.requestStream = true;
256
- method.responseStream = true;
257
- });
258
-
259
- if (noSerialise || voltId) {
260
- if (voltId && !serviceId) {
261
- // We must have a service identifier id when tunnelling in order to be able to route the rpc.
262
- throw new Error("createClient - no serviceId given");
263
- }
264
- forEach(serviceDescriptors, (method) => {
265
- if (voltId) {
266
- // Prepend the resource id to the method path if tunnelling.
267
- if (voltId === serviceId) {
268
- method.path = `/${voltId}${method.path}`;
269
- } else {
270
- method.path = `/${voltId}/${serviceId}${method.path}`;
271
- }
272
- }
273
- if (noSerialise) {
274
- // Save original serialisation methods so we can encrypt/decrypt in the tunnel.
275
- method.requestSerializeOriginal = method.requestSerialize;
276
- method.responseDeserializeOriginal = method.responseDeserialize;
277
-
278
- // Replace default serialisation with NOP, since when tunnelling we encrypt the payload
279
- // before sending it to the channel, so we want it to be treated as a pure byte array (pass-through).
280
- method.requestSerialize = serialiseNOP;
281
- method.responseDeserialize = serialiseNOP;
282
- }
283
- });
284
- }
285
-
286
- const SubClass = grpc.makeGenericClientConstructor(serviceDescriptors);
287
-
288
- return new SubClass(address, credentials);
233
+ function createClient(
234
+ grpc,
235
+ serviceDescriptors,
236
+ address,
237
+ credentials,
238
+ noSerialise,
239
+ voltId,
240
+ serviceId,
241
+ ) {
242
+ let grpcCredentials;
243
+ if (credentials) {
244
+ const ca = credentials.config?.relay?.ca_pem || credentials.cache.ca;
245
+ const cert = credentials.cache.cloud_cert || credentials.cache.cert;
246
+ const { key } = credentials.cache;
247
+
248
+ if (key && cert) {
249
+ const cryyptoOptions = { ca, cert, key };
250
+ const tlsOptions = createSecureContextOptions(cryyptoOptions);
251
+ grpcCredentials = grpc.credentials.createSsl(
252
+ tlsOptions.ca,
253
+ tlsOptions.key,
254
+ tlsOptions.cert,
255
+ );
256
+ } else {
257
+ // Cache has no private key, this implies we are connecting without supplying a client certificate.
258
+ // Simply connect using the CA certificate.
259
+ grpcCredentials = grpc.credentials.createSsl(Buffer.from(ca));
260
+ }
261
+ } else {
262
+ grpcCredentials = grpc.credentials.createInsecure();
263
+ }
264
+
265
+ // Force all methods to appear bi-directional, since we manually handle the call flow (see grpc-call.js).
266
+ forEach(serviceDescriptors, (method) => {
267
+ method.requestStream = true;
268
+ method.responseStream = true;
269
+ });
270
+
271
+ if (noSerialise || voltId) {
272
+ if (voltId && !serviceId) {
273
+ // We must have a service identifier id when tunnelling in order to be able to route the rpc.
274
+ throw new Error("createClient - no serviceId given");
275
+ }
276
+ forEach(serviceDescriptors, (method) => {
277
+ if (voltId) {
278
+ // Prepend the resource id to the method path if tunnelling.
279
+ if (voltId === serviceId) {
280
+ method.path = `/${voltId}${method.path}`;
281
+ } else {
282
+ method.path = `/${voltId}/${serviceId}${method.path}`;
283
+ }
284
+ }
285
+ if (noSerialise) {
286
+ // Save original serialisation methods so we can encrypt/decrypt in the tunnel.
287
+ method.requestSerializeOriginal = method.requestSerialize;
288
+ method.responseDeserializeOriginal = method.responseDeserialize;
289
+
290
+ // Replace default serialisation with NOP, since when tunnelling we encrypt the payload
291
+ // before sending it to the channel, so we want it to be treated as a pure byte array (pass-through).
292
+ method.requestSerialize = serialiseNOP;
293
+ method.responseDeserialize = serialiseNOP;
294
+ }
295
+ });
296
+ }
297
+
298
+ const SubClass = grpc.makeGenericClientConstructor(serviceDescriptors);
299
+
300
+ return new SubClass(address, grpcCredentials);
289
301
  }
290
302
 
291
303
  /**
@@ -293,680 +305,767 @@ function createClient(grpc, serviceDescriptors, address, cryptoOptions, noSerial
293
305
  * @param {*} api
294
306
  */
295
307
  const grpcWrap = (api) => {
296
- const grpcRoutes = {};
297
-
298
- // Don't bother trying to wrap class constructors.
299
- const ignoreMethods = ["constructor"];
300
-
301
- // Support class instances and PoJos
302
- const isClass = api.constructor !== Object;
303
- const iterate = Object.getOwnPropertyNames(isClass ? api.constructor.prototype : api);
304
-
305
- // Wrap each method on the api.
306
- forEach(iterate, (name) => {
307
- if (!ignoreMethods.includes(name)) {
308
- const method = api[name];
309
- grpcRoutes[name] = (call, callback) => {
310
- // Execute the method in the context of the api.
311
- const resultPromise = method.call(api, call.request, call);
312
-
313
- // Enforce promise results.
314
- if (!resultPromise || !resultPromise.then || !resultPromise.catch) {
315
- throw new Error(`implementation methods must return a Promise [${name}]`);
316
- }
317
-
318
- resultPromise
319
- .then((response) => {
320
- if (callback) {
321
- callback(null, response);
322
- }
323
- })
324
- .catch((err) => {
325
- if (callback) {
326
- callback(err);
327
- } else {
328
- // TODO - verify this => how to send error to stream clients?
329
- // Destroy stream on error.
330
- call.destroy(err);
331
- }
332
- });
333
- };
334
- }
335
- });
336
-
337
- return grpcRoutes;
308
+ const grpcRoutes = {};
309
+
310
+ // Don't bother trying to wrap class constructors.
311
+ const ignoreMethods = ["constructor"];
312
+
313
+ // Support class instances and PoJos
314
+ const isClass = api.constructor !== Object;
315
+ const iterate = Object.getOwnPropertyNames(
316
+ isClass ? api.constructor.prototype : api,
317
+ );
318
+
319
+ // Wrap each method on the api.
320
+ forEach(iterate, (name) => {
321
+ if (!ignoreMethods.includes(name)) {
322
+ const method = api[name];
323
+ grpcRoutes[name] = (call, callback) => {
324
+ // Execute the method in the context of the api.
325
+ const resultPromise = method.call(api, call.request, call);
326
+
327
+ // Enforce promise results.
328
+ if (!(resultPromise?.then && resultPromise?.catch)) {
329
+ throw new Error(
330
+ `implementation methods must return a Promise [${name}]`,
331
+ );
332
+ }
333
+
334
+ resultPromise
335
+ .then((response) => {
336
+ if (callback) {
337
+ callback(null, response);
338
+ }
339
+ })
340
+ .catch((err) => {
341
+ if (callback) {
342
+ callback(err);
343
+ } else {
344
+ // TODO - verify this => how to send error to stream clients?
345
+ // Destroy stream on error.
346
+ call.destroy(err);
347
+ }
348
+ });
349
+ };
350
+ }
351
+ });
352
+
353
+ return grpcRoutes;
338
354
  };
339
355
 
340
356
  class GrpcServer {
341
- constructor(options) {
342
- const {grpc, serviceDescriptors, routes, tlsOptions, requireClientCert} = options;
343
- this._grpc = grpc;
344
- this._server = new this._grpc.Server();
345
-
346
- if (tlsOptions) {
347
- const caList = [];
348
- const certChains = [];
349
- [].concat(tlsOptions).forEach((tlsOption) => {
350
- caList.push(tlsOption.ca);
351
- certChains.push({
352
- private_key: tlsOption.key,
353
- cert_chain: tlsOption.cert,
354
- });
355
- });
356
-
357
- // Create credentials from the volt CA and our own pub/priv key.
358
- this._credentials = grpc.ServerCredentials.createSsl(
359
- // The root CAs we trust when verifying client certificates.
360
- Buffer.concat(caList),
361
- // The certificate chain(s) we present to the client.
362
- certChains,
363
- // Flag indicating if we insist on a client certificate.
364
- requireClientCert
365
- );
366
- } else {
367
- this._credentials = grpc.ServerCredentials.createInsecure();
368
- }
369
-
370
- if (serviceDescriptors && !isEmpty(routes)) {
371
- // Enforce decoupling of the service implementation.
372
- const router = grpcWrap(routes);
373
- this._server.addService(serviceDescriptors, router);
374
- }
375
- }
376
-
377
- close(force = false) {
378
- return new Promise((resolve) => {
379
- if (force) {
380
- resolve(this._server.forceShutdown());
381
- } else {
382
- this._server.tryShutdown(resolve);
383
- }
384
- });
385
- }
386
-
387
- listen(address) {
388
- return new Promise((resolve, reject) => {
389
- // If no port is specified, grpc will return the port number assigned.
390
- this._server.bindAsync(address, this._credentials, (err, port) => {
391
- if (err) {
392
- reject(err);
393
- } else {
394
- this._port = port;
395
- this._server.start();
396
- resolve(port);
397
- }
398
- });
399
- });
400
- }
401
-
402
- get server() {
403
- return this._server;
404
- }
405
-
406
- get port() {
407
- return this._port;
408
- }
357
+ constructor(options) {
358
+ const { grpc, serviceDescriptors, routes, tlsOptions, requireClientCert } =
359
+ options;
360
+ this._grpc = grpc;
361
+ this._server = new this._grpc.Server({
362
+ "grpc.keepalive_time_ms": 500,
363
+ "grpc.keepalive_timeout_ms": 5000,
364
+ "grpc.http2.max_pings_without_data": 0,
365
+ "grpc.keepalive_permit_without_calls": 1,
366
+ "grpc.http2.min_ping_interval_without_data_ms": 250,
367
+ "grpc.http2.max_ping_strikes": 0,
368
+ });
369
+
370
+ if (tlsOptions) {
371
+ const caList = [];
372
+ const certChains = [];
373
+ [].concat(tlsOptions).forEach((tlsOption) => {
374
+ caList.push(tlsOption.ca);
375
+ certChains.push({
376
+ private_key: tlsOption.key,
377
+ cert_chain: tlsOption.cert,
378
+ });
379
+ });
380
+
381
+ // Create credentials from the volt CA and our own pub/priv key.
382
+ this._credentials = grpc.ServerCredentials.createSsl(
383
+ // The root CAs we trust when verifying client certificates.
384
+ Buffer.concat(caList),
385
+ // The certificate chain(s) we present to the client.
386
+ certChains,
387
+ // Flag indicating if we insist on a client certificate.
388
+ requireClientCert,
389
+ );
390
+ } else {
391
+ this._credentials = grpc.ServerCredentials.createInsecure();
392
+ }
393
+
394
+ if (serviceDescriptors && !isEmpty(routes)) {
395
+ // Enforce decoupling of the service implementation.
396
+ const router = grpcWrap(routes);
397
+ this._server.addService(serviceDescriptors, router);
398
+ }
399
+ }
400
+
401
+ close(force = false) {
402
+ return new Promise((resolve) => {
403
+ if (force) {
404
+ resolve(this._server.forceShutdown());
405
+ } else {
406
+ this._server.tryShutdown(resolve);
407
+ }
408
+ });
409
+ }
410
+
411
+ listen(address) {
412
+ return new Promise((resolve, reject) => {
413
+ // If no port is specified, grpc will return the port number assigned.
414
+ this._server.bindAsync(address, this._credentials, (err, port) => {
415
+ if (err) {
416
+ reject(err);
417
+ } else {
418
+ this._port = port;
419
+ this._server.start();
420
+ resolve(port);
421
+ }
422
+ });
423
+ });
424
+ }
425
+
426
+ get server() {
427
+ return this._server;
428
+ }
429
+
430
+ get port() {
431
+ return this._port;
432
+ }
409
433
  }
410
434
 
411
- function createServer(grpc, serviceDescriptors, routes, cryptoCache, requireClientCert) {
412
- let tlsOptions;
413
- if (cryptoCache) {
414
- tlsOptions = createSecureContextOptions(cryptoCache);
415
- }
416
- const serverArgs = {grpc, serviceDescriptors, routes, tlsOptions, requireClientCert};
417
- return new GrpcServer(serverArgs);
435
+ function createServer(
436
+ grpc,
437
+ serviceDescriptors,
438
+ routes,
439
+ cryptoCache,
440
+ requireClientCert,
441
+ ) {
442
+ let tlsOptions;
443
+ if (cryptoCache) {
444
+ tlsOptions = createSecureContextOptions(cryptoCache);
445
+ }
446
+ const serverArgs = {
447
+ grpc,
448
+ serviceDescriptors,
449
+ routes,
450
+ tlsOptions,
451
+ requireClientCert,
452
+ };
453
+ return new GrpcServer(serverArgs);
418
454
  }
419
455
 
420
456
  var grpcUtils = /*#__PURE__*/Object.freeze({
421
- __proto__: null,
422
- createClient: createClient,
423
- createServer: createServer
457
+ __proto__: null,
458
+ createClient: createClient,
459
+ createServer: createServer
424
460
  });
425
461
 
426
462
  /* eslint-disable no-underscore-dangle */
427
463
 
428
- const {pki: pki$1} = forge__default["default"];
429
- const log$4 = debug__default["default"]("volt-client-grpc:volt-crypto");
464
+ const { pki: pki$1 } = forge__default["default"];
465
+ const log$4 = debug__default["default"]("volt-client-grpc:volt-credential");
430
466
  const aesAlgorithm = "aes-256-cbc";
431
467
  const rs256Algorithm = "RS256";
432
468
 
433
- class VoltCrypto {
434
- constructor(config, configPath) {
435
- this._config = config;
436
- this._voltConfig = config.volt;
437
- this._configPath = configPath;
438
- this._persistCache = !!configPath;
439
-
440
- if (!this._config.crypto) {
441
- this._cryptoCache = {};
442
- } else {
443
- this._cryptoCache = this._config.crypto;
444
- }
445
-
446
- // Determine if we're dealing with an encrypted key.
447
- if (this._cryptoCache.key && this._cryptoCache.key.startsWith(constants.privateEncryptedKeyPrefix)) {
448
- if (!config.p) {
449
- throw new Error("encrypted key but no passphrase given");
450
- }
451
-
452
- // Need to unencrypt the private key.
453
- const decrypted = pki$1.decryptRsaPrivateKey(this._cryptoCache.key, config.p);
454
- if (!decrypted) {
455
- throw new Error("failed to decrypt key - check passphrase");
456
- }
457
- this._cryptoCache.key = pki$1.privateKeyToPem(decrypted);
458
- }
459
-
460
- if (this._voltConfig.ca_pem) {
461
- if (!this._cryptoCache.ca) {
462
- // Copy the volt signing CA to the crypto cache.
463
- this._cryptoCache.ca = this._voltConfig.ca_pem;
464
- }
465
-
466
- // Pre-cache the target Volt public key by extracting it from the signing certificate.
467
- const voltCert = forge__default["default"].pki.certificateFromPem(this._voltConfig.ca_pem);
468
-
469
- // Extract Volt public key (used for encrypting tunnel payloads).
470
- this._voltPublicKey = forge__default["default"].pki.publicKeyToPem(voltCert.publicKey);
471
- this._voltFingerprint = createPublicKeyFingerprint(this._voltPublicKey);
472
- }
473
- }
474
-
475
- get cache() {
476
- return this._cryptoCache;
477
- }
478
-
479
- get voltFingerprint() {
480
- return this._voltFingerprint;
481
- }
482
-
483
- getKey() {
484
- const privateKey = pki$1.privateKeyFromPem(this._cryptoCache.key);
485
- const publicKey = pki$1.rsa.setPublicKey(privateKey.n, privateKey.e);
486
- return {privateKey, publicKey};
487
- }
488
-
489
- /**
490
- * Retrieves and re-hydrates the pub/priv key data from the crypto cache, or creates one if not found.
491
- */
492
- createKey() {
493
- if (!this._cryptoCache.key) {
494
- log$4("creating key");
495
- return new Promise((resolve, reject) => {
496
- pki$1.rsa.generateKeyPair({bits: 2048, workers: -1}, (err, keypair) => {
497
- if (err) {
498
- log$4("failure creating key [%s]", err.message);
499
- reject(err);
500
- } else {
501
- log$4("successfully created key");
502
- const pem = pki$1.privateKeyToPem(keypair.privateKey);
503
- this._cryptoCache.key = pem;
504
- resolve(keypair);
505
- }
506
- });
507
- });
508
- } else {
509
- // Already have key data in the cache in pem format => create fully-formed pki instances.
510
- log$4("createKey - key already exists");
511
- return Promise.resolve(this.getKey());
512
- }
513
- }
514
-
515
- /**
516
- * Create cryptocache from scratch.
517
- */
518
- initialise() {
519
- return this.createKey()
520
- .then((/* keypair */) => {
521
- return this.saveCache();
522
- })
523
- .then(() => {
524
- return this._cryptoCache;
525
- })
526
- .catch((err) => {
527
- log$4("failure initialising crypto [%s]", err.message);
528
- return Promise.reject(err);
529
- });
530
- }
531
-
532
- get isBound() {
533
- return !!this._cryptoCache.cert;
534
- }
535
-
536
- /**
537
- * Signs the identity resource id using the private key.
538
- * @param {*} audience the token audience (usually the target volt)
539
- * @param {*} tunnelling flag indicating if the token is required for a tunnelled connection
540
- * @param {*} ttl time to live in seconds (default to 1 minute)
541
- */
542
- getIdentityToken(audience, tunnelling = false, ttl = 60) {
543
- if (!this._cryptoCache.key) {
544
- throw new Error("crypto cache invalid");
545
- }
546
-
547
- const keyPair = this.getKey();
548
- const publicKeyPem = pki$1.publicKeyToPem(keyPair.publicKey);
549
- const base58Key = createPublicKeyFingerprint(publicKeyPem);
550
-
551
- log$4("base58 key is %s", base58Key);
552
-
553
- // Allow TTL either side of the current time.
554
- // @todo - fix with server time sync on volt connection.
555
- const payload = {
556
- aud: audience,
557
- iat: Math.floor(Date.now() / 1000) - ttl,
558
- exp: Math.floor(Date.now() / 1000) + ttl,
559
- };
560
-
561
- let sharedKey;
562
- if (tunnelling) {
563
- // Initialise the tunnel encryption key.
564
- sharedKey = VoltCrypto.aesCreateKey();
565
-
566
- // Encrypt the key details using the target Volt public key and include this in the JWT payload.
567
- payload.sk = VoltCrypto.rsaEncrypt(this._voltPublicKey, sharedKey.key);
568
- payload.iv = VoltCrypto.rsaEncrypt(this._voltPublicKey, sharedKey.iv);
569
- }
570
-
571
- // Sign synchronously.
572
- const token = jwt__default["default"].sign(payload, this._cryptoCache.key, {algorithm: rs256Algorithm, keyid: base58Key});
573
-
574
- // Return the token along with any encryption key details.
575
- return {
576
- token,
577
- sharedKey,
578
- };
579
- }
580
-
581
- /**
582
- * Creates the metadata required for a grpc call, including the Volt authentication token
583
- * and optionally tunnel encryption parameters.
584
- * @param {*} grpc
585
- * @param {*} audience
586
- * @param {*} tunnelling
587
- * @param {*} ttl
588
- * @returns
589
- */
590
- getIdentityMetadata(grpc, audience, tunnelling = false, ttl = 60) {
591
- const identityToken = this.getIdentityToken(audience || this._voltConfig.id, tunnelling, ttl);
592
- const metadata = new grpc.Metadata();
593
- metadata.add(constants.authTokenName, identityToken.token);
594
- return {...identityToken, metadata};
595
- }
596
-
597
- saveCache() {
598
- if (this._persistCache) {
599
- const clone = {...this._config, crypto: {...this._cryptoCache}};
600
- if (this._config.p) {
601
- // A passphrase option exists => encrypt the key before writing the cache file.
602
- const privateKey = pki$1.privateKeyFromPem(this._cryptoCache.key);
603
- clone.crypto.key = pki$1.encryptRsaPrivateKey(privateKey, this._config.p);
604
- }
605
- fs__default["default"].writeFileSync(this._configPath, JSON.stringify(clone, null, 2));
606
- }
607
- }
608
-
609
- static aesCreateKey() {
610
- // Generate random key for the AES-256 algorithm (32 bytes = 256 bits).
611
- const key = crypto__default["default"].randomBytes(32);
612
- const iv = crypto__default["default"].randomBytes(16);
613
- return {key, iv};
614
- }
615
-
616
- static aesEncrypt(buffer, key, iv) {
617
- const cipher = crypto__default["default"].createCipheriv(aesAlgorithm, key, iv);
618
- const crypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
619
- return crypted;
620
- }
621
-
622
- static aesDecrypt(buffer, key, iv) {
623
- const cipher = crypto__default["default"].createDecipheriv(aesAlgorithm, key, iv);
624
- const decrypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
625
- return decrypted;
626
- }
627
-
628
- static rsaEncrypt(key, buffer) {
629
- return crypto__default["default"].publicEncrypt(key, buffer).toString("base64");
630
- }
469
+ class VoltCredential {
470
+ constructor(config, configPath) {
471
+ this._config = config;
472
+ this._voltConfig = config.volt;
473
+ this._configPath = configPath;
474
+ this._persistCache = !!configPath;
475
+
476
+ if (this._config.credential) {
477
+ this._cryptoCache = this._config.credential;
478
+ } else {
479
+ this._cryptoCache = {};
480
+ }
481
+
482
+ // Determine if we're dealing with an encrypted key.
483
+ if (
484
+ this._cryptoCache.key?.startsWith(constants.privateEncryptedKeyPrefix)
485
+ ) {
486
+ if (!config.p) {
487
+ throw new Error("encrypted key but no passphrase given");
488
+ }
489
+
490
+ // Need to unencrypt the private key.
491
+ const decrypted = pki$1.decryptRsaPrivateKey(
492
+ this._cryptoCache.key,
493
+ config.p,
494
+ );
495
+ if (!decrypted) {
496
+ throw new Error("failed to decrypt key - check passphrase");
497
+ }
498
+ this._cryptoCache.key = pki$1.privateKeyToPem(decrypted);
499
+ }
500
+
501
+ if (this._voltConfig.ca_pem) {
502
+ if (!this._cryptoCache.ca) {
503
+ // Copy the volt signing CA to the crypto cache.
504
+ this._cryptoCache.ca = this._voltConfig.ca_pem;
505
+ }
506
+
507
+ // Pre-cache the target Volt public key by extracting it from the signing certificate.
508
+ const voltCert = forge__default["default"].pki.certificateFromPem(this._voltConfig.ca_pem);
509
+
510
+ // Extract Volt public key (used for encrypting Relay payloads).
511
+ this._voltPublicKey = forge__default["default"].pki.publicKeyToPem(voltCert.publicKey);
512
+ this._voltFingerprint = createPublicKeyFingerprint(
513
+ this._voltPublicKey,
514
+ );
515
+ }
516
+ }
517
+
518
+ get config() {
519
+ return this._config;
520
+ }
521
+
522
+ get cache() {
523
+ return this._cryptoCache;
524
+ }
525
+
526
+ get voltFingerprint() {
527
+ return this._voltFingerprint;
528
+ }
529
+
530
+ getKey() {
531
+ const privateKey = pki$1.privateKeyFromPem(this._cryptoCache.key);
532
+ const publicKey = pki$1.rsa.setPublicKey(privateKey.n, privateKey.e);
533
+ return { privateKey, publicKey };
534
+ }
535
+
536
+ /**
537
+ * Retrieves and re-hydrates the pub/priv key data from the crypto cache, or creates one if not found.
538
+ */
539
+ createKey() {
540
+ if (this._cryptoCache.key) {
541
+ // Already have key data in the cache in pem format => create fully-formed pki instances.
542
+ log$4("createKey - key already exists");
543
+ return Promise.resolve(this.getKey());
544
+ } else {
545
+ log$4("creating key");
546
+ return new Promise((resolve, reject) => {
547
+ pki$1.rsa.generateKeyPair({ bits: 2048, workers: -1 }, (err, keypair) => {
548
+ if (err) {
549
+ log$4("failure creating key [%s]", err.message);
550
+ reject(err);
551
+ } else {
552
+ log$4("successfully created key");
553
+ const pem = pki$1.privateKeyToPem(keypair.privateKey);
554
+ this._cryptoCache.key = pem;
555
+ resolve(keypair);
556
+ }
557
+ });
558
+ });
559
+ }
560
+ }
561
+
562
+ /**
563
+ * Create cryptocache from scratch.
564
+ */
565
+ initialise() {
566
+ return this.createKey()
567
+ .then((/* keypair */) => {
568
+ return this.saveCache();
569
+ })
570
+ .then(() => {
571
+ return this._cryptoCache;
572
+ })
573
+ .catch((err) => {
574
+ log$4("failure initialising crypto [%s]", err.message);
575
+ return Promise.reject(err);
576
+ });
577
+ }
578
+
579
+ get isBound() {
580
+ return !!this._cryptoCache.cert;
581
+ }
582
+
583
+ /**
584
+ * Signs the identity resource id using the private key.
585
+ * @param {*} audience the token audience (usually the target volt)
586
+ * @param {*} tunnelling flag indicating if the token is required for a tunnelled connection
587
+ * @param {*} ttl time to live in seconds (default to 1 minute)
588
+ */
589
+ getIdentityToken(audience, tunnelling = false, ttl = 60) {
590
+ if (!this._cryptoCache.key) {
591
+ throw new Error("crypto cache invalid");
592
+ }
593
+
594
+ const keyPair = this.getKey();
595
+ const publicKeyPem = pki$1.publicKeyToPem(keyPair.publicKey);
596
+ const base58Key = createPublicKeyFingerprint(publicKeyPem);
597
+
598
+ log$4("base58 key is %s", base58Key);
599
+
600
+ // Allow TTL either side of the current time.
601
+ // @todo - fix with server time sync on volt connection.
602
+ const payload = {
603
+ aud: audience,
604
+ iat: Math.floor(Date.now() / 1000) - ttl,
605
+ exp: Math.floor(Date.now() / 1000) + ttl,
606
+ };
607
+
608
+ let sharedKey;
609
+ if (tunnelling) {
610
+ // Initialise the Relay encryption key.
611
+ sharedKey = VoltCredential.aesCreateKey();
612
+
613
+ // Encrypt the key details using the target Volt public key and include this in the JWT payload.
614
+ payload.sk = VoltCredential.rsaEncrypt(
615
+ this._voltPublicKey,
616
+ sharedKey.key,
617
+ );
618
+ payload.iv = VoltCredential.rsaEncrypt(this._voltPublicKey, sharedKey.iv);
619
+ }
620
+
621
+ // Sign synchronously.
622
+ const token = jwt__default["default"].sign(payload, this._cryptoCache.key, {
623
+ algorithm: rs256Algorithm,
624
+ keyid: base58Key,
625
+ });
626
+
627
+ // Return the token along with any encryption key details.
628
+ return {
629
+ token,
630
+ sharedKey,
631
+ };
632
+ }
633
+
634
+ /**
635
+ * Creates the metadata required for a grpc call, including the Volt authentication token
636
+ * and optionally tunnel encryption parameters.
637
+ * @param {*} grpc
638
+ * @param {*} audience
639
+ * @param {*} tunnelling
640
+ * @param {*} ttl
641
+ * @returns
642
+ */
643
+ getIdentityMetadata(grpc, audience, tunnelling = false, ttl = 60) {
644
+ const identityToken = this.getIdentityToken(
645
+ audience || this._voltConfig.id,
646
+ tunnelling,
647
+ ttl,
648
+ );
649
+ const metadata = new grpc.Metadata();
650
+ metadata.add(constants.authTokenName, identityToken.token);
651
+ return { ...identityToken, metadata };
652
+ }
653
+
654
+ saveCache() {
655
+ if (this._persistCache) {
656
+ const clone = { ...this._config, credential: { ...this._cryptoCache } };
657
+ if (this._config.p) {
658
+ // A passphrase option exists => encrypt the key before writing the cache file.
659
+ const privateKey = pki$1.privateKeyFromPem(this._cryptoCache.key);
660
+ clone.credential.key = pki$1.encryptRsaPrivateKey(
661
+ privateKey,
662
+ this._config.p,
663
+ );
664
+ }
665
+ fs__default["default"].writeFileSync(this._configPath, JSON.stringify(clone, null, 2));
666
+ }
667
+ }
668
+
669
+ static aesCreateKey() {
670
+ // Generate random key for the AES-256 algorithm (32 bytes = 256 bits).
671
+ const key = crypto__default["default"].randomBytes(32);
672
+ const iv = crypto__default["default"].randomBytes(16);
673
+ return { key, iv };
674
+ }
675
+
676
+ static aesEncrypt(buffer, key, iv) {
677
+ const cipher = crypto__default["default"].createCipheriv(aesAlgorithm, key, iv);
678
+ const crypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
679
+ return crypted;
680
+ }
681
+
682
+ static aesDecrypt(buffer, key, iv) {
683
+ const cipher = crypto__default["default"].createDecipheriv(aesAlgorithm, key, iv);
684
+ const decrypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
685
+ return decrypted;
686
+ }
687
+
688
+ static rsaEncrypt(key, buffer) {
689
+ return crypto__default["default"].publicEncrypt(key, buffer).toString("base64");
690
+ }
631
691
  }
632
692
 
633
- const {get: getProp, snakeCase} = lodash__default["default"];
693
+ const { get: getProp, snakeCase } = lodash__default["default"];
634
694
  const __dirname$1 = path.dirname(url.fileURLToPath((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href))));
635
695
 
636
696
  const defaultProtoPath = path.join(__dirname$1, "../protobuf");
637
697
 
638
698
  const defaultLoaderOptions = {
639
- keepCase: true,
640
- longs: String,
641
- enums: String,
642
- defaults: true,
643
- oneofs: true,
644
- includeDirs: [defaultProtoPath],
699
+ keepCase: true,
700
+ longs: String,
701
+ enums: String,
702
+ defaults: true,
703
+ oneofs: true,
704
+ includeDirs: [defaultProtoPath],
645
705
  };
646
706
 
647
707
  const getProtoDescriptors = (grpc, protoPath, opts) => {
648
- const definition = protoLoader__default["default"].loadSync(protoPath, opts || defaultLoaderOptions);
649
- const descriptors = grpc.loadPackageDefinition(definition);
650
- return descriptors;
708
+ const definition = protoLoader__default["default"].loadSync(
709
+ protoPath,
710
+ opts || defaultLoaderOptions,
711
+ );
712
+ const descriptors = grpc.loadPackageDefinition(definition);
713
+ return descriptors;
651
714
  };
652
715
 
653
716
  const getProtoService = (descriptors, servicePath) => {
654
- const serviceDef = getProp(descriptors, servicePath);
655
- if (serviceDef && serviceDef.service) {
656
- return serviceDef.service;
657
- } else {
658
- return null;
659
- }
717
+ const serviceDef = getProp(descriptors, servicePath);
718
+ if (serviceDef?.service) {
719
+ return serviceDef.service;
720
+ } else {
721
+ return null;
722
+ }
660
723
  };
661
724
 
662
- function getServiceDescriptorsFromPath(grpc, protoPath, servicePackageName, opts) {
663
- let serviceDescriptors;
664
- const descriptors = getProtoDescriptors(grpc, protoPath, opts);
665
- if (descriptors) {
666
- serviceDescriptors = getProtoService(descriptors, servicePackageName);
667
- }
668
-
669
- return serviceDescriptors;
725
+ function getServiceDescriptorsFromPath(
726
+ grpc,
727
+ protoPath,
728
+ servicePackageName,
729
+ opts,
730
+ ) {
731
+ let serviceDescriptors;
732
+ const descriptors = getProtoDescriptors(grpc, protoPath, opts);
733
+ if (descriptors) {
734
+ serviceDescriptors = getProtoService(descriptors, servicePackageName);
735
+ }
736
+
737
+ return serviceDescriptors;
670
738
  }
671
739
 
672
740
  function getServiceDescriptors(grpc, servicePackageName, opts) {
673
- // Extract the package components of the service proto package. The package name should be of the
674
- // fully qualified proto path, e.g. tdx.volt_api.webcam.v1.WebcamControlAPI.
675
- const protoServiceComponents = servicePackageName.split(".");
676
-
677
- // The service name is the last component of the path.
678
- const protoServiceName = protoServiceComponents.pop();
679
-
680
- // The actual file name should match the snake case of the service name.
681
- const protoFileName = snakeCase(protoServiceName).toLowerCase() + ".proto";
682
-
683
- // The path to the proto file should match each component of the package name.
684
- const protoPath = path.join(defaultProtoPath, ...protoServiceComponents, protoFileName);
685
-
686
- let serviceDescriptors;
687
- const descriptors = getProtoDescriptors(grpc, protoPath, opts);
688
- if (descriptors) {
689
- serviceDescriptors = getProtoService(descriptors, servicePackageName);
690
- }
691
-
692
- return serviceDescriptors;
741
+ // Extract the package components of the service proto package. The package name should be of the
742
+ // fully qualified proto path, e.g. tdx.volt_api.webcam.v1.WebcamControlAPI.
743
+ const protoServiceComponents = servicePackageName.split(".");
744
+
745
+ // The service name is the last component of the path.
746
+ const protoServiceName = protoServiceComponents.pop();
747
+
748
+ // The actual file name should match the snake case of the service name.
749
+ const protoFileName = `${snakeCase(protoServiceName).toLowerCase()}.proto`;
750
+
751
+ // The path to the proto file should match each component of the package name.
752
+ const protoPath = path.join(
753
+ defaultProtoPath,
754
+ ...protoServiceComponents,
755
+ protoFileName,
756
+ );
757
+
758
+ let serviceDescriptors;
759
+ const descriptors = getProtoDescriptors(grpc, protoPath, opts);
760
+ if (descriptors) {
761
+ serviceDescriptors = getProtoService(descriptors, servicePackageName);
762
+ }
763
+
764
+ return serviceDescriptors;
693
765
  }
694
766
 
695
767
  function getProtoDescriptorMethods(protoDescriptor) {
696
- const methods = [];
697
- Object.keys(protoDescriptor).forEach((methodName) => {
698
- const method = protoDescriptor[methodName];
699
- methods.push({
700
- path: method.path,
701
- client_streaming: method.requestStream,
702
- server_streaming: method.responseStream,
703
- });
704
- });
705
- return methods;
768
+ const methods = [];
769
+ Object.keys(protoDescriptor).forEach((methodName) => {
770
+ const method = protoDescriptor[methodName];
771
+ methods.push({
772
+ path: method.path,
773
+ client_streaming: method.requestStream,
774
+ server_streaming: method.responseStream,
775
+ });
776
+ });
777
+ return methods;
706
778
  }
707
779
 
708
780
  var protoUtils = /*#__PURE__*/Object.freeze({
709
- __proto__: null,
710
- getServiceDescriptors: getServiceDescriptors,
711
- getProtoDescriptors: getProtoDescriptors,
712
- getProtoDescriptorMethods: getProtoDescriptorMethods,
713
- getServiceDescriptorsFromPath: getServiceDescriptorsFromPath
781
+ __proto__: null,
782
+ getServiceDescriptors: getServiceDescriptors,
783
+ getProtoDescriptors: getProtoDescriptors,
784
+ getProtoDescriptorMethods: getProtoDescriptorMethods,
785
+ getServiceDescriptorsFromPath: getServiceDescriptorsFromPath
714
786
  });
715
787
 
716
788
  /* eslint-disable no-underscore-dangle */
717
789
 
718
790
  const log$3 = debug__default["default"]("volt-client-grpc:grpc-call");
719
791
 
720
- function _prepareInvokeRequest(request, method, methodType = "METHOD_TYPE_UNARY") {
721
- const meta = this._voltClient.crypto.getIdentityMetadata(
722
- this._voltClient.grpc,
723
- this._voltClient.options.id,
724
- this._voltClient.isRemote
725
- );
726
- let invokeRequest;
727
- let callMethod = method;
728
-
729
- if (this._voltClient.isVoltTunnel) {
730
- let requestPayload;
731
- if (request) {
732
- requestPayload = this._grpcClient[method].requestSerialize(request);
733
- } else if (request !== null) {
734
- log$3("****************LOOKOUT****************** - empty request");
735
- } else {
736
- log$3("explicit empty request payload");
737
- }
738
-
739
- const tunnelMethod = this._grpcClient.Tunnel;
740
-
741
- const tunnelResp = {
742
- method_invoke: {
743
- method_name: this._grpcClient[method].path,
744
- method_type: methodType,
745
- token: meta.token,
746
- request: requestPayload,
747
- },
748
- };
749
-
750
- const invokePayload = VoltCrypto.aesEncrypt(
751
- tunnelMethod.responseSerialize(tunnelResp),
752
- meta.sharedKey.key,
753
- meta.sharedKey.iv
754
- );
755
-
756
- log$3("target volt is %s", this._voltClient.crypto.voltFingerprint);
757
-
758
- invokeRequest = {
759
- identity_fingerprint: this._voltClient.crypto.voltFingerprint,
760
- payload: invokePayload,
761
- };
762
-
763
- callMethod = "Invoke";
764
- } else if (this._voltClient.isRemote && meta.sharedKey.key) {
765
- const requestPayload = this._grpcClient[method].requestSerializeOriginal(request);
766
- invokeRequest = VoltCrypto.aesEncrypt(requestPayload, meta.sharedKey.key, meta.sharedKey.iv);
767
- } else {
768
- invokeRequest = request;
769
- }
770
-
771
- return {
772
- meta,
773
- method: callMethod,
774
- methodName: method,
775
- request: invokeRequest,
776
- };
792
+ function _prepareInvokeRequest(
793
+ request,
794
+ method,
795
+ methodType = "METHOD_TYPE_UNARY",
796
+ ) {
797
+ const meta = this._voltClient.credential.getIdentityMetadata(
798
+ this._voltClient.grpc,
799
+ this._voltClient.voltConfig.id,
800
+ this._voltClient.isRemote,
801
+ );
802
+ let invokeRequest;
803
+ let callMethod = method;
804
+
805
+ if (this._voltClient.isVoltRelay) {
806
+ let requestPayload;
807
+ if (request) {
808
+ requestPayload = this._grpcClient[method].requestSerialize(request);
809
+ } else if (request !== null) {
810
+ log$3("****************LOOKOUT****************** - empty request");
811
+ } else {
812
+ log$3("explicit empty request payload");
813
+ }
814
+
815
+ const tunnelMethod = this._grpcClient.Tunnel;
816
+
817
+ const tunnelResp = {
818
+ method_invoke: {
819
+ method_name: this._grpcClient[method].path,
820
+ method_type: methodType,
821
+ token: meta.token,
822
+ request: requestPayload,
823
+ },
824
+ };
825
+
826
+ const invokePayload = VoltCredential.aesEncrypt(
827
+ tunnelMethod.responseSerialize(tunnelResp),
828
+ meta.sharedKey.key,
829
+ meta.sharedKey.iv,
830
+ );
831
+
832
+ log$3("target volt is %s", this._voltClient.credential.voltFingerprint);
833
+
834
+ invokeRequest = {
835
+ identity_fingerprint: this._voltClient.credential.voltFingerprint,
836
+ payload: invokePayload,
837
+ };
838
+
839
+ callMethod = "Invoke";
840
+ } else if (this._voltClient.isRemote && meta.sharedKey.key) {
841
+ const requestPayload =
842
+ this._grpcClient[method].requestSerializeOriginal(request);
843
+ invokeRequest = VoltCredential.aesEncrypt(
844
+ requestPayload,
845
+ meta.sharedKey.key,
846
+ meta.sharedKey.iv,
847
+ );
848
+ } else {
849
+ invokeRequest = request;
850
+ }
851
+
852
+ return {
853
+ meta,
854
+ method: callMethod,
855
+ methodName: method,
856
+ request: invokeRequest,
857
+ };
777
858
  }
778
859
 
779
860
  function _preparePayloadRequest(request, invokeInfo) {
780
- let payloadRequest;
781
-
782
- if (this._voltClient.isVoltTunnel) {
783
- const requestPayload = this._grpcClient[invokeInfo.methodName].requestSerialize(request);
784
- const tunnelMethod = this._grpcClient.Tunnel;
785
-
786
- const tunnelResp = {
787
- method_payload: {
788
- payload: requestPayload,
789
- },
790
- };
791
-
792
- const invokePayload = VoltCrypto.aesEncrypt(
793
- tunnelMethod.responseSerialize(tunnelResp),
794
- invokeInfo.meta.sharedKey.key,
795
- invokeInfo.meta.sharedKey.iv
796
- );
797
-
798
- payloadRequest = {
799
- payload: invokePayload,
800
- };
801
- } else if (this._voltClient.isRemote && invokeInfo.meta.sharedKey.key) {
802
- const requestPayload = this._grpcClient[invokeInfo.methodName].requestSerializeOriginal(request);
803
- payloadRequest = VoltCrypto.aesEncrypt(requestPayload, invokeInfo.meta.sharedKey.key, invokeInfo.meta.sharedKey.iv);
804
- } else {
805
- payloadRequest = request;
806
- }
807
-
808
- return payloadRequest;
861
+ let payloadRequest;
862
+
863
+ if (this._voltClient.isVoltRelay) {
864
+ const requestPayload =
865
+ this._grpcClient[invokeInfo.methodName].requestSerialize(request);
866
+ const tunnelMethod = this._grpcClient.Tunnel;
867
+
868
+ const tunnelResp = {
869
+ method_payload: {
870
+ payload: requestPayload,
871
+ },
872
+ };
873
+
874
+ const invokePayload = VoltCredential.aesEncrypt(
875
+ tunnelMethod.responseSerialize(tunnelResp),
876
+ invokeInfo.meta.sharedKey.key,
877
+ invokeInfo.meta.sharedKey.iv,
878
+ );
879
+
880
+ payloadRequest = {
881
+ payload: invokePayload,
882
+ };
883
+ } else if (this._voltClient.isRemote && invokeInfo.meta.sharedKey.key) {
884
+ const requestPayload =
885
+ this._grpcClient[invokeInfo.methodName].requestSerializeOriginal(request);
886
+ payloadRequest = VoltCredential.aesEncrypt(
887
+ requestPayload,
888
+ invokeInfo.meta.sharedKey.key,
889
+ invokeInfo.meta.sharedKey.iv,
890
+ );
891
+ } else {
892
+ payloadRequest = request;
893
+ }
894
+
895
+ return payloadRequest;
809
896
  }
810
897
 
811
898
  function _parseResponse(method, meta, response) {
812
- let invokeResponse = {};
813
-
814
- if (this._voltClient.isVoltTunnel) {
815
- if (response.payload) {
816
- const decryptedPayload = VoltCrypto.aesDecrypt(response.payload, meta.sharedKey.key, meta.sharedKey.iv);
817
- const tunnelMethod = this._grpcClient.Tunnel;
818
- const responsePayload = tunnelMethod.requestDeserialize(decryptedPayload);
819
- if (responsePayload.payload === "method_payload") {
820
- invokeResponse.payload = this._grpcClient[method].responseDeserialize(responsePayload.method_payload.payload);
821
- } else if (responsePayload.payload === "method_end") {
822
- invokeResponse = responsePayload.method_end;
823
- } else {
824
- log$3("unexpected tunnel payload type: %s", responsePayload.payload);
825
- }
826
- } else if (response.status && response.status.message) {
827
- // There's been an error in the tunnel.
828
- log$3(
829
- "Tunnel status received: %s, code %d, description: %s",
830
- response.status.message,
831
- response.status.code,
832
- response.status.description || "n/a"
833
- );
834
- invokeResponse = {ended: true, error: `Error in tunnel: ${response.status.message}`};
835
- } else {
836
- invokeResponse.methodId = response.invoke_id;
837
- log$3("started method %d for %s", invokeResponse.methodId, method);
838
- }
839
- } else if (this._voltClient.isRemote && meta.sharedKey.key) {
840
- const decryptedPayload = VoltCrypto.aesDecrypt(response, meta.sharedKey.key, meta.sharedKey.iv);
841
- invokeResponse = {payload: this._grpcClient[method].responseDeserializeOriginal(decryptedPayload)};
842
- } else {
843
- invokeResponse = {payload: response};
844
- }
845
-
846
- return invokeResponse;
899
+ let invokeResponse = {};
900
+
901
+ if (this._voltClient.isVoltRelay) {
902
+ if (response.payload) {
903
+ const decryptedPayload = VoltCredential.aesDecrypt(
904
+ response.payload,
905
+ meta.sharedKey.key,
906
+ meta.sharedKey.iv,
907
+ );
908
+ const tunnelMethod = this._grpcClient.Tunnel;
909
+ const responsePayload = tunnelMethod.requestDeserialize(decryptedPayload);
910
+ if (responsePayload.payload === "method_payload") {
911
+ invokeResponse.payload = this._grpcClient[method].responseDeserialize(
912
+ responsePayload.method_payload.payload,
913
+ );
914
+ } else if (responsePayload.payload === "method_end") {
915
+ invokeResponse = responsePayload.method_end;
916
+ } else {
917
+ log$3("unexpected tunnel payload type: %s", responsePayload.payload);
918
+ }
919
+ } else if (response.status?.message) {
920
+ // There's been an error in the tunnel.
921
+ log$3(
922
+ "Tunnel status received: %s, code %d, description: %s",
923
+ response.status.message,
924
+ response.status.code,
925
+ response.status.description || "n/a",
926
+ );
927
+ invokeResponse = {
928
+ ended: true,
929
+ error: `Error in tunnel: ${response.status.message}`,
930
+ };
931
+ } else {
932
+ invokeResponse.methodId = response.invoke_id;
933
+ log$3("started method %d for %s", invokeResponse.methodId, method);
934
+ }
935
+ } else if (this._voltClient.isRemote && meta.sharedKey.key) {
936
+ const decryptedPayload = VoltCredential.aesDecrypt(
937
+ response,
938
+ meta.sharedKey.key,
939
+ meta.sharedKey.iv,
940
+ );
941
+ invokeResponse = {
942
+ payload:
943
+ this._grpcClient[method].responseDeserializeOriginal(decryptedPayload),
944
+ };
945
+ } else {
946
+ invokeResponse = { payload: response };
947
+ }
948
+
949
+ return invokeResponse;
847
950
  }
848
951
 
849
952
  class GRPCCall extends EventEmitter__default["default"] {
850
- constructor(voltClient, methodName, methodType) {
851
- super();
852
- this._methodName = methodName;
853
- this._methodType = methodType;
854
- this._call = null;
855
- this._voltClient = voltClient;
856
- this._lastResponse = null;
857
- this._promise = null;
858
- this._reject = null;
859
- }
860
-
861
- reject(err) {
862
- if (this._reject) {
863
- this._reject(err);
864
- }
865
- }
866
-
867
- wait() {
868
- return this._promise;
869
- }
870
-
871
- start(grpcClient, request, responseCB) {
872
- this._promise = new Promise((resolve, reject) => {
873
- this._grpcClient = grpcClient;
874
- this._reject = reject;
875
-
876
- const callbackIntercept = (err, response) => {
877
- log$3("received callback for method %s", this._methodName);
878
- if (err) {
879
- reject(err);
880
- } else if (response) {
881
- this._lastResponse = response;
882
- if (responseCB) {
883
- responseCB(err, response);
884
- }
885
- } else {
886
- this.end();
887
- resolve(this._lastResponse);
888
- }
889
- };
890
-
891
- this._initialRequest = _prepareInvokeRequest.call(this, request, this._methodName, this._methodType);
892
-
893
- if (!this._grpcClient[this._initialRequest.method]) {
894
- return reject(new Error(`method not found: '${this._initialRequest.method}'`));
895
- }
896
-
897
- this._call = this._grpcClient[this._initialRequest.method](this._initialRequest.meta.metadata, callbackIntercept);
898
-
899
- this._call.on("data", (streamResponse) => {
900
- try {
901
- const parsedResponse = _parseResponse.call(this, this._methodName, this._initialRequest.meta, streamResponse);
902
- if (parsedResponse.payload) {
903
- callbackIntercept(null, parsedResponse.payload);
904
- } else if (parsedResponse.ended) {
905
- if (parsedResponse.error) {
906
- callbackIntercept(new Error(parsedResponse.error), null);
907
- } else {
908
- callbackIntercept(null, null);
909
- }
910
- } else {
911
- log$3("method id is %s", parsedResponse.methodId);
912
- }
913
- } catch (err) {
914
- log$3("failure processing connect response: %s", err.message);
915
- this.emit("error", err);
916
- }
917
- });
918
-
919
- this._call.on("error", (err) => {
920
- log$3("ERROR - intercepted stream error %s", err.message);
921
- callbackIntercept(err, null);
922
- });
923
-
924
- this._call.on("finish", () => {
925
- // The read side has ended (i.e. we called end()).
926
- log$3("finished call %s", this._methodName);
927
- this.emit("finish");
928
- });
929
-
930
- this._call.on("end", () => {
931
- // The remote peer ended the stream.
932
- log$3("ended call %s, method id: %s", this._methodName, this._initialRequest.methodId || "n/a - not tunnelling");
933
- this.emit("end");
934
- callbackIntercept(null, null);
935
- });
936
-
937
- if (this._initialRequest.request) {
938
- this._call.write(this._initialRequest.request);
939
- }
940
- });
941
-
942
- return this;
943
- }
944
-
945
- end() {
946
- if (!this._call) {
947
- throw new Error("call not initialised");
948
- } else {
949
- return this._call.end();
950
- }
951
- }
952
-
953
- get writable() {
954
- return this._call && this._call.writable;
955
- }
956
-
957
- write(request) {
958
- if (!this._call) {
959
- log$3("ERROR - call not initialised");
960
- throw new Error("call not initialised");
961
- } else if (!this._initialRequest) {
962
- this._initialRequest = _prepareInvokeRequest.call(this, request, this._methodName, this._methodType);
963
-
964
- return this._call.write(this._initialRequest.request);
965
- } else {
966
- const payloadRequest = _preparePayloadRequest.call(this, request, this._initialRequest);
967
- return this._call.write(payloadRequest);
968
- }
969
- }
953
+ constructor(voltClient, methodName, methodType) {
954
+ super();
955
+ this._methodName = methodName;
956
+ this._methodType = methodType;
957
+ this._call = null;
958
+ this._voltClient = voltClient;
959
+ }
960
+
961
+ start(grpcClient, request) {
962
+ this._grpcClient = grpcClient;
963
+
964
+ this._initialRequest = _prepareInvokeRequest.call(
965
+ this,
966
+ request,
967
+ this._methodName,
968
+ this._methodType,
969
+ );
970
+
971
+ if (!this._grpcClient[this._initialRequest.method]) {
972
+ return reject(
973
+ new Error(`method not found: '${this._initialRequest.method}'`),
974
+ );
975
+ }
976
+
977
+ this._call = this._grpcClient[this._initialRequest.method](
978
+ this._initialRequest.meta.metadata,
979
+ );
980
+
981
+ this._call.on("data", (streamResponse) => {
982
+ try {
983
+ const parsedResponse = _parseResponse.call(
984
+ this,
985
+ this._methodName,
986
+ this._initialRequest.meta,
987
+ streamResponse,
988
+ );
989
+ if (parsedResponse.payload) {
990
+ this.emit("data", parsedResponse.payload);
991
+ } else if (parsedResponse.ended) {
992
+ if (parsedResponse.error) {
993
+ this.emit("error", new Error(parsedResponse.error));
994
+ } else {
995
+ // Not sure this is necessary - we should receive "end" from grpc soon...
996
+ this.emit("end");
997
+ }
998
+ } else {
999
+ log$3("method id is %s", parsedResponse.methodId);
1000
+ }
1001
+ } catch (err) {
1002
+ log$3("failure processing connect response: %s", err.message);
1003
+ this.emit("error", err);
1004
+ }
1005
+ });
1006
+
1007
+ this._call.on("error", (err) => {
1008
+ log$3("ERROR - intercepted stream error %s", err.message);
1009
+ this.emit("error", err);
1010
+ });
1011
+
1012
+ this._call.on("finish", () => {
1013
+ // The read side has ended (i.e. we called end()).
1014
+ log$3("finished call %s", this._methodName);
1015
+ this.emit("finish");
1016
+ });
1017
+
1018
+ this._call.on("end", () => {
1019
+ // The remote peer ended the stream.
1020
+ log$3(
1021
+ "ended call %s, method id: %s",
1022
+ this._methodName,
1023
+ this._initialRequest.methodId || "n/a - not tunnelling",
1024
+ );
1025
+ this.emit("end");
1026
+ });
1027
+
1028
+ if (this._initialRequest.request) {
1029
+ this._call.write(this._initialRequest.request);
1030
+ }
1031
+
1032
+ return this;
1033
+ }
1034
+
1035
+ end() {
1036
+ if (this._call) {
1037
+ return this._call.end();
1038
+ } else {
1039
+ throw new Error("call not initialised");
1040
+ }
1041
+ }
1042
+
1043
+ get writable() {
1044
+ return this._call?.writable;
1045
+ }
1046
+
1047
+ write(request) {
1048
+ if (!this._call) {
1049
+ log$3("ERROR - call not initialised");
1050
+ throw new Error("call not initialised");
1051
+ } else if (this._initialRequest) {
1052
+ const payloadRequest = _preparePayloadRequest.call(
1053
+ this,
1054
+ request,
1055
+ this._initialRequest,
1056
+ );
1057
+ return this._call.write(payloadRequest);
1058
+ } else {
1059
+ this._initialRequest = _prepareInvokeRequest.call(
1060
+ this,
1061
+ request,
1062
+ this._methodName,
1063
+ this._methodType,
1064
+ );
1065
+
1066
+ return this._call.write(this._initialRequest.request);
1067
+ }
1068
+ }
970
1069
  }
971
1070
 
972
1071
  /* eslint-disable no-use-before-define */
@@ -974,924 +1073,1058 @@ class GRPCCall extends EventEmitter__default["default"] {
974
1073
  const log$2 = debug__default["default"]("volt-client-grpc:volt-connection");
975
1074
 
976
1075
  function _cleanUp(immediateReconnect) {
977
- this._session = false;
978
-
979
- if (this._pingTimer) {
980
- clearTimeout(this._pingTimer);
981
- this._pingTimer = 0;
982
- }
983
-
984
- if (this._pingTimeoutTimer) {
985
- clearTimeout(this._pingTimeoutTimer);
986
- this._pingTimeoutTimer = 0;
987
- }
988
-
989
- if (!this._dying && (immediateReconnect || (this._autoRetry && !this._reconnectTimer))) {
990
- this._reconnectTimer = setTimeout(
991
- () => {
992
- this._reconnectTimer = 0;
993
- _doConnect.call(this);
994
- },
995
- immediateReconnect ? 0 : this._reconnectInterval
996
- );
997
- }
998
-
999
- if (this.call && this.call.writable) {
1000
- this.call.end();
1001
- }
1076
+ this._session = false;
1077
+
1078
+ if (this._pingTimer) {
1079
+ clearTimeout(this._pingTimer);
1080
+ this._pingTimer = 0;
1081
+ }
1082
+
1083
+ if (this._pingTimeoutTimer) {
1084
+ clearTimeout(this._pingTimeoutTimer);
1085
+ this._pingTimeoutTimer = 0;
1086
+ }
1087
+
1088
+ if (
1089
+ !this._dying &&
1090
+ (immediateReconnect || (this._autoRetry && !this._reconnectTimer))
1091
+ ) {
1092
+ this._reconnectTimer = setTimeout(
1093
+ () => {
1094
+ this._reconnectTimer = 0;
1095
+ _doConnect.call(this);
1096
+ },
1097
+ immediateReconnect ? 0 : this._reconnectInterval,
1098
+ );
1099
+ }
1100
+
1101
+ if (this.call?.writable) {
1102
+ this.call.end();
1103
+ }
1002
1104
  }
1003
1105
 
1004
1106
  function _connectionTimeoutHandler() {
1005
- log$2("server timed out");
1006
- this.emit("connected", false);
1007
- _cleanUp.call(this);
1107
+ log$2("server timed out");
1108
+ this.emit("connected", false);
1109
+ _cleanUp.call(this);
1008
1110
  }
1009
1111
 
1010
1112
  function _doConnect() {
1011
- this.call = new GRPCCall(this._voltClient, "Connect", "METHOD_TYPE_BIDI");
1012
-
1013
- const grpcClient = this._voltClient.getVoltAPIClient();
1014
- const helloPayload = {
1015
- hello: {},
1016
- };
1017
-
1018
- this.call.start(grpcClient, helloPayload, (err, response) => {
1019
- if (err) {
1020
- log$2("error on connection stream [%s]", err.message);
1021
- _cleanUp.call(this);
1022
- this.emit("error", err);
1023
- } else {
1024
- switch (response.payload) {
1025
- case "ping": {
1026
- log$2("pinged");
1027
-
1028
- // Received ping response from server => clear timeout.
1029
- if (this._pingTimeoutTimer) {
1030
- clearTimeout(this._pingTimeoutTimer);
1031
- }
1032
-
1033
- // Schedule the next ping.
1034
- _startPingTimer.call(this);
1035
- break;
1036
- }
1037
- case "hello":
1038
- if (!this._session) {
1039
- this._session = true;
1040
- this.emit("connected", this._session);
1041
- }
1042
- break;
1043
- case "evt":
1044
- log$2("received event %s", response.evt.event_type);
1045
- this.emit("evt", response.evt);
1046
- break;
1047
- default:
1048
- log$2("unimplemented connect response payload: %s", response.payload);
1049
- break;
1050
- }
1051
- }
1052
- });
1053
-
1054
- this.call
1055
- .wait()
1056
- .then(() => {
1057
- if (this._session) {
1058
- this.emit("connected", false);
1059
- }
1060
- })
1061
- .catch((err) => {
1062
- log$2("unexpected error on connect call [%s]", err.message);
1063
- })
1064
- .finally(() => {
1065
- _cleanUp.call(this);
1066
- });
1067
-
1068
- _startPingTimer.call(this);
1113
+ this.call = new GRPCCall(this._voltClient, "Connect", "METHOD_TYPE_BIDI");
1114
+
1115
+ const grpcClient = this._voltClient.getVoltAPIClient();
1116
+ const helloPayload = {
1117
+ hello: {},
1118
+ };
1119
+
1120
+ this.call.start(grpcClient, helloPayload, (err, response) => {
1121
+ if (err) {
1122
+ log$2("error on connection stream [%s]", err.message);
1123
+ _cleanUp.call(this);
1124
+ this.emit("error", err);
1125
+ } else {
1126
+ switch (response.payload) {
1127
+ case "ping": {
1128
+ log$2("pinged");
1129
+
1130
+ // Received ping response from server => clear timeout.
1131
+ if (this._pingTimeoutTimer) {
1132
+ clearTimeout(this._pingTimeoutTimer);
1133
+ }
1134
+
1135
+ // Schedule the next ping.
1136
+ _startPingTimer.call(this);
1137
+ break;
1138
+ }
1139
+ case "hello": {
1140
+ if (!this._session) {
1141
+ this._session = true;
1142
+ this.emit("connected", this._session);
1143
+ }
1144
+ break;
1145
+ }
1146
+ case "evt": {
1147
+ log$2("received event %s", response.evt.event_type);
1148
+ this.emit("evt", response.evt);
1149
+ break;
1150
+ }
1151
+ default:
1152
+ log$2("unimplemented connect response payload: %s", response.payload);
1153
+ break;
1154
+ }
1155
+ }
1156
+ });
1157
+
1158
+ this.call
1159
+ .wait()
1160
+ .then(() => {
1161
+ if (this._session) {
1162
+ this.emit("connected", false);
1163
+ }
1164
+ })
1165
+ .catch((err) => {
1166
+ log$2("unexpected error on connect call [%s]", err.message);
1167
+ })
1168
+ .finally(() => {
1169
+ _cleanUp.call(this);
1170
+ });
1171
+
1172
+ _startPingTimer.call(this);
1069
1173
  }
1070
1174
 
1071
1175
  function _startPingTimer() {
1072
- if (this._pingTimer) {
1073
- log$2("ping timer running");
1074
- return;
1075
- }
1076
-
1077
- this._pingTimer = setTimeout(() => {
1078
- // Send next ping to server.
1079
- const request = {ping: {timestamp: Date.now()}};
1080
-
1081
- log$2("pinging Volt");
1082
- this.call.write(request);
1083
-
1084
- this._pingTimer = 0;
1085
-
1086
- // Schedule a timeout if we don't hear back from the server.
1087
- if (this._pingTimeoutTimer) {
1088
- clearTimeout(this._pingTimeoutTimer);
1089
- }
1090
-
1091
- this._pingTimeoutTimer = setTimeout(_connectionTimeoutHandler.bind(this), this._timeoutInterval);
1092
- }, this._pingInterval);
1176
+ if (this._pingTimer) {
1177
+ log$2("ping timer running");
1178
+ return;
1179
+ }
1180
+
1181
+ this._pingTimer = setTimeout(() => {
1182
+ // Send next ping to server.
1183
+ const request = { ping: { timestamp: Date.now() } };
1184
+
1185
+ log$2("pinging Volt");
1186
+ this.call.write(request);
1187
+
1188
+ this._pingTimer = 0;
1189
+
1190
+ // Schedule a timeout if we don't hear back from the server.
1191
+ if (this._pingTimeoutTimer) {
1192
+ clearTimeout(this._pingTimeoutTimer);
1193
+ }
1194
+
1195
+ this._pingTimeoutTimer = setTimeout(
1196
+ _connectionTimeoutHandler.bind(this),
1197
+ this._timeoutInterval,
1198
+ );
1199
+ }, this._pingInterval);
1093
1200
  }
1094
1201
 
1095
1202
  class VoltConnection extends EventEmitter__default["default"] {
1096
- constructor(voltClient, grpc, options = {}) {
1097
- super();
1098
-
1099
- this._grpc = grpc;
1100
- this._autoRetry = options.autoReconnect === undefined ? true : !!options.autoReconnect;
1101
- this._dying = false;
1102
- this._voltClient = voltClient;
1103
- this._options = options;
1104
- this._pingTimer = 0;
1105
- this._pingTimeoutTimer = 0;
1106
- this._session = false;
1107
- this._pingInterval = options.pingInterval || 10000;
1108
- this._reconnectInterval = options.reconnectInterval || 5000;
1109
- this._timeoutInterval = options.timeoutInterval || 60000;
1110
- }
1111
-
1112
- connect(throwOnFail) {
1113
- if (throwOnFail) {
1114
- return _doConnect.call(this);
1115
- } else {
1116
- return Promise.resolve(_cleanUp.call(this, true));
1117
- }
1118
- }
1119
-
1120
- disconnect() {
1121
- this._dying = true;
1122
- _cleanUp.call(this);
1123
- }
1203
+ constructor(voltClient, grpc) {
1204
+ super();
1205
+
1206
+ const config = voltClient.config;
1207
+ this._grpc = grpc;
1208
+ this._autoRetry =
1209
+ config.autoReconnect === undefined ? true : !!config.autoReconnect;
1210
+ this._dying = false;
1211
+ this._voltClient = voltClient;
1212
+ this._pingTimer = 0;
1213
+ this._pingTimeoutTimer = 0;
1214
+ this._session = false;
1215
+ this._pingInterval = config.pingInterval || 10000;
1216
+ this._reconnectInterval = config.reconnectInterval || 5000;
1217
+ this._timeoutInterval = config.timeoutInterval || 60000;
1218
+ }
1219
+
1220
+ connect(throwOnFail) {
1221
+ if (throwOnFail) {
1222
+ return _doConnect.call(this);
1223
+ } else {
1224
+ return Promise.resolve(_cleanUp.call(this, true));
1225
+ }
1226
+ }
1227
+
1228
+ disconnect() {
1229
+ this._dying = true;
1230
+ _cleanUp.call(this);
1231
+ }
1124
1232
  }
1125
1233
 
1126
1234
  /* eslint-disable no-underscore-dangle */
1127
1235
 
1128
- const {pki} = forge__default["default"];
1129
- const {filter, pick} = lodash__default["default"];
1236
+ const { pki } = forge__default["default"];
1237
+ const { filter, pick } = lodash__default["default"];
1130
1238
 
1131
1239
  const log$1 = debug__default["default"]("volt-client-grpc:volt-client-internal");
1132
1240
  const voltServices = [
1133
- constants.serviceType.voltAPI,
1134
- constants.serviceType.fileAPI,
1135
- constants.serviceType.sqliteDatabaseAPI,
1136
- constants.serviceType.sqliteServerAPI,
1137
- constants.serviceType.ssiAPI,
1138
- constants.serviceType.tunnelAPI,
1139
- constants.serviceType.wireAPI,
1241
+ constants.serviceType.voltAPI,
1242
+ constants.serviceType.fileAPI,
1243
+ constants.serviceType.sqliteDatabaseAPI,
1244
+ constants.serviceType.sqliteServerAPI,
1245
+ constants.serviceType.ssiAPI,
1246
+ constants.serviceType.relayAPI,
1247
+ constants.serviceType.wireAPI,
1140
1248
  ];
1141
1249
 
1142
1250
  function issueBind(bindRequest, ttl) {
1143
- // eslint-disable-next-line no-use-before-define
1144
- return unaryCall.call(this, "Bind", bindRequest).then((bindResponse) => {
1145
- log$1("got binding request response %j", bindResponse);
1146
- if (bindResponse.status && bindResponse.status.code) {
1147
- log$1("error in bind response: %s", bindResponse.status.message);
1148
- return Promise.reject(new Error(bindResponse.status.message));
1149
- } else {
1150
- switch (bindResponse.decision) {
1151
- case "POLICY_DECISION_PERMIT":
1152
- //
1153
- // The request status is permit => cache the bind response info.
1154
- //
1155
-
1156
- // This is the certificate assigned to us by the volt.
1157
- this._crypto.cache.cert = bindResponse.cert;
1158
-
1159
- // This is the signing CA used by the volt (don't ov)
1160
- this._crypto.cache.ca = bindResponse.chain;
1161
-
1162
- // Resource id is assigned by the volt.
1163
- this._crypto.cache.client_id = bindResponse.identity_id;
1164
- this._crypto.saveCache();
1165
- break;
1166
- case "POLICY_DECISION_DENY":
1167
- log$1(">>>>>>>>>>>>>>> access request is DENIED <<<<<<<<<<<<<<<<<<<");
1168
- break;
1169
- case "POLICY_DECISION_PROMPT":
1170
- case "POLICY_DECISION_PENDING":
1171
- log$1("access pending approval - waiting...");
1172
- break;
1173
- default:
1174
- log$1("ignoring unknown bind descision %s", bindResponse.status);
1175
- break;
1176
- }
1177
- }
1178
-
1179
- return bindResponse.decision;
1180
- });
1251
+ // eslint-disable-next-line no-use-before-define
1252
+ return unaryCall.call(this, "Bind", bindRequest).then((bindResponse) => {
1253
+ log$1("got binding request response %j", bindResponse);
1254
+ if (bindResponse.status?.code) {
1255
+ log$1("error in bind response: %s", bindResponse.status.message);
1256
+ return Promise.reject(new Error(bindResponse.status.message));
1257
+ } else {
1258
+ switch (bindResponse.decision) {
1259
+ case "POLICY_DECISION_PERMIT": {
1260
+ //
1261
+ // The request status is permit => cache the bind response info.
1262
+ //
1263
+
1264
+ // This is the certificate assigned to us by the volt.
1265
+ this._credential.cache.cert = bindResponse.cert;
1266
+
1267
+ // This is the signing CA used by the volt (don't ov)
1268
+ this._credential.cache.ca = bindResponse.chain;
1269
+
1270
+ // Resource id is assigned by the volt.
1271
+ this._credential.cache.client_id = bindResponse.identity_id;
1272
+ this._credential.saveCache();
1273
+ break;
1274
+ }
1275
+ case "POLICY_DECISION_DENY": {
1276
+ log$1(">>>>>>>>>>>>>>> access request is DENIED <<<<<<<<<<<<<<<<<<<");
1277
+ break;
1278
+ }
1279
+ case "POLICY_DECISION_PROMPT":
1280
+ case "POLICY_DECISION_PENDING": {
1281
+ log$1("access pending approval - waiting...");
1282
+ break;
1283
+ }
1284
+ default:
1285
+ log$1("ignoring unknown bind descision %s", bindResponse.status);
1286
+ break;
1287
+ }
1288
+ }
1289
+
1290
+ return bindResponse.decision;
1291
+ });
1181
1292
  }
1182
1293
 
1183
1294
  function findDIDDocumentService(document, serviceType) {
1184
- if (!document.service) {
1185
- return [];
1186
- }
1295
+ if (!document.service) {
1296
+ return [];
1297
+ }
1187
1298
 
1188
- const matches = filter(document.service, (svc) => svc.type === serviceType);
1189
- return matches;
1299
+ const matches = filter(document.service, (svc) => svc.type === serviceType);
1300
+ return matches;
1190
1301
  }
1191
1302
 
1192
1303
  async function bindInternal() {
1193
- try {
1194
- // Build grpc client info.
1195
- if (this.isRemote) {
1196
- const getJSON = bent__default["default"]("json");
1197
- // @todo - currently Volt tunnel CA discovery is not secure.
1198
- const protocol =
1199
- this._config.tunnel_host?.startsWith("localhost:") || this._config.cloud_host?.startsWith("localhost:")
1200
- ? "http"
1201
- : "https";
1202
- const tunnelURL = `${protocol}://${this._config.tunnel_host || this._config.cloud_host}/info`;
1203
- log$1("attempting to retrieve tunnel information from %s", tunnelURL);
1204
- const tunnelInfo = await getJSON(tunnelURL);
1205
- if (!tunnelInfo.ca_pem) {
1206
- throw new Error("Unable to fetch tunnel CA - cannot securely connect.");
1207
- } else {
1208
- log$1("Auto-fetched tunnel CA %s, remote address %s", tunnelInfo.ca_pem, tunnelInfo.local_address);
1209
- this._crypto.cache.tunnel_ca_pem = tunnelInfo.ca_pem;
1210
- this._crypto.cache.tunnel_address = tunnelInfo.local_address;
1211
- }
1212
- }
1213
-
1214
- if (!this._crypto.cache.ca) {
1215
- this._crypto.cache.ca = this._options.ca_pem;
1216
- }
1217
-
1218
- if (!this._crypto.cache.ca) {
1219
- throw new Error("No certificate authority found in configuration for target Volt - check configuration");
1220
- }
1221
-
1222
- const keyPair = this._crypto.getKey();
1223
- const publicKeyPem = pki.publicKeyToPem(keyPair.publicKey);
1224
-
1225
- if (!this._crypto.cache.bindIp) {
1226
- // Default the IP address if none is specified. This is used to set the SAN in the
1227
- // certificate issued by the Volt.
1228
- this._crypto.cache.bindIp = ip__default["default"].address();
1229
- }
1230
-
1231
- this._crypto.saveCache();
1232
-
1233
- // Form the request message.
1234
- const bindRequest = {
1235
- binding_name: this._config.client_name,
1236
- public_key: publicKeyPem,
1237
- host: this._crypto.cache.bindIp,
1238
- x509_credential: [],
1239
- };
1240
-
1241
- if (this._crypto.cache.cert) {
1242
- bindRequest.x509_credential = [this._crypto.cache.cert + this._crypto.cache.ca];
1243
- }
1244
-
1245
- if (this._options.challenge_code) {
1246
- bindRequest.challenge = signBase64(keyPair.privateKey, this._options.challenge_code);
1247
- } else {
1248
- log$1("****no Volt challenge code available**** => not sending challenge signature");
1249
- }
1250
-
1251
- // For remote connections, add our cloud-issued certificate as an additional credential.
1252
- if (this._crypto.cache.tunnel_ca_pem && this._crypto.cache.cloud_cert) {
1253
- bindRequest.x509_credential = bindRequest.x509_credential.concat(
1254
- this._crypto.cache.cloud_cert + this._crypto.cache.tunnel_ca_pem
1255
- );
1256
- }
1257
-
1258
- log$1("sending %d x509 credentials", bindRequest.x509_credential.length);
1259
- log$1("bind TTL is ", this._config.bindRequestTTL);
1260
-
1261
- // This will block while the request is pending.
1262
- const pollInterval = 10000;
1263
- let decision = "";
1264
- do {
1265
- if (decision) {
1266
- // Wait a while before retrying.
1267
- // eslint-disable-next-line no-await-in-loop
1268
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
1269
- }
1270
- // eslint-disable-next-line no-await-in-loop
1271
- decision = await issueBind.call(this, bindRequest, this._options.bindRequestTTL);
1272
- log$1("binding decision: %s", decision);
1273
- } while (decision === "POLICY_DECISION_PROMPT" || decision === "POLICY_DECISION_PENDING");
1274
-
1275
- return decision === "POLICY_DECISION_PERMIT";
1276
- } catch (err) {
1277
- log$1("failure binding to Volt [%s]", err.message);
1278
- throw err;
1279
- }
1304
+ try {
1305
+ // Check if we need to resolve a Relay volt.
1306
+ if (
1307
+ typeof this._voltConfig?.relay === "string" ||
1308
+ this._voltConfig?.relay?.http_address
1309
+ ) {
1310
+ const relayURL =
1311
+ this._voltConfig.relay?.http_address || this._voltConfig.relay;
1312
+ log$1("attempting to retrieve Relay information from %s", relayURL);
1313
+ this._voltConfig.relay = await fetchVoltConfig.call(
1314
+ this,
1315
+ `${relayURL}/discovery`,
1316
+ );
1317
+ if (this._voltConfig.relay.ca_pem) {
1318
+ log$1(
1319
+ "Auto-fetched Relay CA %s, remote address %s",
1320
+ this._voltConfig.relay.ca_pem,
1321
+ this._voltConfig.relay.address,
1322
+ );
1323
+ } else {
1324
+ throw new Error("Unable to fetch Relay CA - cannot securely connect.");
1325
+ }
1326
+ }
1327
+
1328
+ if (!this._credential.cache.ca) {
1329
+ this._credential.cache.ca = this._voltConfig.ca_pem;
1330
+ }
1331
+
1332
+ if (!this._credential.cache.ca) {
1333
+ throw new Error(
1334
+ "No certificate authority found in configuration for target Volt - check configuration",
1335
+ );
1336
+ }
1337
+
1338
+ const keyPair = this._credential.getKey();
1339
+ const publicKeyPem = pki.publicKeyToPem(keyPair.publicKey);
1340
+
1341
+ if (!this._credential.cache.bindIp) {
1342
+ // Default the IP address if none is specified. This is used to set the SAN in the
1343
+ // certificate issued by the Volt.
1344
+ this._credential.cache.bindIp = ip__default["default"].address();
1345
+ }
1346
+
1347
+ this._credential.saveCache();
1348
+
1349
+ // Form the request message.
1350
+ const bindRequest = {
1351
+ binding_name: this._config.client_name,
1352
+ public_key: publicKeyPem,
1353
+ host: this._credential.cache.bindIp,
1354
+ x509_credential: [],
1355
+ };
1356
+
1357
+ if (this._credential.cache.cert) {
1358
+ bindRequest.x509_credential = [
1359
+ this._credential.cache.cert + this._credential.cache.ca,
1360
+ ];
1361
+ }
1362
+
1363
+ if (this._voltConfig.challenge_code) {
1364
+ bindRequest.challenge = signBase64(
1365
+ keyPair.privateKey,
1366
+ this._voltConfig.challenge_code,
1367
+ );
1368
+ } else {
1369
+ log$1(
1370
+ "****no Volt challenge code available**** => not sending challenge signature",
1371
+ );
1372
+ }
1373
+
1374
+ // For remote connections, add our cloud-issued certificate as an additional credential.
1375
+ if (this._config?.relay?.ca_pem && this._credential.cache.cloud_cert) {
1376
+ bindRequest.x509_credential = bindRequest.x509_credential.concat(
1377
+ this._credential.cache.cloud_cert + this._config.relay.ca_pem,
1378
+ );
1379
+ }
1380
+
1381
+ log$1("sending %d x509 credentials", bindRequest.x509_credential.length);
1382
+ log$1("bind TTL is ", this._config.bindRequestTTL);
1383
+
1384
+ // This will block while the request is pending.
1385
+ const pollInterval = 10000;
1386
+ let decision = "";
1387
+ do {
1388
+ if (decision) {
1389
+ // Wait a while before retrying.
1390
+ // eslint-disable-next-line no-await-in-loop
1391
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
1392
+ }
1393
+ // eslint-disable-next-line no-await-in-loop
1394
+ decision = await issueBind.call(
1395
+ this,
1396
+ bindRequest,
1397
+ this._voltConfig.bindRequestTTL,
1398
+ );
1399
+ log$1("binding decision: %s", decision);
1400
+ } while (
1401
+ decision === "POLICY_DECISION_PROMPT" ||
1402
+ decision === "POLICY_DECISION_PENDING"
1403
+ );
1404
+
1405
+ return decision === "POLICY_DECISION_PERMIT";
1406
+ } catch (err) {
1407
+ log$1("failure binding to Volt [%s]", err.message);
1408
+ throw err;
1409
+ }
1280
1410
  }
1281
1411
 
1282
1412
  function connectInternal() {
1283
- try {
1284
- if (this._voltConnection) {
1285
- log$1("connectInternal - Volt connection already exists");
1286
- return Promise.resolve();
1287
- }
1288
-
1289
- const onDisconnected = () => {
1290
- this._connected = false;
1291
- this._session = null;
1292
-
1293
- if (this._cachedClient) {
1294
- this._grpc.closeClient(this._cachedClient);
1295
- this._cachedClient = null;
1296
- }
1297
-
1298
- if (this._cachedRemoteClient) {
1299
- this._grpc.closeClient(this._cachedRemoteClient);
1300
- this._cachedRemoteClient = null;
1301
- }
1302
- };
1303
-
1304
- this._voltConnection = new VoltConnection(this, this._grpc, this._options);
1305
-
1306
- this._voltConnection.on("connected", (session) => {
1307
- this._session = session;
1308
- this._connected = !!session;
1309
- if (!this._connected) {
1310
- onDisconnected();
1311
- }
1312
- this.emit("connected", !!session);
1313
- });
1314
-
1315
- this._voltConnection.on("error", (err) => {
1316
- // Should auto-reconnect.
1317
- log$1("Volt connection error [%s]", err.message);
1318
- if (this._connected) {
1319
- onDisconnected();
1320
- this.emit("connected", false);
1321
- }
1322
- });
1323
-
1324
- this._voltConnection.on("evt", (evt) => {
1325
- this.emit("evt", evt);
1326
- });
1327
-
1328
- return this._voltConnection.connect();
1329
- } catch (err) {
1330
- log$1("connect - error [%s]", err.message);
1331
- throw err;
1332
- }
1413
+ try {
1414
+ if (this._voltConnection) {
1415
+ log$1("connectInternal - Volt connection already exists");
1416
+ return Promise.resolve();
1417
+ }
1418
+
1419
+ const onDisconnected = () => {
1420
+ this._connected = false;
1421
+ this._session = null;
1422
+
1423
+ if (this._cachedClient) {
1424
+ this._grpc.closeClient(this._cachedClient);
1425
+ this._cachedClient = null;
1426
+ }
1427
+
1428
+ if (this._cachedRemoteClient) {
1429
+ this._grpc.closeClient(this._cachedRemoteClient);
1430
+ this._cachedRemoteClient = null;
1431
+ }
1432
+ };
1433
+
1434
+ this._voltConnection = new VoltConnection(this, this._grpc);
1435
+
1436
+ this._voltConnection.on("connected", (session) => {
1437
+ this._session = session;
1438
+ this._connected = !!session;
1439
+ if (!this._connected) {
1440
+ onDisconnected();
1441
+ }
1442
+ this.emit("connected", !!session);
1443
+ });
1444
+
1445
+ this._voltConnection.on("error", (err) => {
1446
+ // Should auto-reconnect.
1447
+ log$1("Volt connection error [%s]", err.message);
1448
+ if (this._connected) {
1449
+ onDisconnected();
1450
+ this.emit("connected", false);
1451
+ }
1452
+ });
1453
+
1454
+ this._voltConnection.on("evt", (evt) => {
1455
+ this.emit("evt", evt);
1456
+ });
1457
+
1458
+ return this._voltConnection.connect();
1459
+ } catch (err) {
1460
+ log$1("connect - error [%s]", err.message);
1461
+ throw err;
1462
+ }
1333
1463
  }
1334
1464
 
1335
1465
  function getVoltAPIClientInternal() {
1336
- if (!this._cachedClient) {
1337
- const serviceAddress = this.isRemote ? this._crypto.cache.tunnel_address : this._options.local_address;
1338
- log$1("creating cached VoltAPI service client on %s", serviceAddress);
1339
- let serviceDescriptors = {};
1340
- voltServices.forEach((pkg) => {
1341
- const packageDescriptors = getServiceDescriptors(this._grpc, pkg);
1342
- serviceDescriptors = {...serviceDescriptors, ...packageDescriptors};
1343
- });
1344
-
1345
- this._cachedClient = createClient(
1346
- this._grpc,
1347
- serviceDescriptors,
1348
- serviceAddress,
1349
- this._crypto.cache,
1350
- this.isRemote && !this.isVoltTunnel,
1351
- this._config.cloud_host ? this._options.id : "",
1352
- this._config.cloud_host ? this._options.id : ""
1353
- );
1354
- }
1355
-
1356
- return this._cachedClient;
1466
+ if (!this._cachedClient) {
1467
+ const serviceAddress = this.isRemote
1468
+ ? this._config.relay.address
1469
+ : this._voltConfig.address;
1470
+ log$1("creating cached VoltAPI service client on %s", serviceAddress);
1471
+ let serviceDescriptors = {};
1472
+ voltServices.forEach((pkg) => {
1473
+ const packageDescriptors = getServiceDescriptors(this._grpc, pkg);
1474
+ serviceDescriptors = { ...serviceDescriptors, ...packageDescriptors };
1475
+ });
1476
+
1477
+ this._cachedClient = createClient(
1478
+ this._grpc,
1479
+ serviceDescriptors,
1480
+ serviceAddress,
1481
+ this._credential,
1482
+ this.isRemote && !this.isVoltRelay,
1483
+ this._config?.relay?.cloud ? this._voltConfig.id : "",
1484
+ this._config?.relay?.cloud ? this._voltConfig.id : "",
1485
+ );
1486
+ }
1487
+
1488
+ return this._cachedClient;
1357
1489
  }
1358
1490
 
1359
1491
  function unaryCall(method, request) {
1360
- const grpcClient = this.getVoltAPIClient();
1492
+ return new Promise((resolve, reject) => {
1493
+ const grpcClient = this.getVoltAPIClient();
1494
+
1495
+ const call = new GRPCCall(this, method, "METHOD_TYPE_UNARY");
1496
+
1497
+ let response = null;
1498
+
1499
+ call.on("data", (payload) => {
1500
+ // Cache the response and wait for `end`.
1501
+ response = payload;
1502
+ });
1503
+
1504
+ call.on("error", reject);
1505
+
1506
+ call.on("end", () => {
1507
+ if (!response) {
1508
+ return reject(new Error("no response received"));
1509
+ }
1510
+
1511
+ // Convert non-OK status to a JS error.
1512
+ if (response.status?.message) {
1513
+ reject(new Error(response.status.message));
1514
+ } else {
1515
+ resolve(response);
1516
+ }
1517
+ });
1518
+
1519
+ call.start(grpcClient, request);
1520
+ });
1521
+ }
1361
1522
 
1362
- const call = new GRPCCall(this, method, "METHOD_TYPE_UNARY");
1363
- call.start(grpcClient, request);
1364
- return call.wait();
1523
+ async function fetchVoltConfig(discovery_url) {
1524
+ try {
1525
+ const getJSON = bent__default["default"]("json");
1526
+ const fullVoltConfig = await getJSON(discovery_url);
1527
+
1528
+ if (!fullVoltConfig || typeof fullVoltConfig !== "object") {
1529
+ throw new Error(`invalid config resolved from: ${discovery_url}`);
1530
+ }
1531
+
1532
+ const voltConfig = pick(
1533
+ fullVoltConfig,
1534
+ "id",
1535
+ "display_name",
1536
+ "public_key",
1537
+ "fingerprint",
1538
+ "address",
1539
+ "ca_pem",
1540
+ "challenge_code",
1541
+ "cloud",
1542
+ "relay",
1543
+ );
1544
+
1545
+ return voltConfig;
1546
+ } catch (err) {
1547
+ throw new Error(
1548
+ `Failure loading config from ${discovery_url}: ${err.message}`,
1549
+ );
1550
+ }
1365
1551
  }
1366
1552
 
1367
- async function fetchVoltConfig(volt_did) {
1368
- const didResolution = getDIDResolutionURL(volt_did);
1369
- if (!didResolution) {
1370
- throw new Error(`Invalid Volt DID: ${volt_did}`);
1371
- }
1372
-
1373
- const getJSON = bent__default["default"]("json");
1374
- const didDocument = await getJSON(didResolution);
1375
- const voltConfigServices = findDIDDocumentService(didDocument, constants.didServiceType.voltConfig);
1376
- if (voltConfigServices.length !== 1) {
1377
- log$1(
1378
- "Unexpected number of Volt configuration endpoints found in DID document for %s, services found: %d",
1379
- volt_did,
1380
- voltConfigServices.length
1381
- );
1382
- }
1383
- const serviceEndpoint = voltConfigServices[0].serviceEndpoint;
1384
- const resolvedConfig = await getJSON(serviceEndpoint);
1385
-
1386
- const voltConfig = pick(
1387
- resolvedConfig,
1388
- "id",
1389
- "display_name",
1390
- "public_key",
1391
- "fingerprint",
1392
- "local_address",
1393
- "ca_pem",
1394
- "challenge_code"
1395
- );
1396
-
1397
- return {
1398
- volt: voltConfig,
1399
- tunnel_ca_pem: resolvedConfig.tunnel_ca_pem,
1400
- tunnel_address: resolvedConfig.tunnel_address,
1401
- cloud_host: resolvedConfig.tunnel_address.split(":")[0],
1402
- };
1553
+ async function fetchVoltConfigFromDID(volt_did) {
1554
+ try {
1555
+ const didResolution = getDIDResolutionURL(volt_did);
1556
+ if (!didResolution) {
1557
+ throw new Error(`Invalid Volt DID: ${volt_did}`);
1558
+ }
1559
+
1560
+ const getJSON = bent__default["default"]("json");
1561
+ const didDocument = await getJSON(didResolution);
1562
+ const voltConfigServices = findDIDDocumentService(
1563
+ didDocument,
1564
+ constants.didServiceType.voltConfig,
1565
+ );
1566
+ if (voltConfigServices.length !== 1) {
1567
+ log$1(
1568
+ "Unexpected number of Volt configuration endpoints found in DID document for %s, services found: %d",
1569
+ volt_did,
1570
+ voltConfigServices.length,
1571
+ );
1572
+ }
1573
+
1574
+ const serviceEndpoint = voltConfigServices[0].serviceEndpoint;
1575
+ return await fetchVoltConfig.call(this, serviceEndpoint);
1576
+ } catch (err) {
1577
+ throw new Error(
1578
+ `Failure fetching Volt config from DID document ${volt_did}: ${err.message}`,
1579
+ );
1580
+ }
1403
1581
  }
1404
1582
 
1405
- const {readFile} = fs__default["default"].promises;
1583
+ const { readFile } = fs__default["default"].promises;
1406
1584
  const log = debug__default["default"]("volt-client-grpc:volt-client");
1407
1585
 
1408
1586
  class VoltClient extends EventEmitter__default["default"] {
1409
- /**
1410
- * @param {object} grpc - an instance of the grpc module (see https://www.npmjs.com/package/grpc)
1411
- */
1412
- constructor(grpc) {
1413
- super();
1414
-
1415
- if (!grpc) {
1416
- throw new Error("invalid arguments, grpc is required");
1417
- }
1418
- this._grpc = grpc;
1419
- this._cachedClient = null;
1420
- this._cachedRemoteClient = null;
1421
- this._session = null;
1422
- this._config = null;
1423
- this._options = null;
1424
- this._voltConnection = null;
1425
- }
1426
-
1427
- get config() {
1428
- return this._config;
1429
- }
1430
-
1431
- get crypto() {
1432
- return this._crypto;
1433
- }
1434
-
1435
- get grpc() {
1436
- return this._grpc;
1437
- }
1438
-
1439
- get options() {
1440
- return this._options;
1441
- }
1442
-
1443
- /**
1444
- * Initialises a binding and connection to the volt.
1445
- * @param {string} [config] - the location of the Volt configuration file, or a configuration object
1446
- */
1447
- async initialise(config, extras = {}) {
1448
- try {
1449
- if (!config) {
1450
- throw new Error("configPath argument is required to be a non-empty string");
1451
- }
1452
-
1453
- let configPath;
1454
- let configJSON;
1455
- if (typeof config === "string") {
1456
- configPath = path__default["default"].resolve(config);
1457
- log("Attempt to load config from file %s", configPath);
1458
- try {
1459
- const configContents = await readFile(new URL(configPath, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href))));
1460
- configJSON = JSON.parse(configContents);
1461
- } catch (err) {
1462
- log("failure loading config file %s [%s]", configPath, err.message);
1463
- throw new Error(`failed to load configuration - check JSON format in ${configPath}`);
1464
- }
1465
- } else if (typeof config === "object") {
1466
- configJSON = config;
1467
- } else {
1468
- throw new Error("config must be either a file path or a config object");
1469
- }
1470
-
1471
- if (!configJSON || typeof configJSON !== "object") {
1472
- throw new Error("config argument is required to be an object");
1473
- }
1474
-
1475
- if (!configJSON.client_name || typeof configJSON.client_name !== "string") {
1476
- throw new Error("client_name property required in config");
1477
- }
1478
-
1479
- this._config = {...configJSON, ...extras};
1480
-
1481
- if (this._config.volt_did && !this._config.volt) {
1482
- // No Volt configuration, attempt to discover it via the given DID.
1483
- const didConfig = await fetchVoltConfig.call(this, this._config.volt_did);
1484
- log("resolved config from DID: %s", JSON.stringify(didConfig, null, 2));
1485
- this._config = {...this._config, ...didConfig};
1486
- }
1487
-
1488
- this._options = this._config.volt;
1489
-
1490
- if (!this._options || typeof this._options !== "object") {
1491
- throw new Error("configuration is missing the 'volt' object");
1492
- }
1493
-
1494
- if (!this._options.id || typeof this._options.id !== "string") {
1495
- throw new Error("'id' property is missing in Volt configuration");
1496
- }
1497
-
1498
- this._crypto = new VoltCrypto(this._config, configPath);
1499
-
1500
- await this._crypto.initialise();
1501
-
1502
- if (!this.isRemote) {
1503
- // If we're not connecting via a tunnel, we must have the address and CA.
1504
- if (!this._options.local_address || typeof this._options.local_address !== "string") {
1505
- throw new Error("'local_address' property missing in Volt configuration");
1506
- }
1507
-
1508
- if (!this._options.ca_pem || typeof this._options.ca_pem !== "string") {
1509
- throw new Error("'ca_pPem' property missing in Volt configuration");
1510
- }
1511
- }
1512
-
1513
- let isBound;
1514
- if (!this._crypto._cryptoCache.cert) {
1515
- // No certificate present in the cache yet => we need to bind.
1516
- try {
1517
- isBound = await bindInternal.call(this);
1518
- } catch (bindErr) {
1519
- if (bindErr.message === "invalid arguments") {
1520
- // This is usually the result of a missing challenge signature or credential.
1521
- log("failure binding to Volt - did you supply a challenge code or verified credential?");
1522
- throw bindErr;
1523
- }
1524
- }
1525
- } else {
1526
- isBound = true;
1527
- }
1528
-
1529
- if (!isBound) {
1530
- // This is usually because of request being denied.
1531
- throw new Error("Volt binding failed");
1532
- }
1533
-
1534
- return Promise.resolve();
1535
- } catch (err) {
1536
- log("Failure starting Volt client [%s]", err.message);
1537
- throw err;
1538
- }
1539
- }
1540
-
1541
- initialiseAndConnect(configPath, extras = {}) {
1542
- return this.initialise(configPath, extras)
1543
- .then(() => {
1544
- return connectInternal.call(this);
1545
- })
1546
- .catch((err) => {
1547
- log("startAndConnect failure: %s", err.message);
1548
- return Promise.reject(err);
1549
- });
1550
- }
1551
-
1552
- /**
1553
- * Creates a GRPC client for the given Volt service description.
1554
- *
1555
- * Automatically handles remote connections.
1556
- *
1557
- * n.b. for this javascript client Protobuf definitions should conform to the recommended
1558
- * structure, which is that a package proto file resides in a folder path that matches the
1559
- * package name, and services contained in the package are named in in Pascal Case and using
1560
- * the suffix 'API'. For example the WebcamControlAPI in package tdx.volt_api.webcam.v1 should reside
1561
- * in a protobuf file at tdx/api/webcam/v1/webcam_control_api.proto
1562
- *
1563
- * @param {object} service a service description.
1564
- * @param {object} descriptors the service descriptors, must be specified unless the service
1565
- * packages are well-known Volt APIs.
1566
- */
1567
- createServiceClient(service, descriptors) {
1568
- const pkg = service.service_description.service_api;
1569
-
1570
- let serviceDescriptors;
1571
- if (!descriptors) {
1572
- serviceDescriptors = {};
1573
- pkg.forEach((svc) => {
1574
- log("adding service %s to service client", svc);
1575
- const packageDescriptors = getServiceDescriptors(this._grpc, svc);
1576
- serviceDescriptors = {...serviceDescriptors, ...packageDescriptors};
1577
- });
1578
- } else {
1579
- serviceDescriptors = descriptors;
1580
- }
1581
-
1582
- if (this.isRemote) {
1583
- if (!this._crypto.cache.tunnel_address) {
1584
- throw new Error("Remote connection enabled but no tunnel address - have you called start()?");
1585
- }
1586
-
1587
- // In remote mode => create a client using the discovered tunnel address **and** passing the service reourceId
1588
- return createClient(
1589
- this._grpc,
1590
- serviceDescriptors,
1591
- this._crypto.cache.tunnel_address,
1592
- this._crypto.cache,
1593
- false,
1594
- service.volt_id,
1595
- service.id
1596
- );
1597
- } else {
1598
- return createClient(
1599
- this._grpc,
1600
- serviceDescriptors,
1601
- service.service_description.local_address,
1602
- this._crypto.cache
1603
- );
1604
- }
1605
- }
1606
-
1607
- get isRemote() {
1608
- return (this._config.cloud_host || this._config.tunnel_host) && this._options.id;
1609
- }
1610
-
1611
- get isVoltTunnel() {
1612
- return this.isRemote && this._config.tunnel_host;
1613
- }
1614
-
1615
- connect() {
1616
- return connectInternal.call(this);
1617
- }
1618
-
1619
- disconnect() {
1620
- if (this._voltConnection) {
1621
- this._voltConnection.disconnect();
1622
- this._voltConnection = null;
1623
- }
1624
- }
1625
-
1626
- getVoltAPIClient() {
1627
- return getVoltAPIClientInternal.call(this);
1628
- }
1629
-
1630
- /**
1631
- * Request resource access.
1632
- * @param {*} targetResourceId
1633
- * @param {*} accessType - see vault.proto for enum values.
1634
- */
1635
- async RequestAccessBlocking(targetResourceId, accessType = "VOLT_ACCESS_READ") {
1636
- try {
1637
- const accessRequest = {
1638
- access: accessType,
1639
- resource_id: targetResourceId,
1640
- };
1641
-
1642
- // This will block while the request is pending.
1643
- // TODO - implement streamed rpc on volt? Not sure there is a need really...
1644
- const pollInterval = 10000;
1645
- let decision = "";
1646
- do {
1647
- if (decision) {
1648
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
1649
- }
1650
- const accessResponse = await this.RequestAccess(accessRequest);
1651
- decision = accessResponse.decision;
1652
- log("access decision: %s", decision);
1653
- } while (decision === "POLICY_DECISION_PROMPT" || decision === "POLICY_DECISION_PENDING");
1654
-
1655
- log("requestResourceAccess result is %j", decision);
1656
- return decision === "POLICY_DECISION_PERMIT";
1657
- } catch (err) {
1658
- log("failure requesting resource access [%s]", err.message);
1659
- return Promise.reject(err);
1660
- }
1661
- }
1662
-
1663
- /**
1664
- * VoltAPI - resource management
1665
- */
1666
-
1667
- CanAccessResource(request) {
1668
- return unaryCall.call(this, "CanAccessResource", request);
1669
- }
1670
-
1671
- DeleteResource(request) {
1672
- return unaryCall.call(this, "DeleteResource", request);
1673
- }
1674
-
1675
- DiscoverServices(request) {
1676
- return unaryCall.call(this, "DiscoverServices", request);
1677
- }
1678
-
1679
- GetResource(request) {
1680
- return unaryCall.call(this, "GetResource", request);
1681
- }
1682
-
1683
- GetResources(request) {
1684
- return unaryCall.call(this, "GetResources", request);
1685
- }
1686
-
1687
- GetResourceAncestors(request) {
1688
- return unaryCall.call(this, "GetResourceAncestors", request);
1689
- }
1690
-
1691
- GetResourceDescendants(request) {
1692
- return unaryCall.call(this, "GetResourceDescendants", request);
1693
- }
1694
-
1695
- RequestAccess(request) {
1696
- return unaryCall.call(this, "RequestAccess", request);
1697
- }
1698
-
1699
- SaveResource(request) {
1700
- return unaryCall.call(this, "SaveResource", request);
1701
- }
1702
-
1703
- SaveResourceAttribute(request) {
1704
- return unaryCall.call(this, "SaveResourceAttribute", request);
1705
- }
1706
-
1707
- SetServiceStatus(request) {
1708
- return unaryCall.call(this, "SetServiceStatus", request);
1709
- }
1710
-
1711
- /**
1712
- * VoltAPI - volt management
1713
- */
1714
-
1715
- Bind(request) {
1716
- return unaryCall.call(this, "Bind", request);
1717
- }
1718
-
1719
- DeleteAccess(request) {
1720
- return unaryCall.call(this, "DeleteAccess", request);
1721
- }
1722
-
1723
- DeleteVolt(request) {
1724
- return unaryCall.call(this, "DeleteVolt", request);
1725
- }
1726
-
1727
- GetAccess(request) {
1728
- return unaryCall.call(this, "GetAccess", request);
1729
- }
1730
-
1731
- GetBindings(request) {
1732
- return unaryCall.call(this, "GetBindings", request);
1733
- }
1734
-
1735
- GetIdentities(request) {
1736
- return unaryCall.call(this, "GetIdentities", request);
1737
- }
1738
-
1739
- GetIdentity(request) {
1740
- return unaryCall.call(this, "GetIdentity", request);
1741
- }
1742
-
1743
- GetIdentityToken(request) {
1744
- return unaryCall.call(this, "GetIdentityToken", request);
1745
- }
1746
-
1747
- GetPolicy(request) {
1748
- return unaryCall.call(this, "GetPolicy", request);
1749
- }
1750
-
1751
- GetSettings(request) {
1752
- return unaryCall.call(this, "GetSettings", request);
1753
- }
1754
-
1755
- SaveAccess(request) {
1756
- return unaryCall.call(this, "SaveAccess", request);
1757
- }
1758
-
1759
- SaveCloudConnection(request) {
1760
- return unaryCall.call(this, "SaveCloudConnection", request);
1761
- }
1762
-
1763
- SaveIdentity(request) {
1764
- return unaryCall.call(this, "SaveIdentity", request);
1765
- }
1766
-
1767
- SaveSettings(request) {
1768
- return unaryCall.call(this, "SaveSettings", request);
1769
- }
1770
-
1771
- SetAccessRequestDecision(request) {
1772
- return unaryCall.call(this, "SetAccessRequestDecision", request);
1773
- }
1774
-
1775
- SetBindingDecision(request) {
1776
- return unaryCall.call(this, "SetBindingDecision", request);
1777
- }
1778
-
1779
- Shutdown(request) {
1780
- return unaryCall.call(this, "Shutdown", request);
1781
- }
1782
-
1783
- SignVerify(request) {
1784
- return unaryCall.call(this, "SignVerify", request);
1785
- }
1786
-
1787
- /**
1788
- * FileAPI
1789
- */
1790
- GetFileDescendants(request) {
1791
- return unaryCall.call(this, "GetFileDescendants", request);
1792
- }
1793
-
1794
- /**
1795
- * Asynchronous file download
1796
- * @param {*} request
1797
- * @returns stream
1798
- */
1799
- DownloadFile(request) {
1800
- const grpcClient = this.getVoltAPIClient();
1801
-
1802
- return new Promise((resolve, reject) => {
1803
- const meta = this._crypto.getIdentityMetadata(this._grpc, this._options.id, this.isRemote);
1804
- resolve(grpcClient.DownloadFile(request, meta.metadata));
1805
- }).catch((err) => {
1806
- log("error during %s [%s]", method, err.message);
1807
- return Promise.reject(err);
1808
- });
1809
- }
1810
-
1811
- UploadFile(request, callback) {
1812
- const grpcClient = this.getVoltAPIClient();
1813
-
1814
- const uploadCall = new GRPCCall(this, "UploadFile", "METHOD_TYPE_BIDI");
1815
- return uploadCall.start(grpcClient, request, callback);
1816
- }
1817
-
1818
- /**
1819
- * Synchronous file download
1820
- * @param {*} request
1821
- * @returns file buffer, base64 encoded
1822
- */
1823
- DownloadFileSync(request) {
1824
- const grpcClient = this.getVoltAPIClient();
1825
-
1826
- const blocks = [];
1827
-
1828
- const call = new GRPCCall(this, "DownloadFile", "METHOD_TYPE_SERVER_STREAM");
1829
- call.start(grpcClient, request, (err, response) => {
1830
- if (err) {
1831
- return call.reject(err);
1832
- }
1833
-
1834
- switch (response.payload) {
1835
- case "block":
1836
- blocks.push(response.block);
1837
- break;
1838
- case "status":
1839
- if (response.status.message) {
1840
- return call.reject(new Error(response.status.message));
1841
- }
1842
- break;
1843
- default:
1844
- log("unrecognised response payload %s", response.payload);
1845
- break;
1846
- }
1847
- });
1848
-
1849
- return call
1850
- .wait()
1851
- .then(() => {
1852
- log("Download finished");
1853
- return {buffer: Buffer.concat(blocks).toString("base64")};
1854
- })
1855
- .catch((err) => {
1856
- log("error during DownloadFile [%s]", err.message);
1857
- return Promise.reject(err);
1858
- });
1859
- }
1860
-
1861
- /**
1862
- * SqliteDatabaseAPI
1863
- */
1864
- SqlExecute(request, callback) {
1865
- const grpcClient = this.getVoltAPIClient();
1866
-
1867
- const subscribeCall = new GRPCCall(this, "Execute", "METHOD_TYPE_BIDI");
1868
- return subscribeCall.start(grpcClient, request, callback);
1869
- }
1870
-
1871
- /**
1872
- * WireAPI
1873
- */
1874
- PublishWire(request, callback) {
1875
- const grpcClient = this.getVoltAPIClient();
1876
-
1877
- const publishCall = new GRPCCall(this, "PublishWire", "METHOD_TYPE_CLIENT_STREAM");
1878
- return publishCall.start(grpcClient, request, callback);
1879
- }
1880
-
1881
- SubscribeWire(request, callback) {
1882
- const grpcClient = this.getVoltAPIClient();
1883
-
1884
- const subscribeCall = new GRPCCall(this, "SubscribeWire", "METHOD_TYPE_BIDI");
1885
- return subscribeCall.start(grpcClient, request, callback);
1886
- }
1587
+ /**
1588
+ * @param {object} grpc - an instance of the grpc module (see https://www.npmjs.com/package/grpc)
1589
+ */
1590
+ constructor(grpc) {
1591
+ super();
1592
+
1593
+ if (!grpc) {
1594
+ throw new Error("invalid arguments, grpc is required");
1595
+ }
1596
+ this._grpc = grpc;
1597
+ this._cachedClient = null;
1598
+ this._cachedRemoteClient = null;
1599
+ this._session = null;
1600
+ this._config = null;
1601
+ this._voltConfig = null;
1602
+ this._voltConnection = null;
1603
+ }
1604
+
1605
+ get config() {
1606
+ return this._config;
1607
+ }
1608
+
1609
+ get credential() {
1610
+ return this._credential;
1611
+ }
1612
+
1613
+ get grpc() {
1614
+ return this._grpc;
1615
+ }
1616
+
1617
+ get voltConfig() {
1618
+ return this._voltConfig;
1619
+ }
1620
+
1621
+ /**
1622
+ * Initialises a binding and connection to the volt.
1623
+ * @param {string} [config] - the location of the Volt configuration file, or a configuration object
1624
+ */
1625
+ async initialise(config, extras = {}) {
1626
+ try {
1627
+ if (!config) {
1628
+ throw new Error(
1629
+ "configPath argument is required to be a non-empty string",
1630
+ );
1631
+ }
1632
+
1633
+ let configPath;
1634
+ let configJSON;
1635
+ if (typeof config === "string") {
1636
+ configPath = path__default["default"].resolve(config);
1637
+ log("Attempt to load config from file %s", configPath);
1638
+ try {
1639
+ const configContents = await readFile(
1640
+ new URL(configPath, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href))),
1641
+ );
1642
+ configJSON = JSON.parse(configContents);
1643
+ } catch (err) {
1644
+ log("failure loading config file %s [%s]", configPath, err.message);
1645
+ throw new Error(
1646
+ `failed to load configuration - check JSON format in ${configPath}`,
1647
+ );
1648
+ }
1649
+ } else if (typeof config === "object") {
1650
+ configJSON = config;
1651
+ } else {
1652
+ throw new Error("config must be either a file path or a config object");
1653
+ }
1654
+
1655
+ if (!configJSON || typeof configJSON !== "object") {
1656
+ throw new Error("config argument is required to be an object");
1657
+ }
1658
+
1659
+ if (
1660
+ !configJSON.client_name ||
1661
+ typeof configJSON.client_name !== "string"
1662
+ ) {
1663
+ throw new Error("client_name property required in config");
1664
+ }
1665
+
1666
+ this._config = { ...configJSON, ...extras };
1667
+
1668
+ let voltDID = "";
1669
+ let voltHttpAddress = "";
1670
+ if (typeof this._config.volt === "string") {
1671
+ if (this._config.volt.indexOf("did:") === 0) {
1672
+ voltDID = this._config.volt;
1673
+ } else {
1674
+ voltHttpAddress = this._config.volt;
1675
+ }
1676
+ } else if (typeof this._config.volt !== "object") {
1677
+ throw new Error("configuration is missing the 'volt' object");
1678
+ } else {
1679
+ voltDID = this._config.volt.did;
1680
+ voltHttpAddress = this._config.volt.http_address;
1681
+ }
1682
+
1683
+ if (voltDID) {
1684
+ const didConfig = await fetchVoltConfigFromDID.call(this, voltDID);
1685
+ this._config = { ...this._config, volt: didConfig };
1686
+ log("resolved config from DID: %s", JSON.stringify(didConfig, null, 2));
1687
+ } else if (voltHttpAddress) {
1688
+ const discoConfig = await fetchVoltConfig.call(
1689
+ this,
1690
+ `${voltHttpAddress}/discovery`,
1691
+ );
1692
+ this._config = {
1693
+ ...this._config,
1694
+ volt: { ...this._config.volt, ...discoConfig },
1695
+ };
1696
+ }
1697
+
1698
+ this._voltConfig = this._config.volt;
1699
+ this._voltConfig.did = voltDID;
1700
+ this._voltConfig.http_address = voltHttpAddress;
1701
+
1702
+ if (!this._voltConfig.id || typeof this._voltConfig.id !== "string") {
1703
+ throw new Error("'id' property is missing in Volt configuration");
1704
+ }
1705
+
1706
+ this._credential = new VoltCredential(this._config, configPath);
1707
+
1708
+ await this._credential.initialise();
1709
+
1710
+ if (!this.isRemote) {
1711
+ // If we're not connecting via a Relay, we must have the address and CA.
1712
+ if (
1713
+ !this._voltConfig.address ||
1714
+ typeof this._voltConfig.address !== "string"
1715
+ ) {
1716
+ throw new Error("'address' property missing in Volt configuration");
1717
+ }
1718
+
1719
+ if (
1720
+ !this._voltConfig.ca_pem ||
1721
+ typeof this._voltConfig.ca_pem !== "string"
1722
+ ) {
1723
+ throw new Error("'ca_pPem' property missing in Volt configuration");
1724
+ }
1725
+ }
1726
+
1727
+ let isBound;
1728
+ if (this._credential._cryptoCache.cert) {
1729
+ isBound = true;
1730
+ } else {
1731
+ // No certificate present in the cache yet => we need to bind.
1732
+ try {
1733
+ isBound = await bindInternal.call(this);
1734
+ } catch (bindErr) {
1735
+ if (bindErr.message === "invalid arguments") {
1736
+ // This is usually the result of a missing challenge signature or credential.
1737
+ log(
1738
+ "failure binding to Volt - did you supply a challenge code or verified credential?",
1739
+ );
1740
+ throw bindErr;
1741
+ }
1742
+ }
1743
+ }
1744
+
1745
+ if (!isBound) {
1746
+ // This is usually because of request being denied.
1747
+ throw new Error("Volt binding failed");
1748
+ }
1749
+
1750
+ return Promise.resolve();
1751
+ } catch (err) {
1752
+ log("Failure starting Volt client [%s]", err.message);
1753
+ throw err;
1754
+ }
1755
+ }
1756
+
1757
+ initialiseAndConnect(configPath, extras = {}) {
1758
+ return this.initialise(configPath, extras)
1759
+ .then(() => {
1760
+ return connectInternal.call(this);
1761
+ })
1762
+ .catch((err) => {
1763
+ log("initialiseAndConnect failure: %s", err.message);
1764
+ return Promise.reject(err);
1765
+ });
1766
+ }
1767
+
1768
+ /**
1769
+ * Creates a GRPC client for the given Volt service description.
1770
+ *
1771
+ * Automatically handles remote connections.
1772
+ *
1773
+ * n.b. for this javascript client Protobuf definitions should conform to the recommended
1774
+ * structure, which is that a package proto file resides in a folder path that matches the
1775
+ * package name, and services contained in the package are named in in Pascal Case and using
1776
+ * the suffix 'API'. For example the WebcamControlAPI in package tdx.volt_api.webcam.v1 should reside
1777
+ * in a protobuf file at tdx/api/webcam/v1/webcam_control_api.proto
1778
+ *
1779
+ * @param {object} service a service description.
1780
+ * @param {object} descriptors the service descriptors, must be specified unless the service
1781
+ * packages are well-known Volt APIs.
1782
+ */
1783
+ createServiceClient(service, descriptors) {
1784
+ const pkg = service.service_description.service_api;
1785
+
1786
+ let serviceDescriptors;
1787
+ if (descriptors) {
1788
+ serviceDescriptors = descriptors;
1789
+ } else {
1790
+ serviceDescriptors = {};
1791
+ pkg.forEach((svc) => {
1792
+ log("adding service %s to service client", svc);
1793
+ const packageDescriptors = getServiceDescriptors(this._grpc, svc);
1794
+ serviceDescriptors = { ...serviceDescriptors, ...packageDescriptors };
1795
+ });
1796
+ }
1797
+
1798
+ if (this.isRemote) {
1799
+ if (!this._config?.relay?.address) {
1800
+ throw new Error(
1801
+ "Remote connection enabled but no Relay address - have you called start()?",
1802
+ );
1803
+ }
1804
+
1805
+ // In remote mode => create a client using the discovered Relay address **and** passing the service reourceId
1806
+ return createClient(
1807
+ this._grpc,
1808
+ serviceDescriptors,
1809
+ this._config.relay.address,
1810
+ this._credential,
1811
+ false,
1812
+ service.volt_id,
1813
+ service.id,
1814
+ );
1815
+ } else {
1816
+ return createClient(
1817
+ this._grpc,
1818
+ serviceDescriptors,
1819
+ service.service_description.address,
1820
+ this._credential,
1821
+ );
1822
+ }
1823
+ }
1824
+
1825
+ get isRemote() {
1826
+ return !!(this._config?.relay && this._voltConfig.id);
1827
+ }
1828
+
1829
+ get isVoltRelay() {
1830
+ return this.isRemote && !this._config?.relay.cloud;
1831
+ }
1832
+
1833
+ connect() {
1834
+ return connectInternal.call(this);
1835
+ }
1836
+
1837
+ disconnect() {
1838
+ if (this._voltConnection) {
1839
+ this._voltConnection.disconnect();
1840
+ this._voltConnection = null;
1841
+ }
1842
+ }
1843
+
1844
+ getVoltAPIClient() {
1845
+ return getVoltAPIClientInternal.call(this);
1846
+ }
1847
+
1848
+ /**
1849
+ * Request resource access.
1850
+ * @param {*} targetResourceId
1851
+ * @param {*} accessType - see volt.proto for values.
1852
+ */
1853
+ async RequestAccessBlocking(
1854
+ targetResourceId,
1855
+ accessType = "VOLT_ACCESS_READ",
1856
+ ) {
1857
+ try {
1858
+ const accessRequest = {
1859
+ access: accessType,
1860
+ resource_id: targetResourceId,
1861
+ };
1862
+
1863
+ // This will block while the request is pending.
1864
+ // TODO - implement streamed rpc on volt? Not sure there is a need really...
1865
+ const pollInterval = 10000;
1866
+ let decision = "";
1867
+ do {
1868
+ if (decision) {
1869
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
1870
+ }
1871
+ const accessResponse = await this.RequestAccess(accessRequest);
1872
+ decision = accessResponse.decision;
1873
+ log("access decision: %s", decision);
1874
+ } while (
1875
+ decision === "POLICY_DECISION_PROMPT" ||
1876
+ decision === "POLICY_DECISION_PENDING"
1877
+ );
1878
+
1879
+ log("requestResourceAccess result is %j", decision);
1880
+ return decision === "POLICY_DECISION_PERMIT";
1881
+ } catch (err) {
1882
+ log("failure requesting resource access [%s]", err.message);
1883
+ return Promise.reject(err);
1884
+ }
1885
+ }
1886
+
1887
+ /**
1888
+ * VoltAPI - resource management
1889
+ */
1890
+
1891
+ CanAccessResource(request) {
1892
+ return unaryCall.call(this, "CanAccessResource", request);
1893
+ }
1894
+
1895
+ DeleteResource(request) {
1896
+ return unaryCall.call(this, "DeleteResource", request);
1897
+ }
1898
+
1899
+ DiscoverServices(request) {
1900
+ return unaryCall.call(this, "DiscoverServices", request);
1901
+ }
1902
+
1903
+ GetResource(request) {
1904
+ return unaryCall.call(this, "GetResource", request);
1905
+ }
1906
+
1907
+ GetResources(request) {
1908
+ return unaryCall.call(this, "GetResources", request);
1909
+ }
1910
+
1911
+ GetResourceAncestors(request) {
1912
+ return unaryCall.call(this, "GetResourceAncestors", request);
1913
+ }
1914
+
1915
+ GetResourceDescendants(request) {
1916
+ return unaryCall.call(this, "GetResourceDescendants", request);
1917
+ }
1918
+
1919
+ RequestAccess(request) {
1920
+ return unaryCall.call(this, "RequestAccess", request);
1921
+ }
1922
+
1923
+ SaveResource(request) {
1924
+ return unaryCall.call(this, "SaveResource", request);
1925
+ }
1926
+
1927
+ SaveResourceAttribute(request) {
1928
+ return unaryCall.call(this, "SaveResourceAttribute", request);
1929
+ }
1930
+
1931
+ SetServiceStatus(request) {
1932
+ return unaryCall.call(this, "SetServiceStatus", request);
1933
+ }
1934
+
1935
+ /**
1936
+ * VoltAPI - volt management
1937
+ */
1938
+
1939
+ Bind(request) {
1940
+ return unaryCall.call(this, "Bind", request);
1941
+ }
1942
+
1943
+ DeleteAccess(request) {
1944
+ return unaryCall.call(this, "DeleteAccess", request);
1945
+ }
1946
+
1947
+ DeleteVolt(request) {
1948
+ return unaryCall.call(this, "DeleteVolt", request);
1949
+ }
1950
+
1951
+ GetAccess(request) {
1952
+ return unaryCall.call(this, "GetAccess", request);
1953
+ }
1954
+
1955
+ GetBindings(request) {
1956
+ return unaryCall.call(this, "GetBindings", request);
1957
+ }
1958
+
1959
+ GetIdentities(request) {
1960
+ return unaryCall.call(this, "GetIdentities", request);
1961
+ }
1962
+
1963
+ GetIdentity(request) {
1964
+ return unaryCall.call(this, "GetIdentity", request);
1965
+ }
1966
+
1967
+ GetIdentityToken(request) {
1968
+ return unaryCall.call(this, "GetIdentityToken", request);
1969
+ }
1970
+
1971
+ GetPolicy(request) {
1972
+ return unaryCall.call(this, "GetPolicy", request);
1973
+ }
1974
+
1975
+ GetSettings(request) {
1976
+ return unaryCall.call(this, "GetSettings", request);
1977
+ }
1978
+
1979
+ SaveAccess(request) {
1980
+ return unaryCall.call(this, "SaveAccess", request);
1981
+ }
1982
+
1983
+ SaveCloudConnection(request) {
1984
+ return unaryCall.call(this, "SaveCloudConnection", request);
1985
+ }
1986
+
1987
+ SaveIdentity(request) {
1988
+ return unaryCall.call(this, "SaveIdentity", request);
1989
+ }
1990
+
1991
+ SaveSettings(request) {
1992
+ return unaryCall.call(this, "SaveSettings", request);
1993
+ }
1994
+
1995
+ SetAccessRequestDecision(request) {
1996
+ return unaryCall.call(this, "SetAccessRequestDecision", request);
1997
+ }
1998
+
1999
+ SetBindingDecision(request) {
2000
+ return unaryCall.call(this, "SetBindingDecision", request);
2001
+ }
2002
+
2003
+ Shutdown(request) {
2004
+ return unaryCall.call(this, "Shutdown", request);
2005
+ }
2006
+
2007
+ SignVerify(request) {
2008
+ return unaryCall.call(this, "SignVerify", request);
2009
+ }
2010
+
2011
+ /**
2012
+ * FileAPI
2013
+ */
2014
+ GetFileDescendants(request) {
2015
+ return unaryCall.call(this, "GetFileDescendants", request);
2016
+ }
2017
+
2018
+ /**
2019
+ * Asynchronous file download
2020
+ * @param {*} request
2021
+ * @returns stream
2022
+ */
2023
+ DownloadFile(request) {
2024
+ const grpcClient = this.getVoltAPIClient();
2025
+
2026
+ const downloadCall = new GRPCCall(
2027
+ this,
2028
+ "DownloadFile",
2029
+ "METHOD_TYPE_SERVER_STREAM",
2030
+ );
2031
+ return downloadCall.start(grpcClient, request);
2032
+ }
2033
+
2034
+ UploadFile(request) {
2035
+ const grpcClient = this.getVoltAPIClient();
2036
+
2037
+ const uploadCall = new GRPCCall(this, "UploadFile", "METHOD_TYPE_BIDI");
2038
+ return uploadCall.start(grpcClient, request);
2039
+ }
2040
+
2041
+ /**
2042
+ * Synchronous file download
2043
+ * @param {*} request
2044
+ * @returns file buffer, base64 encoded
2045
+ */
2046
+ DownloadFileSync(request) {
2047
+ return new Promise((resolve, reject) => {
2048
+ const grpcClient = this.getVoltAPIClient();
2049
+
2050
+ const blocks = [];
2051
+
2052
+ const call = new GRPCCall(
2053
+ this,
2054
+ "DownloadFile",
2055
+ "METHOD_TYPE_SERVER_STREAM",
2056
+ );
2057
+
2058
+ call.on("data", (response) => {
2059
+ switch (response.payload) {
2060
+ case "block": {
2061
+ blocks.push(response.block);
2062
+ break;
2063
+ }
2064
+ case "status": {
2065
+ if (response.status.message) {
2066
+ return call.reject(new Error(response.status.message));
2067
+ }
2068
+ break;
2069
+ }
2070
+ default:
2071
+ log("unrecognised response payload %s", response.payload);
2072
+ break;
2073
+ }
2074
+ });
2075
+
2076
+ call.on("error", (err) => {
2077
+ log("error during DownloadFile [%s]", err.message);
2078
+ reject(err);
2079
+ });
2080
+
2081
+ call.on("end", () => {
2082
+ log("Download finished");
2083
+ resolve({ buffer: Buffer.concat(blocks).toString("base64") });
2084
+ });
2085
+
2086
+ call.start(grpcClient, request);
2087
+ });
2088
+ }
2089
+
2090
+ /**
2091
+ * SqliteDatabaseAPI
2092
+ */
2093
+ SqlExecute(request) {
2094
+ const grpcClient = this.getVoltAPIClient();
2095
+
2096
+ const subscribeCall = new GRPCCall(this, "Execute", "METHOD_TYPE_BIDI");
2097
+ return subscribeCall.start(grpcClient, request);
2098
+ }
2099
+
2100
+ /**
2101
+ * WireAPI
2102
+ */
2103
+ PublishWire(request) {
2104
+ const grpcClient = this.getVoltAPIClient();
2105
+
2106
+ const publishCall = new GRPCCall(this, "PublishWire", "METHOD_TYPE_BIDI");
2107
+ return publishCall.start(grpcClient, request);
2108
+ }
2109
+
2110
+ SubscribeWire(request) {
2111
+ const grpcClient = this.getVoltAPIClient();
2112
+
2113
+ const subscribeCall = new GRPCCall(
2114
+ this,
2115
+ "SubscribeWire",
2116
+ "METHOD_TYPE_BIDI",
2117
+ );
2118
+ return subscribeCall.start(grpcClient, request);
2119
+ }
1887
2120
  }
1888
2121
 
1889
2122
  Object.defineProperty(exports, 'generateId', {
1890
- enumerable: true,
1891
- get: function () { return uuid.v4; }
2123
+ enumerable: true,
2124
+ get: function () { return uuid.v4; }
1892
2125
  });
1893
2126
  exports.VoltClient = VoltClient;
1894
- exports.VoltCrypto = VoltCrypto;
2127
+ exports.VoltCredential = VoltCredential;
1895
2128
  exports.constants = constants;
1896
2129
  exports.grpcUtils = grpcUtils;
1897
2130
  exports.protoUtils = protoUtils;