@memberjunction/installer 5.11.0 → 5.13.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.
Files changed (51) hide show
  1. package/dist/InstallerEngine.d.ts +83 -0
  2. package/dist/InstallerEngine.d.ts.map +1 -1
  3. package/dist/InstallerEngine.js +476 -3
  4. package/dist/InstallerEngine.js.map +1 -1
  5. package/dist/adapters/GitHubReleaseProvider.d.ts +66 -9
  6. package/dist/adapters/GitHubReleaseProvider.d.ts.map +1 -1
  7. package/dist/adapters/GitHubReleaseProvider.js +157 -29
  8. package/dist/adapters/GitHubReleaseProvider.js.map +1 -1
  9. package/dist/adapters/ProcessRunner.d.ts +6 -0
  10. package/dist/adapters/ProcessRunner.d.ts.map +1 -1
  11. package/dist/adapters/ProcessRunner.js +3 -0
  12. package/dist/adapters/ProcessRunner.js.map +1 -1
  13. package/dist/index.d.ts +2 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +3 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/logging/EventLogger.d.ts +105 -0
  18. package/dist/logging/EventLogger.d.ts.map +1 -0
  19. package/dist/logging/EventLogger.js +165 -0
  20. package/dist/logging/EventLogger.js.map +1 -0
  21. package/dist/logging/ReportGenerator.d.ts +175 -0
  22. package/dist/logging/ReportGenerator.d.ts.map +1 -0
  23. package/dist/logging/ReportGenerator.js +526 -0
  24. package/dist/logging/ReportGenerator.js.map +1 -0
  25. package/dist/models/InstallConfig.d.ts +5 -0
  26. package/dist/models/InstallConfig.d.ts.map +1 -1
  27. package/dist/models/InstallConfig.js +2 -1
  28. package/dist/models/InstallConfig.js.map +1 -1
  29. package/dist/models/InstallPlan.d.ts +17 -0
  30. package/dist/models/InstallPlan.d.ts.map +1 -1
  31. package/dist/models/InstallPlan.js.map +1 -1
  32. package/dist/phases/CodeGenPhase.d.ts +35 -2
  33. package/dist/phases/CodeGenPhase.d.ts.map +1 -1
  34. package/dist/phases/CodeGenPhase.js +128 -8
  35. package/dist/phases/CodeGenPhase.js.map +1 -1
  36. package/dist/phases/ConfigurePhase.d.ts +143 -8
  37. package/dist/phases/ConfigurePhase.d.ts.map +1 -1
  38. package/dist/phases/ConfigurePhase.js +378 -31
  39. package/dist/phases/ConfigurePhase.js.map +1 -1
  40. package/dist/phases/DependencyPhase.d.ts +40 -2
  41. package/dist/phases/DependencyPhase.d.ts.map +1 -1
  42. package/dist/phases/DependencyPhase.js +102 -5
  43. package/dist/phases/DependencyPhase.js.map +1 -1
  44. package/dist/phases/MigratePhase.d.ts +34 -6
  45. package/dist/phases/MigratePhase.d.ts.map +1 -1
  46. package/dist/phases/MigratePhase.js +48 -7
  47. package/dist/phases/MigratePhase.js.map +1 -1
  48. package/dist/phases/ScaffoldPhase.d.ts.map +1 -1
  49. package/dist/phases/ScaffoldPhase.js +20 -6
  50. package/dist/phases/ScaffoldPhase.js.map +1 -1
  51. package/package.json +1 -1
@@ -4,22 +4,26 @@
4
4
  * Gathers user configuration via prompt events (or reads from `--config` /
5
5
  * `--yes` defaults), then generates the three configuration file families:
6
6
  *
7
- * 1. **`.env`** — Database credentials, API keys, port settings, auth config.
7
+ * 1. **`.env`** — Database credentials, API keys, port settings, auth config,
8
+ * and `MJ_BASE_ENCRYPTION_KEY` for field-level encryption.
8
9
  * Written to both the repo root and `packages/MJAPI/.env`.
9
10
  * 2. **`mj.config.cjs`** — CodeGen configuration (host, port, database, schema,
10
- * optional new user setup).
11
- * 3. **Explorer environment files** — `environment.ts` and `environment.development.ts`
12
- * in `packages/MJExplorer/src/environments/`.
11
+ * optional new user setup, and `encryptionKeys` block).
12
+ * 3. **Explorer environment files** — `environment.ts` and
13
+ * `environment.development.ts` in `packages/MJExplorer/src/environments/`.
13
14
  *
14
- * **Preserve-vs-create strategy**: If a configuration file already exists, it
15
- * is preserved (not overwritten). This allows users to re-run the installer
16
- * without losing hand-edited configuration. Only missing files are created.
15
+ * **Preserve-vs-patch strategy**: If a configuration file already exists it is
16
+ * preserved, but the installer will patch in `MJ_BASE_ENCRYPTION_KEY` and
17
+ * `encryptionKeys` support if they are missing. This lets users re-run the
18
+ * installer without losing hand-edited configuration while still gaining new
19
+ * required settings.
17
20
  *
18
21
  * @module phases/ConfigurePhase
19
22
  * @see InstallConfig — the full configuration interface.
20
23
  * @see InstallConfigDefaults — default values for auto-mode.
21
24
  */
22
25
  import path from 'node:path';
26
+ import { randomBytes } from 'node:crypto';
23
27
  import { FileSystemAdapter } from '../adapters/FileSystemAdapter.js';
24
28
  /**
25
29
  * Phase E — Gathers configuration and generates `.env`, `mj.config.cjs`,
@@ -58,20 +62,35 @@ export class ConfigurePhase {
58
62
  Message: 'Gathering configuration...',
59
63
  });
60
64
  const config = await this.resolveConfig(context.Config, context.Yes, emitter);
61
- // Step 2: .env files — preserve existing, create if missing
65
+ // Step 2: .env files — preserve existing, create if missing, patch encryption key
62
66
  const envPath = path.join(context.Dir, '.env');
63
- const mjapiEnvPath = path.join(context.Dir, 'packages', 'MJAPI', '.env');
67
+ const mjapiEnvPath = await this.resolveMjapiEnvPath(context.Dir);
64
68
  if (await this.fileSystem.FileExists(envPath)) {
65
- filesPreserved.push(envPath);
69
+ const existingRootEnv = await this.fileSystem.ReadText(envPath);
70
+ const patchedRootEnv = this.ensureEnvVar(existingRootEnv, 'MJ_BASE_ENCRYPTION_KEY', config.BaseEncryptionKey ?? '');
71
+ if (patchedRootEnv !== existingRootEnv) {
72
+ await this.fileSystem.WriteText(envPath, patchedRootEnv);
73
+ filesWritten.push(envPath);
74
+ }
75
+ else {
76
+ filesPreserved.push(envPath);
77
+ }
66
78
  // If MJAPI .env doesn't exist but root does, copy root → MJAPI
67
79
  const mjapiDir = path.dirname(mjapiEnvPath);
68
80
  if (await this.fileSystem.DirectoryExists(mjapiDir) && !(await this.fileSystem.FileExists(mjapiEnvPath))) {
69
- const rootEnvContent = await this.fileSystem.ReadText(envPath);
70
- await this.fileSystem.WriteText(mjapiEnvPath, rootEnvContent);
81
+ await this.fileSystem.WriteText(mjapiEnvPath, patchedRootEnv);
71
82
  filesWritten.push(mjapiEnvPath);
72
83
  }
73
84
  else if (await this.fileSystem.FileExists(mjapiEnvPath)) {
74
- filesPreserved.push(mjapiEnvPath);
85
+ const existingMjapiEnv = await this.fileSystem.ReadText(mjapiEnvPath);
86
+ const patchedMjapiEnv = this.ensureEnvVar(existingMjapiEnv, 'MJ_BASE_ENCRYPTION_KEY', config.BaseEncryptionKey ?? '');
87
+ if (patchedMjapiEnv !== existingMjapiEnv) {
88
+ await this.fileSystem.WriteText(mjapiEnvPath, patchedMjapiEnv);
89
+ filesWritten.push(mjapiEnvPath);
90
+ }
91
+ else {
92
+ filesPreserved.push(mjapiEnvPath);
93
+ }
75
94
  }
76
95
  }
77
96
  else {
@@ -83,15 +102,20 @@ export class ConfigurePhase {
83
102
  filesWritten.push(mjapiEnvPath);
84
103
  }
85
104
  }
86
- // Step 3: mj.config.cjs — preserve existing, create if missing
105
+ // Step 3: mj.config.cjs — preserve existing, create if missing, patch encryption + user
87
106
  const configCjsPath = path.join(context.Dir, 'mj.config.cjs');
88
107
  if (await this.fileSystem.FileExists(configCjsPath)) {
89
- filesPreserved.push(configCjsPath);
90
- // If user is creating a new user, patch that section into the existing config
108
+ const existingContent = await this.fileSystem.ReadText(configCjsPath);
109
+ let updatedContent = this.ensureEncryptionKeysBlock(existingContent);
91
110
  if (config.CreateNewUser) {
92
- const existingContent = await this.fileSystem.ReadText(configCjsPath);
93
- const updatedContent = this.patchNewUserSetup(existingContent, config.CreateNewUser);
111
+ updatedContent = this.patchNewUserSetup(updatedContent, config.CreateNewUser);
112
+ }
113
+ if (updatedContent !== existingContent) {
94
114
  await this.fileSystem.WriteText(configCjsPath, updatedContent);
115
+ filesWritten.push(configCjsPath);
116
+ }
117
+ else {
118
+ filesPreserved.push(configCjsPath);
95
119
  }
96
120
  }
97
121
  else {
@@ -103,10 +127,30 @@ export class ConfigurePhase {
103
127
  await this.writeMjConfigCjs(configCjsPath, config);
104
128
  filesWritten.push(configCjsPath);
105
129
  }
130
+ // Step 3.5: Backfill auth values from any existing .env files into the
131
+ // config so that Explorer environment patching has real values to work
132
+ // with. This covers the case where the root .env was freshly written
133
+ // with empty auth but apps/MJAPI/.env has real credentials from a
134
+ // previous install or the bootstrap archive.
135
+ await this.backfillAuthFromEnv(context.Dir, config);
106
136
  // Step 4: Explorer environment files — preserve existing, create if missing
107
137
  const envFilesResult = await this.updateExplorerEnvironments(context.Dir, config, emitter);
108
138
  filesWritten.push(...envFilesResult.Written);
109
139
  filesPreserved.push(...envFilesResult.Preserved);
140
+ // Auth-not-configured warning — more specific than the generic defaults warning
141
+ if (config.AuthProvider === 'none') {
142
+ emitter.Emit('warn', {
143
+ Type: 'warn',
144
+ Phase: 'configure',
145
+ Message: 'Authentication provider is not configured. '
146
+ + 'MJExplorer will NOT start until you set up authentication. '
147
+ + 'To fix: (1) Register an Azure AD (Entra) or Auth0 application, '
148
+ + '(2) Edit packages/MJExplorer/src/environments/environment.ts — '
149
+ + 'set AUTH_TYPE, CLIENT_ID, and TENANT_ID (for Entra) or '
150
+ + 'AUTH_TYPE, AUTH0_DOMAIN, and AUTH0_CLIENTID (for Auth0), '
151
+ + '(3) Update .env with the same credentials for MJAPI.',
152
+ });
153
+ }
110
154
  // Summary
111
155
  const parts = [];
112
156
  if (filesWritten.length > 0) {
@@ -134,13 +178,24 @@ export class ConfigurePhase {
134
178
  // ---------------------------------------------------------------------------
135
179
  // Config resolution — prompts for any missing values
136
180
  // ---------------------------------------------------------------------------
181
+ /**
182
+ * Resolve a partial config into a fully populated {@link InstallConfig} by
183
+ * prompting for missing values (or using defaults in `--yes` mode).
184
+ *
185
+ * Also generates a `BaseEncryptionKey` if one was not provided.
186
+ *
187
+ * @param partial - Config values already known (from CLI flags, env vars, or config file).
188
+ * @param yes - When `true`, use defaults for all missing fields without prompting.
189
+ * @param emitter - Event emitter used to send prompt events.
190
+ * @returns A fully populated config object.
191
+ */
137
192
  async resolveConfig(partial, yes, emitter) {
138
193
  const config = { ...partial };
139
194
  // Database settings
140
195
  config.DatabaseHost = config.DatabaseHost ?? await this.promptInput(emitter, 'db-host', 'Database server hostname:', 'localhost', yes);
141
196
  config.DatabasePort = config.DatabasePort ?? parseInt(await this.promptInput(emitter, 'db-port', 'Database server port:', '1433', yes), 10);
142
197
  config.DatabaseName = config.DatabaseName ?? await this.promptInput(emitter, 'db-name', 'Database name:', 'MemberJunction', yes);
143
- config.DatabaseTrustCert = config.DatabaseTrustCert ?? (await this.promptConfirm(emitter, 'db-trust-cert', 'Trust self-signed server certificate? (common for local instances)', false, yes));
198
+ config.DatabaseTrustCert = config.DatabaseTrustCert ?? await this.promptConfirm(emitter, 'db-trust-cert', 'Trust self-signed server certificate? (common for local instances)', false, yes);
144
199
  // CodeGen credentials
145
200
  config.CodeGenUser = config.CodeGenUser ?? await this.promptInput(emitter, 'codegen-user', 'CodeGen database login:', 'MJ_CodeGen', yes);
146
201
  config.CodeGenPassword = config.CodeGenPassword ?? await this.promptInput(emitter, 'codegen-password', 'CodeGen database password:', '', yes);
@@ -171,7 +226,7 @@ export class ConfigurePhase {
171
226
  config.AuthProviderValues.TenantID = config.AuthProviderValues.TenantID ?? await this.promptInput(emitter, 'entra-tenant-id', 'Entra Tenant ID:', '', yes);
172
227
  config.AuthProviderValues.ClientID = config.AuthProviderValues.ClientID ?? await this.promptInput(emitter, 'entra-client-id', 'Entra Web Client ID:', '', yes);
173
228
  }
174
- else if (config.AuthProvider === 'auth0') {
229
+ else {
175
230
  config.AuthProviderValues.Domain = config.AuthProviderValues.Domain ?? await this.promptInput(emitter, 'auth0-domain', 'Auth0 Domain:', '', yes);
176
231
  config.AuthProviderValues.ClientID = config.AuthProviderValues.ClientID ?? await this.promptInput(emitter, 'auth0-client-id', 'Auth0 Client ID:', '', yes);
177
232
  config.AuthProviderValues.ClientSecret = config.AuthProviderValues.ClientSecret ?? await this.promptInput(emitter, 'auth0-client-secret', 'Auth0 Client Secret:', '', yes);
@@ -192,14 +247,21 @@ export class ConfigurePhase {
192
247
  config.CreateNewUser = { Email: email, FirstName: firstName, LastName: lastName, Username: username };
193
248
  }
194
249
  }
250
+ // Encryption key — generate a cryptographically random 256-bit key if not provided
251
+ config.BaseEncryptionKey = config.BaseEncryptionKey ?? this.generateBaseEncryptionKey();
195
252
  return config;
196
253
  }
197
254
  // ---------------------------------------------------------------------------
198
255
  // File generation
199
256
  // ---------------------------------------------------------------------------
257
+ /**
258
+ * Write a fresh `.env` file with all config values including the encryption key.
259
+ *
260
+ * @param envPath - Absolute path to write the `.env` file.
261
+ * @param config - Fully resolved config.
262
+ */
200
263
  async writeEnvFile(envPath, config) {
201
264
  const trustCert = config.DatabaseTrustCert ? 'DB_TRUST_SERVER_CERTIFICATE=1' : '';
202
- const authType = this.mapAuthType(config.AuthProvider);
203
265
  const content = `#Database Setup
204
266
  DB_HOST='${config.DatabaseHost}'
205
267
  DB_PORT=${config.DatabasePort}
@@ -216,6 +278,9 @@ OUTPUT_CODE='${config.DatabaseName}'
216
278
  # Name of the schema that MJ has been setup in. This defaults to __mj
217
279
  MJ_CORE_SCHEMA='__mj'
218
280
 
281
+ # Encryption key for MJ field-level encryption (base64-encoded, 256-bit)
282
+ MJ_BASE_ENCRYPTION_KEY='${config.BaseEncryptionKey ?? ''}'
283
+
219
284
  # AI API Keys
220
285
  AI_VENDOR_API_KEY__OpenAILLM='${config.OpenAIKey ?? ''}'
221
286
  AI_VENDOR_API_KEY__MistralLLM='${config.MistralKey ?? ''}'
@@ -241,15 +306,22 @@ ASK_SKIP_ORGANIZATION_ID=1
241
306
  `;
242
307
  await this.fileSystem.WriteText(envPath, content);
243
308
  }
309
+ /**
310
+ * Write a fresh `mj.config.cjs` with database settings, encryption keys,
311
+ * and optional new user setup.
312
+ *
313
+ * @param configPath - Absolute path to write the config file.
314
+ * @param config - Fully resolved config.
315
+ */
244
316
  async writeMjConfigCjs(configPath, config) {
245
- // Generate a minimal mj.config.cjs for fresh installs
246
317
  const newUserSection = config.CreateNewUser
247
318
  ? ` newUserSetup: {
248
319
  userName: '${config.CreateNewUser.Username}',
249
320
  firstName: '${config.CreateNewUser.FirstName}',
250
321
  lastName: '${config.CreateNewUser.LastName}',
251
322
  email: '${config.CreateNewUser.Email}',
252
- },`
323
+ },
324
+ `
253
325
  : '';
254
326
  const content = `module.exports = {
255
327
  settings: {
@@ -258,13 +330,28 @@ ASK_SKIP_ORGANIZATION_ID=1
258
330
  database: '${config.DatabaseName}',
259
331
  mjCoreSchema: '__mj',
260
332
  },
261
- ${newUserSection}
262
- output: [],
333
+ encryptionKeys: {
334
+ MJ_BASE_ENCRYPTION_KEY: process.env.MJ_BASE_ENCRYPTION_KEY || '',
335
+ },
336
+ ${newUserSection} output: [],
263
337
  commands: [],
264
338
  };
265
339
  `;
266
340
  await this.fileSystem.WriteText(configPath, content);
267
341
  }
342
+ // ---------------------------------------------------------------------------
343
+ // Patching helpers — update existing config files without full overwrite
344
+ // ---------------------------------------------------------------------------
345
+ /**
346
+ * Patch or replace a `newUserSetup` block in an existing `mj.config.cjs`.
347
+ *
348
+ * If an existing `newUserSetup: { ... }` block is found it is replaced
349
+ * in-place; otherwise the block is inserted before the closing `};`.
350
+ *
351
+ * @param content - Current file content.
352
+ * @param newUser - New user details to insert.
353
+ * @returns The patched content.
354
+ */
268
355
  patchNewUserSetup(content, newUser) {
269
356
  const newUserBlock = `newUserSetup: {
270
357
  userName: '${newUser.Username}',
@@ -284,6 +371,74 @@ ${newUserSection}
284
371
  }
285
372
  return content;
286
373
  }
374
+ /**
375
+ * Ensure an existing `mj.config.cjs` has the `encryptionKeys` block.
376
+ *
377
+ * If the block already exists (detected by `encryptionKeys :` pattern) the
378
+ * content is returned unchanged. Otherwise the block is inserted after the
379
+ * `settings: { ... }` block, or before the closing `};` as a fallback.
380
+ *
381
+ * @param content - Current `mj.config.cjs` file content.
382
+ * @returns The content with `encryptionKeys` guaranteed to be present.
383
+ */
384
+ ensureEncryptionKeysBlock(content) {
385
+ if (/encryptionKeys\s*:/.test(content)) {
386
+ return content;
387
+ }
388
+ const block = ` encryptionKeys: {
389
+ MJ_BASE_ENCRYPTION_KEY: process.env.MJ_BASE_ENCRYPTION_KEY || '',
390
+ },
391
+ `;
392
+ // Preferred: insert after the `settings: { ... },` block.
393
+ // The settings block is always flat (host, port, database, mjCoreSchema)
394
+ // so matching to the first `}` with a non-greedy quantifier is safe.
395
+ const insertAfterSettings = content.match(/settings\s*:\s*\{[\s\S]*?\}\s*,?\n/);
396
+ if (insertAfterSettings?.index !== undefined) {
397
+ const insertAt = insertAfterSettings.index + insertAfterSettings[0].length;
398
+ return content.slice(0, insertAt) + block + content.slice(insertAt);
399
+ }
400
+ // Fallback: insert before closing `};`
401
+ const insertPoint = content.lastIndexOf('};');
402
+ if (insertPoint >= 0) {
403
+ return content.slice(0, insertPoint) + block + content.slice(insertPoint);
404
+ }
405
+ return content;
406
+ }
407
+ /**
408
+ * Ensure a KEY=VALUE variable exists in a `.env` file.
409
+ *
410
+ * If `name` is already present (with any value, including empty), the
411
+ * content is returned unchanged. Otherwise the variable is appended.
412
+ *
413
+ * @param content - Existing `.env` file content.
414
+ * @param name - Environment variable name (e.g. `MJ_BASE_ENCRYPTION_KEY`).
415
+ * @param value - Value to set if the variable is missing.
416
+ * @returns The content with the variable guaranteed to be present.
417
+ */
418
+ ensureEnvVar(content, name, value) {
419
+ const envVarPattern = new RegExp(`^${name}=`, 'm');
420
+ if (envVarPattern.test(content)) {
421
+ return content;
422
+ }
423
+ const suffix = content.endsWith('\n') ? '' : '\n';
424
+ return `${content}${suffix}${name}='${value}'\n`;
425
+ }
426
+ // ---------------------------------------------------------------------------
427
+ // Explorer environment files
428
+ // ---------------------------------------------------------------------------
429
+ /**
430
+ * Create or preserve Explorer environment files (`environment.ts`,
431
+ * `environment.development.ts`).
432
+ *
433
+ * Searches for `MJExplorer/src/environments/` under several candidate
434
+ * parent paths (monorepo, distribution, flat). Existing files are preserved;
435
+ * missing files are generated from the resolved config.
436
+ *
437
+ * @param dir - Repo root directory.
438
+ * @param config - Fully resolved config.
439
+ * @param emitter - Event emitter for progress/warn events.
440
+ * @returns Lists of files written and files preserved.
441
+ */
287
442
  async updateExplorerEnvironments(dir, config, emitter) {
288
443
  const envDirCandidates = [
289
444
  path.join(dir, 'packages', 'MJExplorer', 'src', 'environments'),
@@ -320,14 +475,23 @@ ${newUserSection}
320
475
  ? await this.fileSystem.ListFiles(envDir, /environment.*\.ts$/)
321
476
  : [];
322
477
  if (envFiles.length > 0) {
323
- // Existing environment files found — preserve them
478
+ // Existing environment files found — preserve structure but patch
479
+ // empty auth/connection fields with resolved config values.
480
+ let patchedCount = 0;
324
481
  for (const file of envFiles) {
325
- filesPreserved.push(path.join(envDir, file));
482
+ const filePath = path.join(envDir, file);
483
+ filesPreserved.push(filePath);
484
+ const patched = await this.patchExplorerEnvironmentFile(filePath, config);
485
+ if (patched)
486
+ patchedCount++;
326
487
  }
488
+ const patchMsg = patchedCount > 0
489
+ ? `, patched ${patchedCount} file(s) with auth/connection values`
490
+ : '';
327
491
  emitter.Emit('step:progress', {
328
492
  Type: 'step:progress',
329
493
  Phase: 'configure',
330
- Message: `Existing environment files found (${envFiles.join(', ')}), preserving.`,
494
+ Message: `Existing environment files found (${envFiles.join(', ')}), preserving${patchMsg}.`,
331
495
  });
332
496
  }
333
497
  else {
@@ -347,6 +511,13 @@ ${newUserSection}
347
511
  }
348
512
  return { Written: filesWritten, Preserved: filesPreserved };
349
513
  }
514
+ /**
515
+ * Generate the content for an Angular `environment.ts` file.
516
+ *
517
+ * @param config - Fully resolved config.
518
+ * @param production - `true` for `environment.ts`, `false` for `environment.development.ts`.
519
+ * @returns TypeScript source code for the environment file.
520
+ */
350
521
  generateEnvironmentFile(config, production) {
351
522
  const authType = this.mapAuthType(config.AuthProvider);
352
523
  const clientId = config.AuthProviderValues?.ClientID ?? '';
@@ -375,9 +546,142 @@ ${newUserSection}
375
546
  };
376
547
  `;
377
548
  }
549
+ /**
550
+ * Reads ALL existing .env files and backfills auth-related values into
551
+ * the config object when they are missing. Merges non-empty values from
552
+ * all candidates, so if the root `.env` has empty auth but
553
+ * `apps/MJAPI/.env` has real credentials, those credentials are used.
554
+ */
555
+ async backfillAuthFromEnv(dir, config) {
556
+ const candidates = [
557
+ path.join(dir, '.env'),
558
+ path.join(dir, 'apps', 'MJAPI', '.env'),
559
+ path.join(dir, 'packages', 'MJAPI', '.env'),
560
+ ];
561
+ // Merge env vars from ALL existing .env files. Later files fill in
562
+ // values that earlier files left empty, so the most complete file wins.
563
+ const merged = {};
564
+ for (const candidate of candidates) {
565
+ if (await this.fileSystem.FileExists(candidate)) {
566
+ const content = await this.fileSystem.ReadText(candidate);
567
+ const vars = this.parseEnvFile(content);
568
+ for (const [key, value] of Object.entries(vars)) {
569
+ if (value && !merged[key]) {
570
+ merged[key] = value;
571
+ }
572
+ }
573
+ }
574
+ }
575
+ if (Object.keys(merged).length === 0)
576
+ return;
577
+ if (!config.AuthProviderValues) {
578
+ config.AuthProviderValues = {};
579
+ }
580
+ const clientId = merged['WEB_CLIENT_ID'] || merged['VITE_WEB_CLIENT_ID'] || '';
581
+ const tenantId = merged['TENANT_ID'] || merged['VITE_TENANT_ID'] || '';
582
+ const auth0Domain = merged['AUTH0_DOMAIN'] || '';
583
+ const auth0ClientId = merged['AUTH0_CLIENT_ID'] || '';
584
+ const graphqlPort = merged['GRAPHQL_PORT'] || '';
585
+ if (clientId && !config.AuthProviderValues.ClientID) {
586
+ config.AuthProviderValues.ClientID = clientId;
587
+ }
588
+ if (tenantId && !config.AuthProviderValues.TenantID) {
589
+ config.AuthProviderValues.TenantID = tenantId;
590
+ }
591
+ if (auth0Domain && !config.AuthProviderValues.Domain) {
592
+ config.AuthProviderValues.Domain = auth0Domain;
593
+ }
594
+ if (auth0ClientId && !config.AuthProviderValues.ClientID) {
595
+ config.AuthProviderValues.ClientID = auth0ClientId;
596
+ }
597
+ if (graphqlPort && !config.APIPort) {
598
+ config.APIPort = parseInt(graphqlPort, 10);
599
+ }
600
+ // Infer AuthProvider from env values if it was defaulted to 'none'
601
+ if (config.AuthProvider === 'none') {
602
+ if (tenantId && clientId) {
603
+ config.AuthProvider = 'entra';
604
+ }
605
+ else if (auth0Domain) {
606
+ config.AuthProvider = 'auth0';
607
+ }
608
+ }
609
+ }
610
+ /**
611
+ * Parses a simple .env file into key-value pairs.
612
+ * Handles `KEY=VALUE`, `KEY='VALUE'`, and `KEY="VALUE"` formats.
613
+ */
614
+ parseEnvFile(content) {
615
+ const result = {};
616
+ for (const line of content.split('\n')) {
617
+ const trimmed = line.trim();
618
+ if (!trimmed || trimmed.startsWith('#'))
619
+ continue;
620
+ const eqIndex = trimmed.indexOf('=');
621
+ if (eqIndex < 0)
622
+ continue;
623
+ const key = trimmed.slice(0, eqIndex).trim();
624
+ let value = trimmed.slice(eqIndex + 1).trim();
625
+ if ((value.startsWith("'") && value.endsWith("'")) ||
626
+ (value.startsWith('"') && value.endsWith('"'))) {
627
+ value = value.slice(1, -1);
628
+ }
629
+ result[key] = value;
630
+ }
631
+ return result;
632
+ }
633
+ /**
634
+ * Patches an existing Explorer environment file, filling in empty string
635
+ * values for auth/connection fields from the resolved config.
636
+ *
637
+ * @returns `true` if the file was modified.
638
+ */
639
+ async patchExplorerEnvironmentFile(filePath, config) {
640
+ let content = await this.fileSystem.ReadText(filePath);
641
+ const original = content;
642
+ const clientId = config.AuthProviderValues?.ClientID ?? '';
643
+ const tenantId = config.AuthProviderValues?.TenantID ?? '';
644
+ const authority = tenantId
645
+ ? `https://login.microsoftonline.com/${tenantId}`
646
+ : '';
647
+ const auth0Domain = config.AuthProviderValues?.Domain ?? '';
648
+ const apiPort = config.APIPort ?? 4000;
649
+ const explorerPort = config.ExplorerPort ?? 4200;
650
+ const authType = this.mapAuthType(config.AuthProvider);
651
+ // Map of field name → desired value. Only patch if the current value is empty.
652
+ const patches = {
653
+ GRAPHQL_URI: `http://localhost:${apiPort}/`,
654
+ GRAPHQL_WS_URI: `ws://localhost:${apiPort}/`,
655
+ REDIRECT_URI: `http://localhost:${explorerPort}`,
656
+ CLIENT_ID: clientId,
657
+ TENANT_ID: tenantId,
658
+ CLIENT_AUTHORITY: authority,
659
+ AUTH_TYPE: authType,
660
+ AUTH0_DOMAIN: auth0Domain,
661
+ AUTH0_CLIENTID: clientId,
662
+ };
663
+ for (const [field, value] of Object.entries(patches)) {
664
+ if (!value)
665
+ continue;
666
+ // Match: "FIELD": "" or "FIELD": '' or FIELD: "" or FIELD: ''
667
+ const emptyPattern = new RegExp(`(["']?${field}["']?\\s*[:=]\\s*)(?:["']{2}|["']\\s*["'])`);
668
+ if (emptyPattern.test(content)) {
669
+ content = content.replace(emptyPattern, `$1'${value}'`);
670
+ }
671
+ }
672
+ if (content !== original) {
673
+ await this.fileSystem.WriteText(filePath, content);
674
+ return true;
675
+ }
676
+ return false;
677
+ }
378
678
  // ---------------------------------------------------------------------------
379
679
  // Prompt helpers
380
680
  // ---------------------------------------------------------------------------
681
+ /**
682
+ * Emit a text input prompt and return the user's response (or the default
683
+ * value when in `--yes` mode).
684
+ */
381
685
  promptInput(emitter, id, message, defaultValue, yes) {
382
686
  if (yes)
383
687
  return Promise.resolve(defaultValue);
@@ -392,6 +696,10 @@ ${newUserSection}
392
696
  });
393
697
  });
394
698
  }
699
+ /**
700
+ * Emit a yes/no confirmation prompt and return the boolean result (or the
701
+ * default value when in `--yes` mode).
702
+ */
395
703
  promptConfirm(emitter, id, message, defaultValue, yes) {
396
704
  if (yes)
397
705
  return Promise.resolve(defaultValue);
@@ -408,6 +716,10 @@ ${newUserSection}
408
716
  });
409
717
  });
410
718
  }
719
+ /**
720
+ * Emit a select-from-list prompt and return the chosen value (or the
721
+ * default when in `--yes` mode).
722
+ */
411
723
  promptSelect(emitter, id, message, choices, defaultValue) {
412
724
  return new Promise((resolve) => {
413
725
  emitter.Emit('prompt', {
@@ -424,16 +736,51 @@ ${newUserSection}
424
736
  // ---------------------------------------------------------------------------
425
737
  // Helpers
426
738
  // ---------------------------------------------------------------------------
739
+ /**
740
+ * Map the user-facing auth provider name to the `AUTH_TYPE` string expected
741
+ * by the Angular environment config.
742
+ *
743
+ * `'none'` defaults to `'msal'` because the `MJEnvironmentConfig` type
744
+ * requires `AUTH_TYPE` to be `'msal' | 'auth0'`.
745
+ *
746
+ * **Important**: When `AuthProvider` is `'none'`, the Explorer will show a
747
+ * validation error because `AUTH_TYPE='msal'` requires `CLIENT_ID` and
748
+ * `TENANT_ID`. The caller should emit a warning when auth is unconfigured.
749
+ */
427
750
  mapAuthType(provider) {
428
751
  switch (provider) {
429
752
  case 'entra': return 'msal';
430
753
  case 'auth0': return 'auth0';
431
- // 'none' defaults to 'msal' because the MJEnvironmentConfig type
432
- // requires AUTH_TYPE to be 'msal' | 'auth0'. With an empty CLIENT_ID
433
- // the MSAL provider will simply skip authentication.
434
754
  case 'none': return 'msal';
435
755
  default: return 'msal';
436
756
  }
437
757
  }
758
+ /**
759
+ * Resolve the path to the MJAPI `.env` file. Checks both `packages/MJAPI/`
760
+ * (monorepo layout) and `apps/MJAPI/` (distribution layout).
761
+ */
762
+ async resolveMjapiEnvPath(dir) {
763
+ const candidates = [
764
+ path.join(dir, 'packages', 'MJAPI', '.env'),
765
+ path.join(dir, 'apps', 'MJAPI', '.env'),
766
+ ];
767
+ for (const candidate of candidates) {
768
+ if (await this.fileSystem.DirectoryExists(path.dirname(candidate))) {
769
+ return candidate;
770
+ }
771
+ }
772
+ // Fallback to packages layout
773
+ return candidates[0];
774
+ }
775
+ /**
776
+ * Generate a cryptographically random 256-bit key encoded as base64.
777
+ *
778
+ * Used for MJ's field-level encryption (`MJ_BASE_ENCRYPTION_KEY`).
779
+ *
780
+ * @returns A 44-character base64 string (32 bytes).
781
+ */
782
+ generateBaseEncryptionKey() {
783
+ return randomBytes(32).toString('base64');
784
+ }
438
785
  }
439
786
  //# sourceMappingURL=ConfigurePhase.js.map