@twin.org/node-core 0.0.1-next.10

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.
Files changed (43) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +21 -0
  3. package/dist/cjs/index.cjs +1718 -0
  4. package/dist/esm/index.mjs +1681 -0
  5. package/dist/types/bootstrap.d.ts +59 -0
  6. package/dist/types/builders/engineEnvBuilder.d.ts +8 -0
  7. package/dist/types/builders/engineServerEnvBuilder.d.ts +13 -0
  8. package/dist/types/index.d.ts +10 -0
  9. package/dist/types/models/IEngineEnvironmentVariables.d.ts +389 -0
  10. package/dist/types/models/IEngineServerEnvironmentVariables.d.ts +45 -0
  11. package/dist/types/models/INodeEnvironmentVariables.d.ts +29 -0
  12. package/dist/types/models/INodeOptions.d.ts +69 -0
  13. package/dist/types/models/nodeFeatures.d.ts +17 -0
  14. package/dist/types/node.d.ts +26 -0
  15. package/dist/types/server.d.ts +17 -0
  16. package/dist/types/utils.d.ts +30 -0
  17. package/docs/changelog.md +76 -0
  18. package/docs/examples.md +1 -0
  19. package/docs/reference/functions/bootstrap.md +29 -0
  20. package/docs/reference/functions/bootstrapAttestationMethod.md +35 -0
  21. package/docs/reference/functions/bootstrapAuth.md +35 -0
  22. package/docs/reference/functions/bootstrapBlobEncryption.md +35 -0
  23. package/docs/reference/functions/bootstrapImmutableProofMethod.md +35 -0
  24. package/docs/reference/functions/bootstrapNodeIdentity.md +35 -0
  25. package/docs/reference/functions/bootstrapNodeUser.md +35 -0
  26. package/docs/reference/functions/buildConfiguration.md +30 -0
  27. package/docs/reference/functions/buildEngineConfiguration.md +19 -0
  28. package/docs/reference/functions/fileExists.md +19 -0
  29. package/docs/reference/functions/getExecutionDirectory.md +11 -0
  30. package/docs/reference/functions/getFeatures.md +19 -0
  31. package/docs/reference/functions/initialiseLocales.md +17 -0
  32. package/docs/reference/functions/loadJsonFile.md +25 -0
  33. package/docs/reference/functions/run.md +19 -0
  34. package/docs/reference/functions/start.md +31 -0
  35. package/docs/reference/index.md +35 -0
  36. package/docs/reference/interfaces/IEngineEnvironmentVariables.md +775 -0
  37. package/docs/reference/interfaces/IEngineServerEnvironmentVariables.md +87 -0
  38. package/docs/reference/interfaces/INodeEnvironmentVariables.md +1331 -0
  39. package/docs/reference/interfaces/INodeOptions.md +165 -0
  40. package/docs/reference/type-aliases/NodeFeatures.md +5 -0
  41. package/docs/reference/variables/NodeFeatures.md +19 -0
  42. package/locales/en.json +34 -0
  43. package/package.json +52 -0
@@ -0,0 +1,1718 @@
1
+ 'use strict';
2
+
3
+ var apiAuthEntityStorageService = require('@twin.org/api-auth-entity-storage-service');
4
+ var core = require('@twin.org/core');
5
+ var crypto = require('@twin.org/crypto');
6
+ var engineTypes = require('@twin.org/engine-types');
7
+ var entityStorageModels = require('@twin.org/entity-storage-models');
8
+ var identityModels = require('@twin.org/identity-models');
9
+ var vaultModels = require('@twin.org/vault-models');
10
+ var walletModels = require('@twin.org/wallet-models');
11
+ var promises = require('node:fs/promises');
12
+ var path = require('node:path');
13
+ var dotenv = require('dotenv');
14
+ var engineServer = require('@twin.org/engine-server');
15
+ var engineServerTypes = require('@twin.org/engine-server-types');
16
+ var engine = require('@twin.org/engine');
17
+ var engineCore = require('@twin.org/engine-core');
18
+ var engineModels = require('@twin.org/engine-models');
19
+
20
+ function _interopNamespaceDefault(e) {
21
+ var n = Object.create(null);
22
+ if (e) {
23
+ Object.keys(e).forEach(function (k) {
24
+ if (k !== 'default') {
25
+ var d = Object.getOwnPropertyDescriptor(e, k);
26
+ Object.defineProperty(n, k, d.get ? d : {
27
+ enumerable: true,
28
+ get: function () { return e[k]; }
29
+ });
30
+ }
31
+ });
32
+ }
33
+ n.default = e;
34
+ return Object.freeze(n);
35
+ }
36
+
37
+ var dotenv__namespace = /*#__PURE__*/_interopNamespaceDefault(dotenv);
38
+
39
+ // Copyright 2024 IOTA Stiftung.
40
+ // SPDX-License-Identifier: Apache-2.0.
41
+ /**
42
+ * The features that can be enabled on the node.
43
+ */
44
+ // eslint-disable-next-line @typescript-eslint/naming-convention
45
+ const NodeFeatures = {
46
+ /**
47
+ * NodeIdentity - generates an identity for the node if not provided in config.
48
+ */
49
+ NodeIdentity: "node-identity",
50
+ /**
51
+ * NodeUser - generates a user for the node if not provided in config.
52
+ */
53
+ NodeUser: "node-user"
54
+ };
55
+
56
+ // Copyright 2024 IOTA Stiftung.
57
+ // SPDX-License-Identifier: Apache-2.0.
58
+ /* eslint-disable no-console */
59
+ /**
60
+ * Initialise the locales for the application.
61
+ * @param localesDirectory The directory containing the locales.
62
+ */
63
+ async function initialiseLocales(localesDirectory) {
64
+ const localesFile = path.resolve(path.join(localesDirectory, "en.json"));
65
+ console.info("Locales File:", localesFile);
66
+ if (await fileExists(localesFile)) {
67
+ const enLangContent = await promises.readFile(localesFile, "utf8");
68
+ core.I18n.addDictionary("en", JSON.parse(enLangContent));
69
+ }
70
+ else {
71
+ console.warn(`Locales file not found: ${localesFile}`);
72
+ }
73
+ }
74
+ /**
75
+ * Get the directory where the application is being executed.
76
+ * @returns The execution directory.
77
+ */
78
+ function getExecutionDirectory() {
79
+ return process.cwd();
80
+ }
81
+ /**
82
+ * Does the specified file exist.
83
+ * @param filename The filename to check for existence.
84
+ * @returns True if the file exists.
85
+ */
86
+ async function fileExists(filename) {
87
+ try {
88
+ const stats = await promises.stat(filename);
89
+ return stats.isFile();
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ }
95
+ /**
96
+ * Load the JSON file.
97
+ * @param filename The filename of the JSON file to load.
98
+ * @returns The contents of the JSON file or null if it could not be loaded.
99
+ */
100
+ async function loadJsonFile(filename) {
101
+ const content = await promises.readFile(filename, "utf8");
102
+ return JSON.parse(content);
103
+ }
104
+ /**
105
+ * Get the features that are enabled on the node.
106
+ * @param env The environment variables for the node.
107
+ * @returns The features that are enabled on the node.
108
+ */
109
+ function getFeatures(env) {
110
+ if (core.Is.empty(env.features)) {
111
+ return [];
112
+ }
113
+ const features = [];
114
+ const allFeatures = Object.values(NodeFeatures);
115
+ const splitFeatures = env.features.split(",");
116
+ for (const feature of splitFeatures) {
117
+ const featureTrimmed = feature.trim();
118
+ if (allFeatures.includes(featureTrimmed)) {
119
+ features.push(featureTrimmed);
120
+ }
121
+ }
122
+ return features;
123
+ }
124
+
125
+ // Copyright 2024 IOTA Stiftung.
126
+ // SPDX-License-Identifier: Apache-2.0.
127
+ const DEFAULT_NODE_USERNAME = "admin@node";
128
+ /**
129
+ * Bootstrap the application.
130
+ * @param engineCore The engine core for the node.
131
+ * @param context The context for the node.
132
+ * @param envVars The environment variables for the node.
133
+ */
134
+ async function bootstrap(engineCore, context, envVars) {
135
+ const features = getFeatures(envVars);
136
+ await bootstrapNodeIdentity(engineCore, context, envVars, features);
137
+ await bootstrapNodeUser(engineCore, context, envVars, features);
138
+ await bootstrapAuth(engineCore, context, envVars);
139
+ await bootstrapBlobEncryption(engineCore, context, envVars);
140
+ await bootstrapAttestationMethod(engineCore, context, envVars);
141
+ await bootstrapImmutableProofMethod(engineCore, context, envVars);
142
+ }
143
+ /**
144
+ * Bootstrap the node creating any necessary resources.
145
+ * @param engineCore The engine core for the node.
146
+ * @param context The context for the node.
147
+ * @param envVars The environment variables for the node.
148
+ * @param features The features that are enabled on the node. The features that are enabled on the node.
149
+ */
150
+ async function bootstrapNodeIdentity(engineCore, context, envVars, features) {
151
+ if (features.includes(NodeFeatures.NodeIdentity)) {
152
+ // When we bootstrap the node we need to generate an identity for it,
153
+ // But we have a chicken and egg problem in that we can't create the identity
154
+ // to store the mnemonic in the vault without an identity. We use a temporary identity
155
+ // and then replace it with the new identity later in the process.
156
+ const engineDefaultTypes = engineCore.getDefaultTypes();
157
+ if (!core.Is.empty(engineDefaultTypes.vaultConnector)) {
158
+ const vaultConnector = vaultModels.VaultConnectorFactory.get(engineDefaultTypes.vaultConnector);
159
+ const workingIdentity = envVars.identity ??
160
+ context.state.nodeIdentity ??
161
+ `bootstrap-temp-${core.Converter.bytesToHex(core.RandomHelper.generate(16))}`;
162
+ await bootstrapMnemonic(engineCore, envVars, features, vaultConnector, workingIdentity);
163
+ const addresses = await bootstrapWallet(engineCore, envVars, features, workingIdentity);
164
+ const finalIdentity = await bootstrapIdentity(engineCore, envVars, features, workingIdentity);
165
+ await finaliseWallet(engineCore, envVars, features, finalIdentity, addresses);
166
+ await finaliseMnemonic(vaultConnector, workingIdentity, finalIdentity);
167
+ context.state.nodeIdentity = finalIdentity;
168
+ context.stateDirty = true;
169
+ engineCore.logInfo(core.I18n.formatMessage("node.nodeIdentity", {
170
+ identity: context.state.nodeIdentity
171
+ }));
172
+ }
173
+ }
174
+ }
175
+ /**
176
+ * Bootstrap the identity for the node.
177
+ * @param engineCore The engine core for the node.
178
+ * @param envVars The environment variables for the node.
179
+ * @param features The features that are enabled on the node. The features that are enabled on the node.
180
+ * @param nodeIdentity The identity of the node.
181
+ * @returns The addresses for the wallet.
182
+ */
183
+ async function bootstrapIdentity(engineCore, envVars, features, nodeIdentity) {
184
+ const engineDefaultTypes = engineCore.getDefaultTypes();
185
+ // Now create an identity for the node controlled by the address we just funded
186
+ const identityConnector = identityModels.IdentityConnectorFactory.get(engineDefaultTypes.identityConnector);
187
+ let identityDocument;
188
+ try {
189
+ const identityResolverConnector = identityModels.IdentityResolverConnectorFactory.get(engineDefaultTypes.identityResolverConnector);
190
+ identityDocument = await identityResolverConnector.resolveDocument(nodeIdentity);
191
+ engineCore.logInfo(core.I18n.formatMessage("node.existingNodeIdentity", { identity: nodeIdentity }));
192
+ }
193
+ catch { }
194
+ if (core.Is.empty(identityDocument)) {
195
+ engineCore.logInfo(core.I18n.formatMessage("node.generatingNodeIdentity"));
196
+ identityDocument = await identityConnector.createDocument(nodeIdentity);
197
+ engineCore.logInfo(core.I18n.formatMessage("node.createdNodeIdentity", { identity: identityDocument.id }));
198
+ }
199
+ if (engineDefaultTypes.identityConnector === engineTypes.IdentityConnectorType.Iota) {
200
+ const didUrn = core.Urn.fromValidString(identityDocument.id);
201
+ const didParts = didUrn.parts();
202
+ const objectId = didParts[3];
203
+ engineCore.logInfo(core.I18n.formatMessage("node.identityExplorer", {
204
+ url: `${envVars.iotaExplorerEndpoint}object/${objectId}?network=${envVars.iotaNetwork}`
205
+ }));
206
+ }
207
+ return identityDocument.id;
208
+ }
209
+ /**
210
+ * Bootstrap the wallet for the node.
211
+ * @param engineCore The engine core for the node.
212
+ * @param envVars The environment variables for the node.
213
+ * @param features The features that are enabled on the node.
214
+ * @param nodeIdentity The identity of the node.
215
+ * @returns The addresses for the wallet.
216
+ */
217
+ async function bootstrapWallet(engineCore, envVars, features, nodeIdentity) {
218
+ const engineDefaultTypes = engineCore.getDefaultTypes();
219
+ const walletConnector = walletModels.WalletConnectorFactory.get(engineDefaultTypes.walletConnector);
220
+ const addresses = await walletConnector.getAddresses(nodeIdentity, 0, 0, 5);
221
+ const balance = await walletConnector.getBalance(nodeIdentity, addresses[0]);
222
+ if (balance === 0n) {
223
+ let address0 = addresses[0];
224
+ if (engineDefaultTypes.walletConnector === engineTypes.WalletConnectorType.Iota) {
225
+ address0 = `${envVars.iotaExplorerEndpoint}address/${address0}?network=${envVars.iotaNetwork}`;
226
+ }
227
+ engineCore.logInfo(core.I18n.formatMessage("node.fundingWallet", { address: address0 }));
228
+ // Add some funds to the wallet from the faucet
229
+ await walletConnector.ensureBalance(nodeIdentity, addresses[0], 1000000000n);
230
+ }
231
+ else {
232
+ engineCore.logInfo(core.I18n.formatMessage("node.fundedWallet"));
233
+ }
234
+ return addresses;
235
+ }
236
+ /**
237
+ * Bootstrap the identity for the node.
238
+ * @param engineCore The engine core for the node.
239
+ * @param envVars The environment variables for the node.
240
+ * @param features The features that are enabled on the node.
241
+ * @param finalIdentity The identity of the node.
242
+ * @param addresses The addresses for the wallet.
243
+ */
244
+ async function finaliseWallet(engineCore, envVars, features, finalIdentity, addresses) {
245
+ const engineDefaultTypes = engineCore.getDefaultTypes();
246
+ // If we are using entity storage for wallet the identity associated with the
247
+ // address will be wrong, so fix it
248
+ if (engineDefaultTypes.walletConnector === "entity-storage") {
249
+ const walletAddress = entityStorageModels.EntityStorageConnectorFactory.get(core.StringHelper.kebabCase("WalletAddress"));
250
+ const addr = await walletAddress.get(addresses[0]);
251
+ if (!core.Is.empty(addr)) {
252
+ addr.identity = finalIdentity;
253
+ await walletAddress.set(addr);
254
+ }
255
+ }
256
+ }
257
+ /**
258
+ * Generate a mnemonic for the node identity.
259
+ * @param engineCore The engine core for the node.
260
+ * @param envVars The environment variables for the node.
261
+ * @param features The features that are enabled on the node.
262
+ * @param vaultConnector The vault connector to use.
263
+ * @param nodeIdentity The identity of the node.
264
+ */
265
+ async function bootstrapMnemonic(engineCore, envVars, features, vaultConnector, nodeIdentity) {
266
+ let mnemonic = envVars.mnemonic;
267
+ let storeMnemonic = false;
268
+ try {
269
+ const storedMnemonic = await vaultConnector.getSecret(`${nodeIdentity}/mnemonic`);
270
+ storeMnemonic = storedMnemonic !== mnemonic;
271
+ mnemonic = storedMnemonic;
272
+ }
273
+ catch {
274
+ storeMnemonic = true;
275
+ }
276
+ // If there is no mnemonic then we need to generate one
277
+ if (core.Is.empty(mnemonic)) {
278
+ mnemonic = crypto.Bip39.randomMnemonic();
279
+ storeMnemonic = true;
280
+ engineCore.logInfo(core.I18n.formatMessage("node.generatingMnemonic", { mnemonic }));
281
+ }
282
+ // If there is no mnemonic stored in the vault then we need to store it
283
+ if (storeMnemonic) {
284
+ engineCore.logInfo(core.I18n.formatMessage("node.storingMnemonic"));
285
+ await vaultConnector.setSecret(`${nodeIdentity}/mnemonic`, mnemonic);
286
+ }
287
+ else {
288
+ engineCore.logInfo(core.I18n.formatMessage("node.existingMnemonic"));
289
+ }
290
+ }
291
+ /**
292
+ * Finalise the mnemonic for the node identity.
293
+ * @param vaultConnector The vault connector to use.
294
+ * @param workingIdentity The identity of the node.
295
+ * @param finalIdentity The final identity for the node.
296
+ */
297
+ async function finaliseMnemonic(vaultConnector, workingIdentity, finalIdentity) {
298
+ // Now that we have an identity we can remove the temporary one
299
+ // and store the mnemonic with the new identity
300
+ if (workingIdentity.startsWith("bootstrap-temp-") && workingIdentity !== finalIdentity) {
301
+ const mnemonic = await vaultConnector.getSecret(`${workingIdentity}/mnemonic`);
302
+ await vaultConnector.setSecret(`${finalIdentity}/mnemonic`, mnemonic);
303
+ await vaultConnector.removeSecret(`${workingIdentity}/mnemonic`);
304
+ }
305
+ }
306
+ /**
307
+ * Bootstrap the user.
308
+ * @param engineCore The engine core for the node.
309
+ * @param context The context for the node.
310
+ * @param envVars The environment variables for the node.
311
+ * @param features The features that are enabled on the node.
312
+ */
313
+ async function bootstrapNodeUser(engineCore, context, envVars, features) {
314
+ if (features.includes(NodeFeatures.NodeUser)) {
315
+ const engineDefaultTypes = engineCore.getDefaultTypes();
316
+ if (engineDefaultTypes.authenticationComponent === "authentication-entity-storage" &&
317
+ core.Is.stringValue(context.state.nodeIdentity)) {
318
+ const authUserEntityStorage = entityStorageModels.EntityStorageConnectorFactory.get(core.StringHelper.kebabCase("AuthenticationUser"));
319
+ const email = envVars.username ?? DEFAULT_NODE_USERNAME;
320
+ let nodeAdminUser = await authUserEntityStorage.get(email);
321
+ if (core.Is.empty(nodeAdminUser)) {
322
+ engineCore.logInfo(core.I18n.formatMessage("node.creatingNodeUser", { email }));
323
+ const generatedPassword = envVars.password ?? crypto.PasswordGenerator.generate(16);
324
+ const passwordBytes = core.Converter.utf8ToBytes(generatedPassword);
325
+ const saltBytes = core.RandomHelper.generate(16);
326
+ const hashedPassword = await apiAuthEntityStorageService.PasswordHelper.hashPassword(passwordBytes, saltBytes);
327
+ nodeAdminUser = {
328
+ email,
329
+ password: hashedPassword,
330
+ salt: core.Converter.bytesToBase64(saltBytes),
331
+ identity: context.state.nodeIdentity
332
+ };
333
+ engineCore.logInfo(core.I18n.formatMessage("node.nodeAdminUserEmail", { email: nodeAdminUser.email }));
334
+ engineCore.logInfo(core.I18n.formatMessage("node.nodeAdminUserPassword", { password: generatedPassword }));
335
+ await authUserEntityStorage.set(nodeAdminUser);
336
+ }
337
+ else {
338
+ engineCore.logInfo(core.I18n.formatMessage("node.existingNodeUser", { email }));
339
+ // The user already exists, so double check the other details match
340
+ let needsUpdate = false;
341
+ if (nodeAdminUser.identity !== context.state.nodeIdentity) {
342
+ nodeAdminUser.identity = context.state.nodeIdentity;
343
+ needsUpdate = true;
344
+ }
345
+ if (core.Is.stringValue(envVars.password)) {
346
+ const passwordBytes = core.Converter.utf8ToBytes(envVars.password);
347
+ const saltBytes = core.Converter.base64ToBytes(nodeAdminUser.salt);
348
+ const hashedPassword = await apiAuthEntityStorageService.PasswordHelper.hashPassword(passwordBytes, saltBytes);
349
+ if (nodeAdminUser.password !== hashedPassword) {
350
+ nodeAdminUser.password = hashedPassword;
351
+ needsUpdate = true;
352
+ }
353
+ }
354
+ if (needsUpdate) {
355
+ await authUserEntityStorage.set(nodeAdminUser);
356
+ }
357
+ }
358
+ // We have create a node user, now we need to create a profile for the user
359
+ const identityProfileConnector = identityModels.IdentityProfileConnectorFactory.get(engineDefaultTypes.identityProfileConnector);
360
+ if (identityProfileConnector) {
361
+ let userProfile;
362
+ try {
363
+ userProfile = await identityProfileConnector.get(context.state.nodeIdentity);
364
+ }
365
+ catch { }
366
+ if (core.Is.empty(userProfile)) {
367
+ engineCore.logInfo(core.I18n.formatMessage("node.creatingUserProfile", { identity: context.state.nodeIdentity }));
368
+ const publicProfile = {
369
+ "@context": "https://schema.org",
370
+ "@type": "Person",
371
+ name: "Node Administrator"
372
+ };
373
+ const privateProfile = {
374
+ "@context": "https://schema.org",
375
+ "@type": "Person",
376
+ givenName: "Node",
377
+ familyName: "Administrator",
378
+ email
379
+ };
380
+ await identityProfileConnector.create(context.state.nodeIdentity, publicProfile, privateProfile);
381
+ }
382
+ else {
383
+ engineCore.logInfo(core.I18n.formatMessage("node.existingUserProfile", { identity: context.state.nodeIdentity }));
384
+ }
385
+ }
386
+ }
387
+ }
388
+ }
389
+ /**
390
+ * Bootstrap the attestation verification methods.
391
+ * @param engineCore The engine core for the node.
392
+ * @param context The context for the node.
393
+ * @param envVars The environment variables for the node.
394
+ * @param features The features that are enabled on the node.
395
+ */
396
+ async function bootstrapAttestationMethod(engineCore, context, envVars, features) {
397
+ if (core.Is.stringValue(context.state.nodeIdentity) &&
398
+ core.Is.arrayValue(context.config.types.identityConnector) &&
399
+ core.Is.stringValue(envVars.attestationVerificationMethodId)) {
400
+ const engineDefaultTypes = engineCore.getDefaultTypes();
401
+ const identityConnector = identityModels.IdentityConnectorFactory.get(engineDefaultTypes.identityConnector);
402
+ const identityResolverConnector = identityModels.IdentityResolverConnectorFactory.get(engineDefaultTypes.identityResolverConnector);
403
+ const identityDocument = await identityResolverConnector.resolveDocument(context.state.nodeIdentity);
404
+ const fullMethodId = `${identityDocument.id}#${envVars.attestationVerificationMethodId}`;
405
+ let createVm = true;
406
+ try {
407
+ identityModels.DocumentHelper.getVerificationMethod(identityDocument, fullMethodId, "assertionMethod");
408
+ createVm = false;
409
+ }
410
+ catch { }
411
+ if (createVm) {
412
+ // Add attestation verification method to DID, the correct node context is now in place
413
+ // so the keys for the verification method will be stored correctly
414
+ engineCore.logInfo(core.I18n.formatMessage("node.addingAttestation", {
415
+ methodId: fullMethodId
416
+ }));
417
+ await identityConnector.addVerificationMethod(context.state.nodeIdentity, context.state.nodeIdentity, "assertionMethod", envVars.attestationVerificationMethodId);
418
+ }
419
+ else {
420
+ engineCore.logInfo(core.I18n.formatMessage("node.existingAttestation", {
421
+ methodId: fullMethodId
422
+ }));
423
+ }
424
+ }
425
+ }
426
+ /**
427
+ * Bootstrap the immutable proof verification methods.
428
+ * @param engineCore The engine core for the node.
429
+ * @param context The context for the node.
430
+ * @param envVars The environment variables for the node.
431
+ * @param features The features that are enabled on the node.
432
+ */
433
+ async function bootstrapImmutableProofMethod(engineCore, context, envVars, features) {
434
+ const engineDefaultTypes = engineCore.getDefaultTypes();
435
+ if (core.Is.stringValue(context.state.nodeIdentity) &&
436
+ core.Is.arrayValue(context.config.types.identityConnector) &&
437
+ core.Is.stringValue(envVars.immutableProofVerificationMethodId)) {
438
+ const identityConnector = identityModels.IdentityConnectorFactory.get(engineDefaultTypes.identityConnector);
439
+ const identityResolverConnector = identityModels.IdentityResolverConnectorFactory.get(engineDefaultTypes.identityResolverConnector);
440
+ const identityDocument = await identityResolverConnector.resolveDocument(context.state.nodeIdentity);
441
+ const fullMethodId = `${identityDocument.id}#${envVars.immutableProofVerificationMethodId}`;
442
+ let createVm = true;
443
+ try {
444
+ identityModels.DocumentHelper.getVerificationMethod(identityDocument, fullMethodId, "assertionMethod");
445
+ createVm = false;
446
+ }
447
+ catch { }
448
+ if (createVm) {
449
+ // Add AIG verification method to DID, the correct node context is now in place
450
+ // so the keys for the verification method will be stored correctly
451
+ engineCore.logInfo(core.I18n.formatMessage("node.addingImmutableProof", {
452
+ methodId: fullMethodId
453
+ }));
454
+ await identityConnector.addVerificationMethod(context.state.nodeIdentity, context.state.nodeIdentity, "assertionMethod", envVars.immutableProofVerificationMethodId);
455
+ }
456
+ else {
457
+ engineCore.logInfo(core.I18n.formatMessage("node.existingImmutableProof", {
458
+ methodId: fullMethodId
459
+ }));
460
+ }
461
+ }
462
+ }
463
+ /**
464
+ * Bootstrap the keys for blob encryption.
465
+ * @param engineCore The engine core for the node.
466
+ * @param context The context for the node.
467
+ * @param envVars The environment variables for the node.
468
+ * @param features The features that are enabled on the node.
469
+ */
470
+ async function bootstrapBlobEncryption(engineCore, context, envVars, features) {
471
+ if ((core.Coerce.boolean(envVars.blobStorageEnableEncryption) ?? false) &&
472
+ core.Is.stringValue(context.state.nodeIdentity)) {
473
+ const engineDefaultTypes = engineCore.getDefaultTypes();
474
+ // Create a new key for encrypting blobs
475
+ const vaultConnector = vaultModels.VaultConnectorFactory.get(engineDefaultTypes.vaultConnector);
476
+ const keyName = `${context.state.nodeIdentity}/${envVars.blobStorageEncryptionKey}`;
477
+ let existingKey;
478
+ try {
479
+ existingKey = await vaultConnector.getKey(keyName);
480
+ }
481
+ catch { }
482
+ if (core.Is.empty(existingKey)) {
483
+ engineCore.logInfo(core.I18n.formatMessage("node.creatingBlobEncryptionKey", { keyName }));
484
+ await vaultConnector.createKey(keyName, vaultModels.VaultKeyType.ChaCha20Poly1305);
485
+ }
486
+ else {
487
+ engineCore.logInfo(core.I18n.formatMessage("node.existingBlobEncryptionKey", { keyName }));
488
+ }
489
+ }
490
+ }
491
+ /**
492
+ * Bootstrap the JWT signing key.
493
+ * @param engineCore The engine core for the node.
494
+ * @param context The context for the node.
495
+ * @param envVars The environment variables for the node.
496
+ * @param features The features that are enabled on the node.
497
+ */
498
+ async function bootstrapAuth(engineCore, context, envVars, features) {
499
+ const engineDefaultTypes = engineCore.getDefaultTypes();
500
+ if (engineDefaultTypes.authenticationComponent === "authentication-entity-storage" &&
501
+ core.Is.stringValue(context.state.nodeIdentity)) {
502
+ // Create a new JWT signing key and a user login for the node
503
+ const vaultConnector = vaultModels.VaultConnectorFactory.get(engineDefaultTypes.vaultConnector);
504
+ const keyName = `${context.state.nodeIdentity}/${envVars.authSigningKeyId}`;
505
+ let existingKey;
506
+ try {
507
+ existingKey = await vaultConnector.getKey(keyName);
508
+ }
509
+ catch { }
510
+ if (core.Is.empty(existingKey)) {
511
+ engineCore.logInfo(core.I18n.formatMessage("node.creatingAuthKey", { keyName }));
512
+ await vaultConnector.createKey(keyName, vaultModels.VaultKeyType.Ed25519);
513
+ }
514
+ else {
515
+ engineCore.logInfo(core.I18n.formatMessage("node.existingAuthKey", { keyName }));
516
+ }
517
+ }
518
+ }
519
+
520
+ // Copyright 2024 IOTA Stiftung.
521
+ // SPDX-License-Identifier: Apache-2.0.
522
+ /**
523
+ * Build the engine core configuration from environment variables.
524
+ * @param envVars The environment variables.
525
+ * @returns The config for the core.
526
+ */
527
+ function buildEngineConfiguration(envVars) {
528
+ if (core.Is.stringValue(envVars.storageFileRoot)) {
529
+ envVars.stateFilename ??= "engine-state.json";
530
+ envVars.storageFileRoot = path.resolve(envVars.storageFileRoot);
531
+ envVars.stateFilename = path.join(envVars.storageFileRoot, envVars.stateFilename);
532
+ }
533
+ envVars.attestationVerificationMethodId ??= "attestation-assertion";
534
+ envVars.immutableProofVerificationMethodId ??= "immutable-proof-assertion";
535
+ envVars.blobStorageEnableEncryption ??= "false";
536
+ envVars.blobStorageEncryptionKey ??= "blob-encryption";
537
+ const coreConfig = {
538
+ debug: core.Coerce.boolean(envVars.debug) ?? false,
539
+ types: {}
540
+ };
541
+ configureEntityStorage(coreConfig, envVars);
542
+ configureBlobStorage(coreConfig, envVars);
543
+ configureVault(coreConfig, envVars);
544
+ configureDlt(coreConfig, envVars);
545
+ configureLogging(coreConfig, envVars);
546
+ configureBackgroundTask(coreConfig, envVars);
547
+ configureEventBus(coreConfig, envVars);
548
+ configureTelemetry(coreConfig, envVars);
549
+ configureMessaging(coreConfig, envVars);
550
+ configureFaucet(coreConfig, envVars);
551
+ configureWallet(coreConfig, envVars);
552
+ configureNft(coreConfig, envVars);
553
+ configureVerifiableStorage(coreConfig, envVars);
554
+ configureIdentity(coreConfig, envVars);
555
+ configureIdentityResolver(coreConfig, envVars);
556
+ configureIdentityProfile(coreConfig, envVars);
557
+ configureAttestation(coreConfig, envVars);
558
+ configureDataProcessing(coreConfig, envVars);
559
+ configureAuditableItemGraph(coreConfig);
560
+ configureAuditableItemStream(coreConfig);
561
+ configureDocumentManagement(coreConfig);
562
+ configureFederatedCatalogue(coreConfig, envVars);
563
+ configureRightsManagement(coreConfig, envVars);
564
+ configureTaskScheduler(coreConfig, envVars);
565
+ return coreConfig;
566
+ }
567
+ /**
568
+ * Helper function to get IOTA configuration from centralized dltConfig.
569
+ * @param coreConfig The core config.
570
+ * @returns The IOTA configuration if found, undefined otherwise.
571
+ */
572
+ function getIotaConfig(coreConfig) {
573
+ const dltConfig = coreConfig.types.dltConfig?.find(config => config.type === engineTypes.DltConfigType.Iota && config.isDefault);
574
+ return dltConfig?.options?.config;
575
+ }
576
+ /**
577
+ * Configures the entity storage.
578
+ * @param coreConfig The core config.
579
+ * @param envVars The environment variables.
580
+ */
581
+ function configureEntityStorage(coreConfig, envVars) {
582
+ coreConfig.types ??= {};
583
+ coreConfig.types.entityStorageConnector ??= [];
584
+ if ((core.Coerce.boolean(envVars.entityMemoryEnable) ?? false) ||
585
+ envVars.entityStorageConnectorType === engineTypes.EntityStorageConnectorType.Memory) {
586
+ coreConfig.types.entityStorageConnector.push({
587
+ type: engineTypes.EntityStorageConnectorType.Memory
588
+ });
589
+ }
590
+ if ((core.Coerce.boolean(envVars.entityFileEnable) ?? false) ||
591
+ envVars.entityStorageConnectorType === engineTypes.EntityStorageConnectorType.File) {
592
+ coreConfig.types.entityStorageConnector.push({
593
+ type: engineTypes.EntityStorageConnectorType.File,
594
+ options: {
595
+ config: { directory: envVars.storageFileRoot ?? "" },
596
+ folderPrefix: envVars.entityStorageTablePrefix
597
+ }
598
+ });
599
+ }
600
+ if (core.Is.stringValue(envVars.awsDynamodbAccessKeyId)) {
601
+ coreConfig.types.entityStorageConnector.push({
602
+ type: engineTypes.EntityStorageConnectorType.AwsDynamoDb,
603
+ options: {
604
+ config: {
605
+ region: envVars.awsDynamodbRegion ?? "",
606
+ accessKeyId: envVars.awsDynamodbAccessKeyId ?? "",
607
+ secretAccessKey: envVars.awsDynamodbSecretAccessKey ?? "",
608
+ endpoint: envVars.awsDynamodbEndpoint ?? ""
609
+ },
610
+ tablePrefix: envVars.entityStorageTablePrefix
611
+ }
612
+ });
613
+ }
614
+ if (core.Is.stringValue(envVars.azureCosmosdbKey)) {
615
+ coreConfig.types.entityStorageConnector.push({
616
+ type: engineTypes.EntityStorageConnectorType.AzureCosmosDb,
617
+ options: {
618
+ config: {
619
+ endpoint: envVars.azureCosmosdbEndpoint ?? "",
620
+ key: envVars.azureCosmosdbKey ?? "",
621
+ databaseId: envVars.azureCosmosdbDatabaseId ?? "",
622
+ containerId: envVars.azureCosmosdbContainerId ?? ""
623
+ },
624
+ tablePrefix: envVars.entityStorageTablePrefix
625
+ }
626
+ });
627
+ }
628
+ if (core.Is.stringValue(envVars.gcpFirestoreCredentials)) {
629
+ coreConfig.types.entityStorageConnector.push({
630
+ type: engineTypes.EntityStorageConnectorType.GcpFirestoreDb,
631
+ options: {
632
+ config: {
633
+ projectId: envVars.gcpFirestoreProjectId ?? "",
634
+ credentials: envVars.gcpFirestoreCredentials ?? "",
635
+ databaseId: envVars.gcpFirestoreDatabaseId ?? "",
636
+ collectionName: envVars.gcpFirestoreCollectionName ?? "",
637
+ endpoint: envVars.gcpFirestoreApiEndpoint ?? ""
638
+ },
639
+ tablePrefix: envVars.entityStorageTablePrefix
640
+ }
641
+ });
642
+ }
643
+ if (core.Is.stringValue(envVars.scylladbHosts)) {
644
+ coreConfig.types.entityStorageConnector.push({
645
+ type: engineTypes.EntityStorageConnectorType.ScyllaDb,
646
+ options: {
647
+ config: {
648
+ hosts: envVars.scylladbHosts.split(",") ?? "",
649
+ localDataCenter: envVars.scylladbLocalDataCenter ?? "",
650
+ keyspace: envVars.scylladbKeyspace ?? ""
651
+ },
652
+ tablePrefix: envVars.entityStorageTablePrefix
653
+ }
654
+ });
655
+ }
656
+ if (core.Is.stringValue(envVars.mySqlHost)) {
657
+ coreConfig.types.entityStorageConnector.push({
658
+ type: engineTypes.EntityStorageConnectorType.MySqlDb,
659
+ options: {
660
+ config: {
661
+ host: envVars.mySqlHost,
662
+ port: envVars.mySqlPort ?? 3306,
663
+ user: envVars.mySqlUser ?? "",
664
+ password: envVars.mySqlPassword ?? "",
665
+ database: envVars.mySqlDatabase ?? ""
666
+ },
667
+ tablePrefix: envVars.entityStorageTablePrefix
668
+ }
669
+ });
670
+ }
671
+ if (core.Is.stringValue(envVars.mySqlHost)) {
672
+ coreConfig.types.entityStorageConnector.push({
673
+ type: engineTypes.EntityStorageConnectorType.MySqlDb,
674
+ options: {
675
+ config: {
676
+ host: envVars.mySqlHost,
677
+ port: envVars.mySqlPort ?? 3306,
678
+ user: envVars.mySqlUser ?? "",
679
+ password: envVars.mySqlPassword ?? "",
680
+ database: envVars.mySqlDatabase ?? ""
681
+ },
682
+ tablePrefix: envVars.entityStorageTablePrefix
683
+ }
684
+ });
685
+ }
686
+ if (core.Is.stringValue(envVars.mongoDbHost)) {
687
+ coreConfig.types.entityStorageConnector.push({
688
+ type: engineTypes.EntityStorageConnectorType.MongoDb,
689
+ options: {
690
+ config: {
691
+ host: envVars.mongoDbHost,
692
+ port: envVars.mongoDbPort,
693
+ user: envVars.mongoDbUser ?? "",
694
+ password: envVars.mongoDbPassword ?? "",
695
+ database: envVars.mongoDbDatabase ?? ""
696
+ },
697
+ tablePrefix: envVars.entityStorageTablePrefix
698
+ }
699
+ });
700
+ }
701
+ if (core.Is.stringValue(envVars.postgreSqlHost)) {
702
+ coreConfig.types.entityStorageConnector.push({
703
+ type: engineTypes.EntityStorageConnectorType.PostgreSql,
704
+ options: {
705
+ config: {
706
+ host: envVars.postgreSqlHost,
707
+ port: envVars.postgreSqlPort,
708
+ user: envVars.postgreSqlUser ?? "",
709
+ password: envVars.postgreSqlPassword ?? "",
710
+ database: envVars.postgreSqlDatabase ?? ""
711
+ },
712
+ tablePrefix: envVars.entityStorageTablePrefix
713
+ }
714
+ });
715
+ }
716
+ const defaultStorageConnector = envVars.entityStorageConnectorType;
717
+ if (core.Is.stringValue(defaultStorageConnector)) {
718
+ for (const config of coreConfig.types.entityStorageConnector) {
719
+ if (config.type === defaultStorageConnector) {
720
+ config.isDefault = true;
721
+ }
722
+ }
723
+ }
724
+ }
725
+ /**
726
+ * Configures the blob storage.
727
+ * @param coreConfig The core config.
728
+ * @param envVars The environment variables.
729
+ */
730
+ function configureBlobStorage(coreConfig, envVars) {
731
+ coreConfig.types.blobStorageConnector ??= [];
732
+ if ((core.Coerce.boolean(envVars.blobMemoryEnable) ?? false) ||
733
+ envVars.blobStorageConnectorType === engineTypes.BlobStorageConnectorType.Memory) {
734
+ coreConfig.types.blobStorageConnector.push({
735
+ type: engineTypes.BlobStorageConnectorType.Memory
736
+ });
737
+ }
738
+ if ((core.Coerce.boolean(envVars.blobFileEnable) ?? false) ||
739
+ envVars.blobStorageConnectorType === engineTypes.BlobStorageConnectorType.File) {
740
+ coreConfig.types.blobStorageConnector.push({
741
+ type: engineTypes.BlobStorageConnectorType.File,
742
+ options: {
743
+ config: {
744
+ directory: core.Is.stringValue(envVars.storageFileRoot)
745
+ ? path.join(envVars.storageFileRoot, "blob-storage")
746
+ : ""
747
+ },
748
+ storagePrefix: envVars.blobStoragePrefix
749
+ }
750
+ });
751
+ }
752
+ if (core.Is.stringValue(envVars.ipfsApiUrl)) {
753
+ coreConfig.types.blobStorageConnector.push({
754
+ type: engineTypes.BlobStorageConnectorType.Ipfs,
755
+ options: {
756
+ config: {
757
+ apiUrl: envVars.ipfsApiUrl,
758
+ bearerToken: envVars.ipfsBearerToken
759
+ }
760
+ }
761
+ });
762
+ }
763
+ if (core.Is.stringValue(envVars.awsS3AccessKeyId)) {
764
+ coreConfig.types.blobStorageConnector.push({
765
+ type: engineTypes.BlobStorageConnectorType.AwsS3,
766
+ options: {
767
+ config: {
768
+ region: envVars.awsS3Region ?? "",
769
+ bucketName: envVars.awsS3BucketName ?? "",
770
+ accessKeyId: envVars.awsS3AccessKeyId ?? "",
771
+ secretAccessKey: envVars.awsS3SecretAccessKey ?? "",
772
+ endpoint: envVars.awsS3Endpoint ?? ""
773
+ },
774
+ storagePrefix: envVars.blobStoragePrefix
775
+ }
776
+ });
777
+ }
778
+ if (core.Is.stringValue(envVars.azureStorageAccountKey)) {
779
+ coreConfig.types.blobStorageConnector.push({
780
+ type: engineTypes.BlobStorageConnectorType.AzureStorage,
781
+ options: {
782
+ config: {
783
+ accountName: envVars.azureStorageAccountName ?? "",
784
+ accountKey: envVars.azureStorageAccountKey ?? "",
785
+ containerName: envVars.azureStorageContainerName ?? "",
786
+ endpoint: envVars.azureStorageEndpoint ?? ""
787
+ },
788
+ storagePrefix: envVars.blobStoragePrefix
789
+ }
790
+ });
791
+ }
792
+ if (core.Is.stringValue(envVars.gcpStorageCredentials)) {
793
+ coreConfig.types.blobStorageConnector.push({
794
+ type: engineTypes.BlobStorageConnectorType.GcpStorage,
795
+ options: {
796
+ config: {
797
+ projectId: envVars.gcpStorageProjectId ?? "",
798
+ credentials: envVars.gcpStorageCredentials ?? "",
799
+ bucketName: envVars.gcpStorageBucketName ?? "",
800
+ apiEndpoint: envVars.gcpFirestoreApiEndpoint
801
+ },
802
+ storagePrefix: envVars.blobStoragePrefix
803
+ }
804
+ });
805
+ }
806
+ const defaultStorageConnectorType = envVars.blobStorageConnectorType;
807
+ if (core.Is.stringValue(defaultStorageConnectorType)) {
808
+ for (const config of coreConfig.types.blobStorageConnector) {
809
+ if (config.type === defaultStorageConnectorType) {
810
+ config.isDefault = true;
811
+ }
812
+ }
813
+ }
814
+ if (coreConfig.types.blobStorageConnector.length > 0) {
815
+ coreConfig.types.blobStorageComponent ??= [];
816
+ coreConfig.types.blobStorageComponent.push({
817
+ type: engineTypes.BlobStorageComponentType.Service,
818
+ options: {
819
+ config: {
820
+ vaultKeyId: (envVars.blobStorageEnableEncryption ?? false)
821
+ ? envVars.blobStorageEncryptionKey
822
+ : undefined
823
+ }
824
+ }
825
+ });
826
+ }
827
+ }
828
+ /**
829
+ * Configures the logging.
830
+ * @param coreConfig The core config.
831
+ * @param envVars The environment variables.
832
+ */
833
+ function configureLogging(coreConfig, envVars) {
834
+ coreConfig.types.loggingConnector ??= [];
835
+ const loggingConnectors = (envVars.loggingConnector ?? "").split(",");
836
+ for (const loggingConnector of loggingConnectors) {
837
+ if (loggingConnector === engineTypes.LoggingConnectorType.Console) {
838
+ coreConfig.types.loggingConnector?.push({
839
+ type: engineTypes.LoggingConnectorType.Console,
840
+ options: {
841
+ config: {
842
+ translateMessages: true,
843
+ hideGroups: true
844
+ }
845
+ },
846
+ isDefault: loggingConnectors.length === 1
847
+ });
848
+ }
849
+ else if (loggingConnector === engineTypes.LoggingConnectorType.EntityStorage) {
850
+ coreConfig.types.loggingConnector?.push({
851
+ type: engineTypes.LoggingConnectorType.EntityStorage,
852
+ isDefault: loggingConnectors.length === 1
853
+ });
854
+ }
855
+ }
856
+ if (loggingConnectors.length > 1) {
857
+ coreConfig.types.loggingConnector?.push({
858
+ type: engineTypes.LoggingConnectorType.Multi,
859
+ isDefault: true,
860
+ options: {
861
+ loggingConnectorTypes: loggingConnectors
862
+ }
863
+ });
864
+ }
865
+ if (loggingConnectors.length > 0) {
866
+ coreConfig.types.loggingComponent ??= [];
867
+ coreConfig.types.loggingComponent.push({ type: engineTypes.LoggingComponentType.Service });
868
+ }
869
+ }
870
+ /**
871
+ * Configures the vault.
872
+ * @param coreConfig The core config.
873
+ * @param envVars The environment variables.
874
+ */
875
+ function configureVault(coreConfig, envVars) {
876
+ coreConfig.types.vaultConnector ??= [];
877
+ if (envVars.vaultConnector === engineTypes.VaultConnectorType.EntityStorage) {
878
+ coreConfig.types.vaultConnector.push({
879
+ type: engineTypes.VaultConnectorType.EntityStorage
880
+ });
881
+ }
882
+ else if (envVars.vaultConnector === engineTypes.VaultConnectorType.Hashicorp) {
883
+ coreConfig.types.vaultConnector.push({
884
+ type: engineTypes.VaultConnectorType.Hashicorp,
885
+ options: {
886
+ config: {
887
+ endpoint: envVars.hashicorpVaultEndpoint ?? "",
888
+ token: envVars.hashicorpVaultToken ?? ""
889
+ }
890
+ }
891
+ });
892
+ }
893
+ }
894
+ /**
895
+ * Configures the background task.
896
+ * @param coreConfig The core config.
897
+ * @param envVars The environment variables.
898
+ */
899
+ function configureBackgroundTask(coreConfig, envVars) {
900
+ coreConfig.types.backgroundTaskConnector ??= [];
901
+ if (envVars.backgroundTaskConnector === engineTypes.BackgroundTaskConnectorType.EntityStorage) {
902
+ coreConfig.types.backgroundTaskConnector.push({
903
+ type: engineTypes.BackgroundTaskConnectorType.EntityStorage
904
+ });
905
+ }
906
+ }
907
+ /**
908
+ * Configures the event bud.
909
+ * @param coreConfig The core config.
910
+ * @param envVars The environment variables.
911
+ */
912
+ function configureEventBus(coreConfig, envVars) {
913
+ coreConfig.types.eventBusConnector ??= [];
914
+ if (envVars.eventBusConnector === engineTypes.EventBusConnectorType.Local) {
915
+ coreConfig.types.eventBusConnector.push({
916
+ type: engineTypes.EventBusConnectorType.Local
917
+ });
918
+ }
919
+ if (coreConfig.types.eventBusConnector.length > 0) {
920
+ coreConfig.types.eventBusComponent ??= [];
921
+ coreConfig.types.eventBusComponent.push({ type: engineTypes.EventBusComponentType.Service });
922
+ }
923
+ }
924
+ /**
925
+ * Configures the telemetry.
926
+ * @param coreConfig The core config.
927
+ * @param envVars The environment variables.
928
+ */
929
+ function configureTelemetry(coreConfig, envVars) {
930
+ coreConfig.types.telemetryConnector ??= [];
931
+ if (envVars.telemetryConnector === engineTypes.TelemetryConnectorType.EntityStorage) {
932
+ coreConfig.types.telemetryConnector.push({
933
+ type: engineTypes.TelemetryConnectorType.EntityStorage
934
+ });
935
+ }
936
+ if (coreConfig.types.telemetryConnector.length > 0) {
937
+ coreConfig.types.telemetryComponent ??= [];
938
+ coreConfig.types.telemetryComponent.push({ type: engineTypes.TelemetryComponentType.Service });
939
+ }
940
+ }
941
+ /**
942
+ * Configures the messaging.
943
+ * @param coreConfig The core config.
944
+ * @param envVars The environment variables.
945
+ */
946
+ function configureMessaging(coreConfig, envVars) {
947
+ coreConfig.types.messagingEmailConnector ??= [];
948
+ coreConfig.types.messagingSmsConnector ??= [];
949
+ coreConfig.types.messagingPushNotificationConnector ??= [];
950
+ if (envVars.messagingEmailConnector === engineTypes.MessagingEmailConnectorType.EntityStorage) {
951
+ coreConfig.types.messagingEmailConnector.push({
952
+ type: engineTypes.MessagingEmailConnectorType.EntityStorage
953
+ });
954
+ }
955
+ else if (envVars.messagingEmailConnector === engineTypes.MessagingEmailConnectorType.Aws) {
956
+ coreConfig.types.messagingEmailConnector.push({
957
+ type: engineTypes.MessagingEmailConnectorType.Aws,
958
+ options: {
959
+ config: {
960
+ region: envVars.awsS3Region ?? "",
961
+ accessKeyId: envVars.awsS3AccessKeyId ?? "",
962
+ secretAccessKey: envVars.awsS3SecretAccessKey ?? "",
963
+ endpoint: envVars.awsS3Endpoint ?? ""
964
+ }
965
+ }
966
+ });
967
+ }
968
+ if (envVars.messagingSmsConnector === engineTypes.MessagingSmsConnectorType.EntityStorage) {
969
+ coreConfig.types.messagingSmsConnector.push({
970
+ type: engineTypes.MessagingSmsConnectorType.EntityStorage
971
+ });
972
+ }
973
+ else if (envVars.messagingSmsConnector === engineTypes.MessagingSmsConnectorType.Aws) {
974
+ coreConfig.types.messagingSmsConnector.push({
975
+ type: engineTypes.MessagingSmsConnectorType.Aws,
976
+ options: {
977
+ config: {
978
+ region: envVars.awsS3Region ?? "",
979
+ accessKeyId: envVars.awsS3AccessKeyId ?? "",
980
+ secretAccessKey: envVars.awsS3SecretAccessKey ?? "",
981
+ endpoint: envVars.awsS3Endpoint ?? ""
982
+ }
983
+ }
984
+ });
985
+ }
986
+ if (envVars.messagingPushNotificationConnector ===
987
+ engineTypes.MessagingPushNotificationConnectorType.EntityStorage) {
988
+ coreConfig.types.messagingPushNotificationConnector.push({
989
+ type: engineTypes.MessagingPushNotificationConnectorType.EntityStorage
990
+ });
991
+ }
992
+ else if (envVars.messagingPushNotificationConnector === engineTypes.MessagingPushNotificationConnectorType.Aws) {
993
+ coreConfig.types.messagingPushNotificationConnector.push({
994
+ type: engineTypes.MessagingPushNotificationConnectorType.Aws,
995
+ options: {
996
+ config: {
997
+ region: envVars.awsS3Region ?? "",
998
+ accessKeyId: envVars.awsS3AccessKeyId ?? "",
999
+ secretAccessKey: envVars.awsS3SecretAccessKey ?? "",
1000
+ endpoint: envVars.awsS3Endpoint ?? "",
1001
+ applicationsSettings: core.Is.json(envVars.awsMessagingPushNotificationApplications)
1002
+ ? JSON.parse(envVars.awsMessagingPushNotificationApplications)
1003
+ : []
1004
+ }
1005
+ }
1006
+ });
1007
+ }
1008
+ if (coreConfig.types.messagingEmailConnector.length > 0 ||
1009
+ coreConfig.types.messagingSmsConnector.length > 0 ||
1010
+ coreConfig.types.messagingPushNotificationConnector.length > 0) {
1011
+ coreConfig.types.messagingComponent ??= [];
1012
+ coreConfig.types.messagingComponent.push({ type: engineTypes.MessagingComponentType.Service });
1013
+ }
1014
+ }
1015
+ /**
1016
+ * Configures the faucet.
1017
+ * @param coreConfig The core config.
1018
+ * @param envVars The environment variables.
1019
+ */
1020
+ function configureFaucet(coreConfig, envVars) {
1021
+ coreConfig.types.faucetConnector ??= [];
1022
+ if (envVars.faucetConnector === engineTypes.FaucetConnectorType.EntityStorage) {
1023
+ coreConfig.types.faucetConnector.push({
1024
+ type: engineTypes.FaucetConnectorType.EntityStorage
1025
+ });
1026
+ }
1027
+ else if (envVars.faucetConnector === engineTypes.FaucetConnectorType.Iota) {
1028
+ const iotaConfig = getIotaConfig(coreConfig);
1029
+ coreConfig.types.faucetConnector.push({
1030
+ type: engineTypes.FaucetConnectorType.Iota,
1031
+ options: {
1032
+ config: {
1033
+ endpoint: envVars.iotaFaucetEndpoint ?? "",
1034
+ clientOptions: iotaConfig?.clientOptions ?? { url: "" },
1035
+ network: iotaConfig?.network ?? ""
1036
+ }
1037
+ }
1038
+ });
1039
+ }
1040
+ }
1041
+ /**
1042
+ * Configures the wallet.
1043
+ * @param coreConfig The core config.
1044
+ * @param envVars The environment variables.
1045
+ */
1046
+ function configureWallet(coreConfig, envVars) {
1047
+ coreConfig.types.walletConnector ??= [];
1048
+ if (envVars.walletConnector === engineTypes.WalletConnectorType.EntityStorage) {
1049
+ coreConfig.types.walletConnector.push({
1050
+ type: engineTypes.WalletConnectorType.EntityStorage
1051
+ });
1052
+ }
1053
+ else if (envVars.walletConnector === engineTypes.WalletConnectorType.Iota) {
1054
+ const iotaConfig = getIotaConfig(coreConfig);
1055
+ coreConfig.types.walletConnector.push({
1056
+ type: engineTypes.WalletConnectorType.Iota,
1057
+ options: {
1058
+ config: iotaConfig ?? {}
1059
+ }
1060
+ });
1061
+ }
1062
+ }
1063
+ /**
1064
+ * Configures the NFT.
1065
+ * @param coreConfig The core config.
1066
+ * @param envVars The environment variables.
1067
+ */
1068
+ function configureNft(coreConfig, envVars) {
1069
+ coreConfig.types.nftConnector ??= [];
1070
+ if (envVars.nftConnector === engineTypes.NftConnectorType.EntityStorage) {
1071
+ coreConfig.types.nftConnector.push({
1072
+ type: engineTypes.NftConnectorType.EntityStorage
1073
+ });
1074
+ }
1075
+ else if (envVars.nftConnector === engineTypes.NftConnectorType.Iota) {
1076
+ const iotaConfig = getIotaConfig(coreConfig);
1077
+ coreConfig.types.nftConnector.push({
1078
+ type: engineTypes.NftConnectorType.Iota,
1079
+ options: {
1080
+ config: iotaConfig ?? {}
1081
+ }
1082
+ });
1083
+ }
1084
+ if (coreConfig.types.nftConnector.length > 0) {
1085
+ coreConfig.types.nftComponent ??= [];
1086
+ coreConfig.types.nftComponent.push({ type: engineTypes.NftComponentType.Service });
1087
+ }
1088
+ }
1089
+ /**
1090
+ * Configures the verifiable storage.
1091
+ * @param coreConfig The core config.
1092
+ * @param envVars The environment variables.
1093
+ */
1094
+ function configureVerifiableStorage(coreConfig, envVars) {
1095
+ coreConfig.types.verifiableStorageConnector ??= [];
1096
+ if (envVars.verifiableStorageConnector === engineTypes.VerifiableStorageConnectorType.EntityStorage) {
1097
+ coreConfig.types.verifiableStorageConnector.push({
1098
+ type: engineTypes.VerifiableStorageConnectorType.EntityStorage
1099
+ });
1100
+ }
1101
+ else if (envVars.verifiableStorageConnector === engineTypes.VerifiableStorageConnectorType.Iota) {
1102
+ const iotaConfig = getIotaConfig(coreConfig);
1103
+ coreConfig.types.verifiableStorageConnector.push({
1104
+ type: engineTypes.VerifiableStorageConnectorType.Iota,
1105
+ options: {
1106
+ config: iotaConfig ?? {}
1107
+ }
1108
+ });
1109
+ }
1110
+ if (coreConfig.types.verifiableStorageConnector.length > 0) {
1111
+ coreConfig.types.verifiableStorageComponent ??= [];
1112
+ coreConfig.types.verifiableStorageComponent.push({
1113
+ type: engineTypes.VerifiableStorageComponentType.Service
1114
+ });
1115
+ coreConfig.types.immutableProofComponent ??= [];
1116
+ coreConfig.types.immutableProofComponent.push({
1117
+ type: engineTypes.ImmutableProofComponentType.Service,
1118
+ options: {
1119
+ config: {
1120
+ verificationMethodId: envVars.immutableProofVerificationMethodId
1121
+ }
1122
+ }
1123
+ });
1124
+ coreConfig.types.auditableItemGraphComponent ??= [];
1125
+ coreConfig.types.auditableItemGraphComponent.push({
1126
+ type: engineTypes.AuditableItemGraphComponentType.Service
1127
+ });
1128
+ coreConfig.types.auditableItemStreamComponent ??= [];
1129
+ coreConfig.types.auditableItemStreamComponent.push({
1130
+ type: engineTypes.AuditableItemStreamComponentType.Service
1131
+ });
1132
+ }
1133
+ }
1134
+ /**
1135
+ * Configures the identity.
1136
+ * @param coreConfig The core config.
1137
+ * @param envVars The environment variables.
1138
+ */
1139
+ function configureIdentity(coreConfig, envVars) {
1140
+ coreConfig.types.identityConnector ??= [];
1141
+ if (envVars.identityConnector === engineTypes.IdentityConnectorType.EntityStorage) {
1142
+ coreConfig.types.identityConnector.push({
1143
+ type: engineTypes.IdentityConnectorType.EntityStorage
1144
+ });
1145
+ }
1146
+ else if (envVars.identityConnector === engineTypes.IdentityConnectorType.Iota) {
1147
+ const iotaConfig = getIotaConfig(coreConfig);
1148
+ coreConfig.types.identityConnector.push({
1149
+ type: engineTypes.IdentityConnectorType.Iota,
1150
+ options: {
1151
+ config: iotaConfig ?? {}
1152
+ }
1153
+ });
1154
+ }
1155
+ if (coreConfig.types.identityConnector.length > 0) {
1156
+ coreConfig.types.identityComponent ??= [];
1157
+ coreConfig.types.identityComponent.push({ type: engineTypes.IdentityComponentType.Service });
1158
+ }
1159
+ }
1160
+ /**
1161
+ * Configures the identity resolver.
1162
+ * @param coreConfig The core config.
1163
+ * @param envVars The environment variables.
1164
+ */
1165
+ function configureIdentityResolver(coreConfig, envVars) {
1166
+ coreConfig.types.identityResolverConnector ??= [];
1167
+ if (envVars.identityResolverConnector === engineTypes.IdentityResolverConnectorType.EntityStorage) {
1168
+ coreConfig.types.identityResolverConnector.push({
1169
+ type: engineTypes.IdentityResolverConnectorType.EntityStorage
1170
+ });
1171
+ }
1172
+ else if (envVars.identityResolverConnector === engineTypes.IdentityResolverConnectorType.Iota) {
1173
+ const iotaConfig = getIotaConfig(coreConfig);
1174
+ coreConfig.types.identityResolverConnector.push({
1175
+ type: engineTypes.IdentityResolverConnectorType.Iota,
1176
+ options: {
1177
+ config: iotaConfig ?? {}
1178
+ }
1179
+ });
1180
+ }
1181
+ else if (envVars.identityResolverConnector === engineTypes.IdentityResolverConnectorType.Universal) {
1182
+ coreConfig.types.identityResolverConnector.push({
1183
+ type: engineTypes.IdentityResolverConnectorType.Universal,
1184
+ options: {
1185
+ config: {
1186
+ endpoint: envVars.universalResolverEndpoint ?? ""
1187
+ }
1188
+ }
1189
+ });
1190
+ }
1191
+ if (coreConfig.types.identityResolverConnector.length > 0) {
1192
+ coreConfig.types.identityResolverComponent ??= [];
1193
+ coreConfig.types.identityResolverComponent.push({
1194
+ type: engineTypes.IdentityResolverComponentType.Service
1195
+ });
1196
+ }
1197
+ }
1198
+ /**
1199
+ * Configures the identity profile.
1200
+ * @param coreConfig The core config.
1201
+ * @param envVars The environment variables.
1202
+ */
1203
+ function configureIdentityProfile(coreConfig, envVars) {
1204
+ coreConfig.types.identityProfileConnector ??= [];
1205
+ if (envVars.identityProfileConnector === engineTypes.IdentityConnectorType.EntityStorage) {
1206
+ coreConfig.types.identityProfileConnector.push({
1207
+ type: engineTypes.IdentityProfileConnectorType.EntityStorage
1208
+ });
1209
+ }
1210
+ if (coreConfig.types.identityProfileConnector.length > 0) {
1211
+ coreConfig.types.identityProfileComponent ??= [];
1212
+ coreConfig.types.identityProfileComponent.push({ type: engineTypes.IdentityProfileComponentType.Service });
1213
+ }
1214
+ }
1215
+ /**
1216
+ * Configures the attestation.
1217
+ * @param coreConfig The core config.
1218
+ * @param envVars The environment variables.
1219
+ */
1220
+ function configureAttestation(coreConfig, envVars) {
1221
+ coreConfig.types.attestationConnector ??= [];
1222
+ if (envVars.attestationConnector === engineTypes.AttestationConnectorType.Nft) {
1223
+ coreConfig.types.attestationConnector.push({
1224
+ type: engineTypes.AttestationConnectorType.Nft
1225
+ });
1226
+ }
1227
+ if (coreConfig.types.attestationConnector.length > 0) {
1228
+ coreConfig.types.attestationComponent ??= [];
1229
+ coreConfig.types.attestationComponent.push({
1230
+ type: engineTypes.AttestationComponentType.Service,
1231
+ options: {
1232
+ config: {
1233
+ verificationMethodId: envVars.attestationVerificationMethodId
1234
+ }
1235
+ }
1236
+ });
1237
+ }
1238
+ }
1239
+ /**
1240
+ * Configures the auditable item graph.
1241
+ * @param coreConfig The core config.
1242
+ * @param envVars The environment variables.
1243
+ */
1244
+ function configureAuditableItemGraph(coreConfig, envVars) {
1245
+ if (core.Is.arrayValue(coreConfig.types.verifiableStorageConnector)) {
1246
+ coreConfig.types.auditableItemGraphComponent ??= [];
1247
+ coreConfig.types.auditableItemGraphComponent.push({
1248
+ type: engineTypes.AuditableItemGraphComponentType.Service
1249
+ });
1250
+ }
1251
+ }
1252
+ /**
1253
+ * Configures the auditable item stream.
1254
+ * @param coreConfig The core config.
1255
+ * @param envVars The environment variables.
1256
+ */
1257
+ function configureAuditableItemStream(coreConfig, envVars) {
1258
+ if (core.Is.arrayValue(coreConfig.types.verifiableStorageConnector)) {
1259
+ coreConfig.types.auditableItemStreamComponent ??= [];
1260
+ coreConfig.types.auditableItemStreamComponent.push({
1261
+ type: engineTypes.AuditableItemStreamComponentType.Service
1262
+ });
1263
+ }
1264
+ }
1265
+ /**
1266
+ * Configures the data processing.
1267
+ * @param coreConfig The core config.
1268
+ * @param envVars The environment variables.
1269
+ */
1270
+ function configureDataProcessing(coreConfig, envVars) {
1271
+ coreConfig.types.dataConverterConnector ??= [];
1272
+ coreConfig.types.dataExtractorConnector ??= [];
1273
+ const converterConnectors = envVars.dataConverterConnectors?.split(",") ?? [];
1274
+ for (const converterConnector of converterConnectors) {
1275
+ if (converterConnector === engineTypes.DataConverterConnectorType.Json) {
1276
+ coreConfig.types.dataConverterConnector.push({
1277
+ type: engineTypes.DataConverterConnectorType.Json
1278
+ });
1279
+ }
1280
+ else if (converterConnector === engineTypes.DataConverterConnectorType.Xml) {
1281
+ coreConfig.types.dataConverterConnector.push({
1282
+ type: engineTypes.DataConverterConnectorType.Xml
1283
+ });
1284
+ }
1285
+ }
1286
+ const extractorConnectors = envVars.dataExtractorConnectors?.split(",") ?? [];
1287
+ for (const extractorConnector of extractorConnectors) {
1288
+ if (extractorConnector === engineTypes.DataExtractorConnectorType.JsonPath) {
1289
+ coreConfig.types.dataExtractorConnector.push({
1290
+ type: engineTypes.DataExtractorConnectorType.JsonPath
1291
+ });
1292
+ }
1293
+ }
1294
+ if (coreConfig.types.dataConverterConnector.length > 0 ||
1295
+ coreConfig.types.dataExtractorConnector.length > 0) {
1296
+ coreConfig.types.dataProcessingComponent ??= [];
1297
+ coreConfig.types.dataProcessingComponent.push({ type: engineTypes.DataProcessingComponentType.Service });
1298
+ }
1299
+ }
1300
+ /**
1301
+ * Configures the document management.
1302
+ * @param coreConfig The core config.
1303
+ * @param envVars The environment variables.
1304
+ */
1305
+ function configureDocumentManagement(coreConfig, envVars) {
1306
+ if (core.Is.arrayValue(coreConfig.types.auditableItemGraphComponent) &&
1307
+ core.Is.arrayValue(coreConfig.types.blobStorageComponent) &&
1308
+ core.Is.arrayValue(coreConfig.types.attestationComponent)) {
1309
+ coreConfig.types.documentManagementComponent ??= [];
1310
+ coreConfig.types.documentManagementComponent.push({
1311
+ type: engineTypes.DocumentManagementComponentType.Service
1312
+ });
1313
+ }
1314
+ }
1315
+ /**
1316
+ * Configures the federated catalogue.
1317
+ * @param coreConfig The core config.
1318
+ * @param envVars The environment variables.
1319
+ */
1320
+ function configureFederatedCatalogue(coreConfig, envVars) {
1321
+ if (core.Is.arrayValue(coreConfig.types.identityResolverComponent)) {
1322
+ coreConfig.types.federatedCatalogueComponent ??= [];
1323
+ coreConfig.types.federatedCatalogueComponent.push({
1324
+ type: engineTypes.FederatedCatalogueComponentType.Service,
1325
+ options: {
1326
+ config: {
1327
+ subResourceCacheTtlMs: core.Coerce.number(envVars.federatedCatalogueCacheTtlMs),
1328
+ clearingHouseApproverList: core.Coerce.object(envVars.federatedCatalogueClearingHouseApproverList) ?? []
1329
+ }
1330
+ }
1331
+ });
1332
+ }
1333
+ }
1334
+ /**
1335
+ * Configures the rights management.
1336
+ * @param coreConfig The core config.
1337
+ * @param envVars The environment variables.
1338
+ */
1339
+ function configureRightsManagement(coreConfig, envVars) {
1340
+ if (core.Coerce.boolean(envVars.rightsManagementEnabled) ?? false) {
1341
+ coreConfig.types.rightsManagementPapComponent ??= [];
1342
+ coreConfig.types.rightsManagementPapComponent.push({
1343
+ type: engineTypes.RightsManagementPapComponentType.Service
1344
+ });
1345
+ coreConfig.types.rightsManagementComponent ??= [];
1346
+ coreConfig.types.rightsManagementComponent.push({
1347
+ type: engineTypes.RightsManagementComponentType.Service
1348
+ });
1349
+ }
1350
+ }
1351
+ /**
1352
+ * Configures the task scheduler.
1353
+ * @param coreConfig The core config.
1354
+ * @param envVars The environment variables.
1355
+ */
1356
+ function configureTaskScheduler(coreConfig, envVars) {
1357
+ if (core.Coerce.boolean(envVars.taskSchedulerEnabled) ?? true) {
1358
+ coreConfig.types.taskSchedulerComponent ??= [];
1359
+ coreConfig.types.taskSchedulerComponent.push({
1360
+ type: engineTypes.TaskSchedulerComponentType.Default
1361
+ });
1362
+ }
1363
+ }
1364
+ /**
1365
+ * Configures the DLT.
1366
+ * @param coreConfig The core config.
1367
+ * @param envVars The environment variables.
1368
+ */
1369
+ function configureDlt(coreConfig, envVars) {
1370
+ // Create centralized DLT configuration for IOTA if essential IOTA variables are set
1371
+ if (core.Is.stringValue(envVars.iotaNodeEndpoint) && core.Is.stringValue(envVars.iotaNetwork)) {
1372
+ coreConfig.types.dltConfig ??= [];
1373
+ const gasStationConfig = core.Is.stringValue(envVars.iotaGasStationEndpoint) &&
1374
+ core.Is.stringValue(envVars.iotaGasStationAuthToken)
1375
+ ? {
1376
+ gasStationUrl: envVars.iotaGasStationEndpoint,
1377
+ gasStationAuthToken: envVars.iotaGasStationAuthToken
1378
+ }
1379
+ : undefined;
1380
+ coreConfig.types.dltConfig.push({
1381
+ type: engineTypes.DltConfigType.Iota,
1382
+ isDefault: true,
1383
+ options: {
1384
+ config: {
1385
+ clientOptions: {
1386
+ url: envVars.iotaNodeEndpoint ?? ""
1387
+ },
1388
+ network: envVars.iotaNetwork ?? "",
1389
+ coinType: core.Coerce.number(envVars.iotaCoinType),
1390
+ gasStation: gasStationConfig
1391
+ }
1392
+ }
1393
+ });
1394
+ }
1395
+ }
1396
+
1397
+ /**
1398
+ * Handles the configuration of the server.
1399
+ * @param envVars The environment variables for the engine server.
1400
+ * @param coreEngineConfig The core engine config.
1401
+ * @param serverInfo The server information.
1402
+ * @param openApiSpecPath The path to the open api spec.
1403
+ * @returns The the config for the core and the server.
1404
+ */
1405
+ function buildEngineServerConfiguration(envVars, coreEngineConfig, serverInfo, openApiSpecPath) {
1406
+ envVars.authSigningKeyId ??= "auth-signing";
1407
+ const webServerOptions = {
1408
+ port: core.Coerce.number(envVars.port),
1409
+ host: core.Coerce.string(envVars.host),
1410
+ methods: core.Is.stringValue(envVars.httpMethods)
1411
+ ? envVars.httpMethods.split(",")
1412
+ : undefined,
1413
+ allowedHeaders: core.Is.stringValue(envVars.httpAllowedHeaders)
1414
+ ? envVars.httpAllowedHeaders.split(",")
1415
+ : undefined,
1416
+ exposedHeaders: core.Is.stringValue(envVars.httpExposedHeaders)
1417
+ ? envVars.httpExposedHeaders.split(",")
1418
+ : undefined,
1419
+ corsOrigins: core.Is.stringValue(envVars.corsOrigins) ? envVars.corsOrigins.split(",") : undefined
1420
+ };
1421
+ const authProcessorType = envVars.authProcessorType;
1422
+ const serverConfig = {
1423
+ ...coreEngineConfig,
1424
+ web: webServerOptions,
1425
+ types: {
1426
+ ...coreEngineConfig.types,
1427
+ informationComponent: [
1428
+ {
1429
+ type: engineServerTypes.InformationComponentType.Service,
1430
+ options: {
1431
+ config: {
1432
+ serverInfo,
1433
+ openApiSpecPath
1434
+ }
1435
+ }
1436
+ }
1437
+ ]
1438
+ }
1439
+ };
1440
+ if (core.Is.stringValue(envVars.mimeTypeProcessors)) {
1441
+ const mimeTypeProcessors = envVars.mimeTypeProcessors.split(",");
1442
+ if (core.Is.arrayValue(mimeTypeProcessors)) {
1443
+ serverConfig.types.mimeTypeProcessor ??= [];
1444
+ for (const mimeTypeProcessor of mimeTypeProcessors) {
1445
+ serverConfig.types.mimeTypeProcessor.push({
1446
+ type: mimeTypeProcessor
1447
+ });
1448
+ }
1449
+ }
1450
+ }
1451
+ serverConfig.types.restRouteProcessor ??= [];
1452
+ serverConfig.types.socketRouteProcessor ??= [];
1453
+ const disableNodeIdentity = core.Coerce.boolean(envVars.disableNodeIdentity);
1454
+ if (!disableNodeIdentity) {
1455
+ serverConfig.types.restRouteProcessor.push({
1456
+ type: engineServerTypes.RestRouteProcessorType.NodeIdentity
1457
+ });
1458
+ serverConfig.types.socketRouteProcessor.push({
1459
+ type: engineServerTypes.SocketRouteProcessorType.NodeIdentity
1460
+ });
1461
+ }
1462
+ if (!coreEngineConfig.silent) {
1463
+ serverConfig.types.restRouteProcessor.push({
1464
+ type: engineServerTypes.RestRouteProcessorType.Logging,
1465
+ options: {
1466
+ config: {
1467
+ includeBody: coreEngineConfig.debug
1468
+ }
1469
+ }
1470
+ });
1471
+ serverConfig.types.socketRouteProcessor.push({
1472
+ type: engineServerTypes.SocketRouteProcessorType.Logging,
1473
+ options: {
1474
+ config: {
1475
+ includeBody: coreEngineConfig.debug
1476
+ }
1477
+ }
1478
+ });
1479
+ }
1480
+ serverConfig.types.restRouteProcessor.push({
1481
+ type: engineServerTypes.RestRouteProcessorType.RestRoute,
1482
+ options: {
1483
+ config: {
1484
+ includeErrorStack: coreEngineConfig.debug
1485
+ }
1486
+ }
1487
+ });
1488
+ serverConfig.types.socketRouteProcessor.push({
1489
+ type: engineServerTypes.SocketRouteProcessorType.SocketRoute,
1490
+ options: {
1491
+ config: {
1492
+ includeErrorStack: coreEngineConfig.debug
1493
+ }
1494
+ }
1495
+ });
1496
+ if (authProcessorType === engineServerTypes.AuthenticationComponentType.EntityStorage) {
1497
+ serverConfig.types.authenticationComponent ??= [];
1498
+ serverConfig.types.authenticationComponent.push({
1499
+ type: engineServerTypes.AuthenticationComponentType.EntityStorage,
1500
+ options: {
1501
+ config: {
1502
+ signingKeyName: envVars.authSigningKeyId
1503
+ }
1504
+ }
1505
+ });
1506
+ serverConfig.types.restRouteProcessor.push({
1507
+ type: engineServerTypes.RestRouteProcessorType.AuthHeader,
1508
+ options: {
1509
+ config: {
1510
+ signingKeyName: envVars.authSigningKeyId
1511
+ }
1512
+ }
1513
+ });
1514
+ serverConfig.types.socketRouteProcessor.push({
1515
+ type: engineServerTypes.SocketRouteProcessorType.AuthHeader,
1516
+ options: {
1517
+ config: {
1518
+ signingKeyName: envVars.authSigningKeyId
1519
+ }
1520
+ }
1521
+ });
1522
+ }
1523
+ engineServer.addDefaultRestPaths(serverConfig);
1524
+ engineServer.addDefaultSocketPaths(serverConfig);
1525
+ return serverConfig;
1526
+ }
1527
+
1528
+ // Copyright 2024 IOTA Stiftung.
1529
+ // SPDX-License-Identifier: Apache-2.0.
1530
+ /* eslint-disable no-console */
1531
+ /**
1532
+ * Start the engine server.
1533
+ * @param nodeOptions Optional run options for the engine server.
1534
+ * @param engineServerConfig The configuration for the engine server.
1535
+ * @param envVars The environment variables.
1536
+ * @returns The engine server.
1537
+ */
1538
+ async function start(nodeOptions, engineServerConfig, envVars) {
1539
+ envVars.storageFileRoot ??= "";
1540
+ if ((envVars.entityStorageConnectorType === engineTypes.EntityStorageConnectorType.File ||
1541
+ envVars.blobStorageConnectorType === engineTypes.BlobStorageConnectorType.File ||
1542
+ core.Is.empty(nodeOptions?.stateStorage)) &&
1543
+ !core.Is.stringValue(envVars.storageFileRoot)) {
1544
+ throw new core.GeneralError("node", "storageFileRootNotSet", {
1545
+ storageFileRoot: `${nodeOptions?.envPrefix ?? ""}_STORAGE_FILE_ROOT`
1546
+ });
1547
+ }
1548
+ // Create the engine instance using file state storage and custom bootstrap.
1549
+ const engine$1 = new engine.Engine({
1550
+ config: engineServerConfig,
1551
+ stateStorage: nodeOptions?.stateStorage ?? new engineCore.FileStateStorage(envVars.stateFilename ?? ""),
1552
+ customBootstrap: async (core, engineContext) => bootstrap(core, engineContext, envVars)
1553
+ });
1554
+ // Extend the engine.
1555
+ if (core.Is.function(nodeOptions?.extendEngine)) {
1556
+ console.info("Extending Engine");
1557
+ await nodeOptions.extendEngine(engine$1);
1558
+ }
1559
+ // Construct the server with the engine.
1560
+ const server = new engineServer.EngineServer({ engineCore: engine$1 });
1561
+ // Extend the engine server.
1562
+ if (core.Is.function(nodeOptions?.extendEngineServer)) {
1563
+ console.info("Extending Engine Server");
1564
+ await nodeOptions?.extendEngineServer(server);
1565
+ }
1566
+ // Need to register the engine with the factory so that background tasks
1567
+ // can clone it to spawn new instances.
1568
+ engineModels.EngineCoreFactory.register("engine", () => engine$1);
1569
+ // Start the server, which also starts the engine.
1570
+ const canContinue = await server.start();
1571
+ if (canContinue) {
1572
+ return {
1573
+ engine: engine$1,
1574
+ server
1575
+ };
1576
+ }
1577
+ }
1578
+
1579
+ // Copyright 2024 IOTA Stiftung.
1580
+ // SPDX-License-Identifier: Apache-2.0.
1581
+ /* eslint-disable no-console */
1582
+ /**
1583
+ * Run the TWIN Node server.
1584
+ * @param nodeOptions Optional configuration options for running the server.
1585
+ * @returns A promise that resolves when the server is started.
1586
+ */
1587
+ async function run(nodeOptions) {
1588
+ try {
1589
+ nodeOptions ??= {};
1590
+ const serverInfo = {
1591
+ name: nodeOptions?.serverName ?? "TWIN Node Server",
1592
+ version: nodeOptions?.serverVersion ?? "0.0.1-next.10" // x-release-please-version
1593
+ };
1594
+ console.log(`\u001B[4m🌩️ ${serverInfo.name} v${serverInfo.version}\u001B[24m\n`);
1595
+ if (!core.Is.stringValue(nodeOptions?.executionDirectory)) {
1596
+ nodeOptions.executionDirectory = getExecutionDirectory();
1597
+ }
1598
+ console.info("Execution Directory:", nodeOptions.executionDirectory);
1599
+ nodeOptions.localesDirectory =
1600
+ nodeOptions?.localesDirectory ??
1601
+ path.resolve(path.join(nodeOptions.executionDirectory, "dist", "locales"));
1602
+ console.info("Locales Directory:", nodeOptions.localesDirectory);
1603
+ await initialiseLocales(nodeOptions.localesDirectory);
1604
+ if (core.Is.empty(nodeOptions?.openApiSpecFile)) {
1605
+ const specFile = path.resolve(path.join(nodeOptions.executionDirectory, "docs", "open-api", "spec.json"));
1606
+ console.info("Default OpenAPI Spec File:", specFile);
1607
+ if (await fileExists(specFile)) {
1608
+ nodeOptions ??= {};
1609
+ nodeOptions.openApiSpecFile = specFile;
1610
+ }
1611
+ }
1612
+ nodeOptions.envPrefix ??= "TWIN_NODE_";
1613
+ console.info("Environment Prefix:", nodeOptions.envPrefix);
1614
+ const { engineServerConfig, nodeEnvVars: envVars } = await buildConfiguration(process.env, nodeOptions, serverInfo);
1615
+ console.info();
1616
+ const startResult = await start(nodeOptions, engineServerConfig, envVars);
1617
+ if (!core.Is.empty(startResult)) {
1618
+ for (const signal of ["SIGHUP", "SIGINT", "SIGTERM"]) {
1619
+ process.on(signal, async () => {
1620
+ await startResult.server.stop();
1621
+ });
1622
+ }
1623
+ }
1624
+ }
1625
+ catch (err) {
1626
+ console.error(core.ErrorHelper.formatErrors(err).join("\n"));
1627
+ // eslint-disable-next-line unicorn/no-process-exit
1628
+ process.exit(1);
1629
+ }
1630
+ }
1631
+ /**
1632
+ * Build the configuration for the TWIN Node server.
1633
+ * @param processEnv The environment variables from the process.
1634
+ * @param options The options for running the server.
1635
+ * @param serverInfo The server information.
1636
+ * @returns A promise that resolves to the engine server configuration, environment prefix, environment variables,
1637
+ * and options.
1638
+ */
1639
+ async function buildConfiguration(processEnv, options, serverInfo) {
1640
+ let defaultEnvOnly = false;
1641
+ if (core.Is.empty(options?.envFilenames)) {
1642
+ const envFile = path.resolve(path.join(options.executionDirectory ?? "", ".env"));
1643
+ console.info("Default Environment File:", envFile);
1644
+ options ??= {};
1645
+ options.envFilenames = [envFile];
1646
+ defaultEnvOnly = true;
1647
+ }
1648
+ if (core.Is.arrayValue(options?.envFilenames)) {
1649
+ const output = dotenv__namespace.config({
1650
+ path: options?.envFilenames
1651
+ });
1652
+ // We don't want to throw an error if the default environment file is not found.
1653
+ // Only if we have custom environment files.
1654
+ if (!defaultEnvOnly && output.error) {
1655
+ throw output.error;
1656
+ }
1657
+ if (core.Is.objectValue(output.parsed)) {
1658
+ Object.assign(processEnv, output.parsed);
1659
+ }
1660
+ }
1661
+ const envVars = core.EnvHelper.envToJson(processEnv, options.envPrefix ?? "");
1662
+ // Expand any environment variables that use the @file: syntax
1663
+ const keys = Object.keys(envVars);
1664
+ for (const key of keys) {
1665
+ if (core.Is.stringValue(envVars[key]) && envVars[key].startsWith("@file:")) {
1666
+ const filePath = envVars[key].slice(6).trim();
1667
+ const embeddedFile = path.resolve(path.join(options.executionDirectory ?? "", filePath));
1668
+ console.info(`Expanding Environment Variable: ${key} from file: ${embeddedFile}`);
1669
+ const fileContent = await loadJsonFile(embeddedFile);
1670
+ envVars[key] = fileContent;
1671
+ }
1672
+ }
1673
+ // Extend the environment variables with any additional custom configuration.
1674
+ if (core.Is.function(options?.extendEnvVars)) {
1675
+ console.info("Extending Environment Variables");
1676
+ await options.extendEnvVars(envVars);
1677
+ }
1678
+ // Build the engine configuration from the environment variables.
1679
+ const coreConfig = buildEngineConfiguration(envVars);
1680
+ const engineServerConfig = buildEngineServerConfiguration(envVars, coreConfig, serverInfo, options?.openApiSpecFile);
1681
+ // Merge any custom configuration provided in the options.
1682
+ if (core.Is.arrayValue(options?.configFilenames)) {
1683
+ for (const configFile of options.configFilenames) {
1684
+ console.info("Loading Configuration File:", configFile);
1685
+ const configFilePath = path.resolve(path.join(options.executionDirectory ?? "", configFile));
1686
+ const config = await loadJsonFile(configFilePath);
1687
+ Object.assign(engineServerConfig, config);
1688
+ }
1689
+ }
1690
+ if (core.Is.objectValue(options?.config)) {
1691
+ console.info("Merging Custom Configuration");
1692
+ Object.assign(engineServerConfig, options.config);
1693
+ }
1694
+ // Merge any custom configuration provided in the options.
1695
+ if (core.Is.function(options?.extendConfig)) {
1696
+ console.info("Extending Configuration");
1697
+ await options.extendConfig(engineServerConfig);
1698
+ }
1699
+ return { engineServerConfig, nodeEnvVars: envVars };
1700
+ }
1701
+
1702
+ exports.NodeFeatures = NodeFeatures;
1703
+ exports.bootstrap = bootstrap;
1704
+ exports.bootstrapAttestationMethod = bootstrapAttestationMethod;
1705
+ exports.bootstrapAuth = bootstrapAuth;
1706
+ exports.bootstrapBlobEncryption = bootstrapBlobEncryption;
1707
+ exports.bootstrapImmutableProofMethod = bootstrapImmutableProofMethod;
1708
+ exports.bootstrapNodeIdentity = bootstrapNodeIdentity;
1709
+ exports.bootstrapNodeUser = bootstrapNodeUser;
1710
+ exports.buildConfiguration = buildConfiguration;
1711
+ exports.buildEngineConfiguration = buildEngineConfiguration;
1712
+ exports.fileExists = fileExists;
1713
+ exports.getExecutionDirectory = getExecutionDirectory;
1714
+ exports.getFeatures = getFeatures;
1715
+ exports.initialiseLocales = initialiseLocales;
1716
+ exports.loadJsonFile = loadJsonFile;
1717
+ exports.run = run;
1718
+ exports.start = start;