@docupace/pipeline 1.0.7-alpha.7 → 1.0.7-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@docupace/pipeline",
3
- "version": "1.0.7-alpha.7",
3
+ "version": "1.0.7-alpha.9",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "type": "module",
7
7
  "bin": {
8
8
  "dp-changeset-cli": "src/changeset/cli.js",
9
- "dp-next-cli": "src/next/cli.js"
9
+ "dp-next-cli": "src/next/cli.js",
10
+ "dp-auth0-cli": "src/auth0/cli.js"
10
11
  },
11
12
  "keywords": [
12
13
  "bash"
@@ -15,6 +16,7 @@
15
16
  "license": "ISC",
16
17
  "dependencies": {
17
18
  "@changesets/cli": "^2.27.10",
19
+ "auth0-deploy-cli": "^7.24.3",
18
20
  "axios": "^1.7.9",
19
21
  "commander": "^12.1.0",
20
22
  "dotenv": "^16.4.7",
@@ -35,7 +37,7 @@
35
37
  },
36
38
  "scripts": {
37
39
  "test-deploy-core": "dp-next-cli deploy-core-pipeline dev template",
38
- "test-deploy-from-site": "dp-next-cli deploy-from-site --from-env qa --to-env qa --from-site rockefeller --to-site rockefeller --deploy-core true",
40
+ "test-deploy-from-site": "dp-next-cli deploy-from-site --from-env dev --to-env dev --from-site financialdev --to-site template --deploy-core true",
39
41
  "test-run-pipline": "dp-next-cli run-pipeline -r docupace-next-e2e -b master -p run-tests-qa"
40
42
  }
41
43
  }
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Command } from 'commander';
4
+ import {
5
+ configureFromSite
6
+ } from './configure.js';
7
+ import {
8
+ getVaultSecrets
9
+ } from './vault.js'
10
+
11
+ import dotenv from 'dotenv';
12
+
13
+ dotenv.config({ path: ['.env.pipeline.local', 'config/.env.pipeline.local'] });
14
+
15
+ const program = new Command();
16
+
17
+ program
18
+ .command('configureFromSite <fromSite> <toSite> <env> <deployUI> <deployGraphQLServer> <useNewDomain>')
19
+ .description('Configure the Auth0 tenants in env for the given site')
20
+ .action(async (fromSite, toSite, env, deployUI, deployGraphQLServer, useNewDomain) => {
21
+ await configureFromSite(fromSite, toSite, env, deployUI, deployGraphQLServer, useNewDomain);
22
+ });
23
+
24
+ program
25
+ .command('getVaultSecrets <vaultPath>')
26
+ .description('Get Secrets for Vault PATH')
27
+ .action(async (vaultPath) => {
28
+ await getVaultSecrets(vaultPath);
29
+ });
30
+
31
+ program.parse(process.argv);
@@ -0,0 +1,586 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import yaml from 'js-yaml';
4
+ import { $ } from 'zx';
5
+ import axios from 'axios';
6
+ import crypto from 'crypto';
7
+ import { deploy } from 'auth0-deploy-cli';
8
+
9
+ import {
10
+ cloneEnvRepository,
11
+ cloneRepository,
12
+ readDeployConfig,
13
+ pushDeployConfig
14
+ } from '../next/deploy.js';
15
+
16
+ import {
17
+ getVaultSecrets,
18
+ updateVaultSecrets
19
+ } from './vault.js';
20
+
21
+ import {
22
+ getVaultSecretsConfigs,
23
+ environmentConfig
24
+ } from '../next/config.js';
25
+
26
+ async function ensureDirectoryExists(dirPath) {
27
+ try {
28
+ await fs.promises.mkdir(dirPath, { recursive: true });
29
+ console.log(`Directory created or already exists: ${dirPath}`);
30
+ } catch (err) {
31
+ console.error(`Failed to create directory: ${err.message}`);
32
+ }
33
+ }
34
+
35
+ async function initializeAuth0Configuration({
36
+ initConfiguration,
37
+ auth0Domain,
38
+ auth0AuthToken,
39
+ coreApiIdentifier,
40
+ }) {
41
+ if (initConfiguration === "true") {
42
+ try {
43
+ // Create a new resource server in Auth0
44
+ console.log("Creating resource server in Auth0...");
45
+
46
+ const resourceServerResponse = await axios.post(
47
+ `https://${auth0Domain}/api/v2/resource-servers`,
48
+ {
49
+ name: "docupace-core",
50
+ identifier: `${coreApiIdentifier}`,
51
+ token_lifetime: 86400,
52
+ allow_offline_access: false,
53
+ signing_alg: "RS256",
54
+ skip_consent_for_verifiable_first_party_clients: true,
55
+ scopes: [],
56
+ },
57
+ {
58
+ headers: {
59
+ Authorization: `Bearer ${auth0AuthToken}`,
60
+ "Content-Type": "application/json",
61
+ },
62
+ }
63
+ );
64
+
65
+ const apiId = resourceServerResponse.data.id;
66
+ console.log(`API ID: ${apiId}`);
67
+
68
+ // Update tenant settings with the default audience
69
+ console.log("Updating tenant settings...");
70
+ await axios.patch(
71
+ `https://${auth0Domain}/api/v2/tenants/settings`,
72
+ {
73
+ default_audience: `${coreApiIdentifier}`,
74
+ },
75
+ {
76
+ headers: {
77
+ Authorization: `Bearer ${auth0AuthToken}`,
78
+ "Content-Type": "application/json",
79
+ },
80
+ }
81
+ );
82
+ console.log(`coreApiIdentifier => ${coreApiIdentifier}`)
83
+ console.log("Tenant settings updated successfully.");
84
+ } catch (error) {
85
+ console.error("Error during Auth0 configuration:", error.response?.data || error.message);
86
+ }
87
+ }
88
+ }
89
+
90
+ async function importAuth0Templates(directoryPath, auth0Domain, auth0ClientID, auth0ClientSecret) {
91
+ try {
92
+ const config = {
93
+ input_file: directoryPath,
94
+ config: {
95
+ AUTH0_DOMAIN: auth0Domain,
96
+ AUTH0_CLIENT_ID: auth0ClientID,
97
+ AUTH0_CLIENT_SECRET: auth0ClientSecret,
98
+ },
99
+ debug: true,
100
+ };
101
+
102
+ console.log('Starting Auth0 template import...');
103
+ await deploy(config);
104
+ console.log('Auth0 template import completed successfully!');
105
+ } catch (error) {
106
+ console.error('Error during Auth0 template import:', error.message);
107
+ process.exit(1); // Exit with an error code
108
+ }
109
+ }
110
+
111
+ async function updateJsonFile(filePath, updates) {
112
+ const content = await fs.promises.readFile(filePath, 'utf8');
113
+ const jsonContent = JSON.parse(content);
114
+ const updatedContent = JSON.stringify({...jsonContent, ...updates}, null, 2);
115
+ await fs.promises.writeFile(filePath, updatedContent);
116
+ }
117
+
118
+ async function replaceInFile(filePath, replacements) {
119
+ let content = await fs.promises.readFile(filePath, 'utf8');
120
+ for (const [search, replace] of replacements) {
121
+ content = content.replace(new RegExp(search, 'g'), replace);
122
+ }
123
+ await fs.promises.writeFile(filePath, content);
124
+ }
125
+
126
+ async function templateAuth0(siteUrl, coreApiContext, env, filePaths, deployUI, deployGraphQLServer, commonSecrets) {
127
+ try {
128
+ let uiAllowedCallbacksUrls,
129
+ uiAllowedLogoutUrls;
130
+ let graphqlAllowedCallbacksUrls,
131
+ graphqlAllowedLogoutUrls;
132
+
133
+ // Configure URLs based on environment
134
+ if (env === 'prd') {
135
+ uiAllowedCallbacksUrls = [`https://${siteUrl}/api/auth/callback`];
136
+ uiAllowedLogoutUrls = [`https://${siteUrl}`];
137
+
138
+ graphqlAllowedCallbacksUrls = [`https://${siteUrl}/api/graphql/callback`];
139
+ graphqlAllowedLogoutUrls = [`https://${siteUrl}/api/graphql/`];
140
+ } else {
141
+ uiAllowedCallbacksUrls = [
142
+ `https://${siteUrl}/api/auth/callback`,
143
+ `http://localhost:3000/api/auth/callback`,
144
+ ];
145
+ uiAllowedLogoutUrls = [
146
+ `https://${siteUrl}`,
147
+ `http://localhost:3000`,
148
+ ];
149
+
150
+ graphqlAllowedCallbacksUrls = [
151
+ `https://${siteUrl}/api/graphql/callback`,
152
+ `http://localhost:4000/api/graphql/callback`,
153
+ ];
154
+ graphqlAllowedLogoutUrls = [
155
+ `http://localhost:4000/api/graphql/`,
156
+ `https://${siteUrl}/api/graphql/`,
157
+ ];
158
+ }
159
+
160
+ const configureUI = deployUI === 'true';
161
+ if (configureUI) {
162
+ console.log('ui_allowed_callbacks_urls ->', uiAllowedCallbacksUrls);
163
+ console.log('ui_allowed_logout_urls ->', uiAllowedLogoutUrls);
164
+
165
+ await updateJsonFile(filePaths.uiJson, {
166
+ callbacks: uiAllowedCallbacksUrls,
167
+ allowed_logout_urls: uiAllowedLogoutUrls,
168
+ });
169
+ console.log('Updated URLs for main UI...');
170
+ } else {
171
+ await fs.promises.unlink(filePaths.uiJson);
172
+ await updateJsonFile(filePaths.databaseJson, {
173
+ enabled_clients: (content) => content.enabled_clients.filter((client) => client !== 'docupace-ui-main'),
174
+ });
175
+ console.log("Removed 'docupace-ui-main' from enabled_clients in database.json");
176
+ }
177
+
178
+ const configureGraphqlServer = deployGraphQLServer === 'true';
179
+ if (configureGraphqlServer) {
180
+ console.log('graphql_allowed_callbacks_urls ->', graphqlAllowedCallbacksUrls);
181
+ console.log('graphql_allowed_logout_urls ->', graphqlAllowedLogoutUrls);
182
+
183
+ await updateJsonFile(filePaths.graphqlJson, {
184
+ callbacks: graphqlAllowedCallbacksUrls,
185
+ allowed_logout_urls: graphqlAllowedLogoutUrls,
186
+ });
187
+ console.log('Updated URLs for GraphQL server...');
188
+ } else {
189
+ await fs.promises.unlink(filePaths.graphqlJson);
190
+ await updateJsonFile(filePaths.databaseJson, {
191
+ enabled_clients: (content) => content.enabled_clients.filter((client) => client !== 'docupace-graphql'),
192
+ });
193
+ console.log("Removed 'docupace-graphql' from enabled_clients in database.json");
194
+ }
195
+
196
+ // TWILIO configuration
197
+ await replaceInFile(filePaths.twilioJson, [
198
+ ['twilioauthtokenplaceholder', commonSecrets.TWILIO_AUTH_TOKEN],
199
+ ['twiliosidplaceholder', commonSecrets.TWILIO_SID],
200
+ ['twiliofromplaceholder', commonSecrets.TWILIO_FROM_NUMBER],
201
+ ]);
202
+
203
+ console.log('TWILIO configuration updated...');
204
+
205
+ // Database configuration
206
+ await replaceInFile(filePaths.databaseLoginJs, [
207
+ ['"${docupaceHost}"', `"${siteUrl}"`],
208
+ ['"${docupaceContext}"', `"${coreApiContext}"`],
209
+ ]);
210
+
211
+ // MFA configuration
212
+ // if (process.env.AUTH0_MFA === 'ENABLE') {
213
+ // console.log('AUTH0 MFA is enabled');
214
+ // await execAsync('rsync -av ./auth0template/templateMFA/ ./auth0template/template/');
215
+ // } else if (process.env.AUTH0_MFA === 'DISABLE') {
216
+ // console.log('AUTH0 MFA is disabled');
217
+ // await execAsync('rsync -av ./auth0template/templateNoMFA/ ./auth0template/template/');
218
+ // }
219
+
220
+ console.log('Template configuration completed.');
221
+ } catch (err) {
222
+ console.error('Error configuring Auth0 templates:', err);
223
+ }
224
+ }
225
+
226
+ async function getAuth0AuthToken(auth0Domain, clientId, clientSecret) {
227
+ try {
228
+ const response = await axios.post(`https://${auth0Domain}/oauth/token`, {
229
+ client_id: clientId,
230
+ client_secret: clientSecret,
231
+ audience: `https://${auth0Domain}/api/v2/`,
232
+ grant_type: 'client_credentials',
233
+ }, {
234
+ headers: {
235
+ 'Content-Type': 'application/json',
236
+ },
237
+ });
238
+
239
+ const authToken = response.data.access_token;
240
+ // console.log("Auth0 Auth Token:", authToken);
241
+ return authToken;
242
+ } catch (error) {
243
+ console.error("Error fetching Auth0 token:", error.response ? error.response.data : error.message);
244
+ }
245
+ }
246
+
247
+ async function configureUI(siteHost, coreURL, docupaceHost, site, env, useNewDomain, auth0Domain, auth0ClientId, auth0ClientSecret, auth0Token, vaultSiteSecretsPath, imageTag, repoPath) {
248
+ console.log(`Configuring UI for site: ${site} Host: ${siteHost} in env: ${env}`);
249
+
250
+ try {
251
+ const auth0Response = await axios.get(`https://${auth0Domain}/api/v2/clients`, {
252
+ headers: {authorization: `Bearer ${auth0Token}`},
253
+ });
254
+
255
+ const uiClient = auth0Response.data.find(client => client.name === "docupace-ui-main");
256
+ const uiAuth0ClientId = uiClient.client_id;
257
+ const uiAuth0ClientSecret = uiClient.client_secret;
258
+
259
+ // Generate Auth0 Secret
260
+ const uiAuth0Secret = crypto.randomBytes(48).toString('base64').replace(/[^a-zA-Z0-9]/g, '');
261
+
262
+ // Prepare data payload
263
+ console.log("Preparing Vault UI data payload...");
264
+ const uiSecretData = JSON.stringify({
265
+ data: {
266
+ AUTH0_CLIENT_ID: uiAuth0ClientId,
267
+ AUTH0_CLIENT_SECRET: uiAuth0ClientSecret,
268
+ AUTH0_SECRET: uiAuth0Secret,
269
+ },
270
+ });
271
+
272
+ await updateVaultSecrets(vaultSiteSecretsPath, uiSecretData);
273
+
274
+ // Prepare ui.app.yaml
275
+ const uiAppYaml = `
276
+ repo: docupace-ui-main
277
+ revision: master
278
+ `.trim();
279
+
280
+ // Prepare ui.values.yaml
281
+ const uiValuesYaml = `
282
+ uiMain:
283
+ auth0BaseUrl: https://${siteHost}
284
+ auth0IssuerBaseUrl: https://${auth0Domain}
285
+ auth0ClientId: vault:secret/data/${site}/ui/config#AUTH0_CLIENT_ID
286
+ graphqlClientUrl: https://${siteHost}/api/graphql
287
+ graphqlServerUrl: https://${siteHost}/api/graphql
288
+ connectUrl: https://${siteHost}
289
+ coreUrl: https://${coreURL}
290
+ env:
291
+ AUTH0_CLIENT_SECRET: vault:secret/data/${site}/ui/config#AUTH0_CLIENT_SECRET
292
+ AUTH0_SECRET: vault:secret/data/${site}/ui/config#AUTH0_SECRET
293
+ image:
294
+ repository: registry.paperout.com/docupace-ui-main-dev-docker-local/docupace-ui-main
295
+ tag: ${imageTag}
296
+ imagePullSecrets:
297
+ - name: jf-artifactory
298
+ ingress:
299
+ enabled: true
300
+ className: nginx
301
+ annotations:
302
+ external-dns.alpha.kubernetes.io/hostname: ${siteHost}
303
+ external-dns.alpha.kubernetes.io/zone: public
304
+ cert-manager.io/cluster-issuer: letsencrypt
305
+ nginx.ingress.kubernetes.io/proxy-buffer-size: 128k
306
+ hosts:
307
+ - host: ${siteHost}
308
+ paths:
309
+ - path: /
310
+ pathType: Prefix
311
+ tls:
312
+ - hosts:
313
+ - ${siteHost}
314
+ secretName: dp-next-ui-cert
315
+ externalConnectIngress:
316
+ enabled: ${useNewDomain}
317
+ className: nginx
318
+ annotations:
319
+ cert-manager.io/cluster-issuer: letsencrypt
320
+ external-dns.alpha.kubernetes.io/hostname: ${siteHost}
321
+ external-dns.alpha.kubernetes.io/zone: public
322
+ nginx.ingress.kubernetes.io/backend-protocol: HTTPS
323
+ nginx.ingress.kubernetes.io/configuration-snippet: |
324
+ proxy_set_header Host ${siteHost};
325
+ nginx.ingress.kubernetes.io/proxy-buffer-size: 8k
326
+ hosts:
327
+ - host: ${siteHost}
328
+ paths:
329
+ - path: /core
330
+ - path: /core_b2b
331
+ - path: /core_reports
332
+ - path: /corerealm
333
+ - path: /connect
334
+ - path: /webstart
335
+ - path: /core_ws
336
+ - path: /core_docupload
337
+ - path: /core_ariws
338
+ - path: /core_restws
339
+ - path: /core_webdav
340
+ tls:
341
+ - hosts:
342
+ - ${siteHost}
343
+ secretName: dp-next-ui-cert
344
+ externalConnectService:
345
+ enabled: ${useNewDomain}
346
+ name: external-connect
347
+ domain: ${docupaceHost}
348
+ `.trim();
349
+
350
+ // Write configuration files
351
+ console.log("Writing configuration files...");
352
+ await ensureDirectoryExists(path.resolve(`${repoPath}/dp/${site}`));
353
+
354
+ await fs.writeFile(`${repoPath}/dp/${site}/ui.app.yaml`, uiAppYaml, (err) => {
355
+ if (err) {
356
+ console.error("Failed to write the file:", err);
357
+ } else {
358
+ console.log("File written successfully.");
359
+ }
360
+ });
361
+
362
+ await fs.writeFile(`${repoPath}/dp/${site}/ui.values.yaml`, uiValuesYaml, (err) => {
363
+ if (err) {
364
+ console.error("Failed to write the file:", err);
365
+ } else {
366
+ console.log("File written successfully.");
367
+ }
368
+ });
369
+ console.log("Done!");
370
+ } catch (error) {
371
+ console.error("Error configuring UI:", error);
372
+ }
373
+ }
374
+
375
+ async function configureGraphQLServer(siteHost, coreURL, docupaceHost, site, env, auth0Domain, auth0ClientId, auth0ClientSecret, auth0Token, vaultSiteSecretsPath, imageTag, shortTemplateLatestCommitId, repoPath, commonSecrets) {
376
+ console.log(`Configuring GraphQL Server for site: ${site} Host: ${siteHost} in env: ${env}`);
377
+
378
+ try {
379
+ const auth0Response = await axios.get(`https://${auth0Domain}/api/v2/clients`, {
380
+ headers: {authorization: `Bearer ${auth0Token}`},
381
+ });
382
+
383
+ const graphQLServerClient = auth0Response.data.find(client => client.name === "docupace-graphql");
384
+ const graphQLServerClientCredentials = auth0Response.data.find(client => client.name === "docupace-graphql-client-credentials");
385
+
386
+ const graphQLServerAuth0ClientId = graphQLServerClient.client_id;
387
+ const graphQLServerAuth0ClientSecret = graphQLServerClient.client_secret;
388
+
389
+ const graphQLServerCCAuth0ClientId = graphQLServerClientCredentials.client_id;
390
+ const graphQLServerCCAuth0ClientSecret = graphQLServerClientCredentials.client_secret;
391
+
392
+ // Prepare data payload
393
+ console.log("Preparing Vault GraphQL Server data payload...");
394
+ const graphQLServerSecretData = JSON.stringify({
395
+ data: {
396
+ AUTH0_CLIENT_ID: graphQLServerAuth0ClientId,
397
+ AUTH0_CLIENT_SECRET: graphQLServerAuth0ClientSecret,
398
+ AUTH0_CC_CLIENT_ID: graphQLServerCCAuth0ClientId,
399
+ AUTH0_CC_CLIENT_SECRET: graphQLServerCCAuth0ClientSecret,
400
+ CORE_PASSWORD: commonSecrets.CORE_PASSWORD,
401
+ REMOTE_CONFIG_PATH: commonSecrets.REMOTE_CONFIG_PATH,
402
+ STANDARD_CONFIG_REMOTE_PATH: commonSecrets.STANDARD_CONFIG_REMOTE_PATH,
403
+ },
404
+ });
405
+
406
+ await updateVaultSecrets(vaultSiteSecretsPath, graphQLServerSecretData);
407
+
408
+ // Prepare ui.app.yaml
409
+ const graphQLServerAppYaml = `
410
+ repo: docupace-graphql-server
411
+ revision: master
412
+ `.trim();
413
+
414
+ // Prepare ui.values.yaml
415
+ const graphQLServerValuesYaml = `
416
+ graphqlServer:
417
+ auth0Domain: https://${auth0Domain}
418
+ auth0ClientId: vault:secret/data/${site}/graphql-server/config#AUTH0_CLIENT_ID
419
+ auth0Audience: ${commonSecrets.CORE_API_IDENTIFIER}
420
+ baseUrl: https://${siteHost}/api/graphql
421
+ coreUrl: https://${coreURL}
422
+ integrationHubUrl: "https://${commonSecrets.INTEGRATION_HUB_URL}"
423
+ standardConfigRemoteBranch: ${shortTemplateLatestCommitId}
424
+ apiLevel: "2"
425
+ env:
426
+ AUTH0_CLIENT_SECRET: vault:secret/data/${site}/graphql-server/config#AUTH0_CLIENT_SECRET
427
+ CORE_PASSWORD: vault:secret/data/common/config#CORE_PASSWORD
428
+ REMOTE_CONFIG_PATH: vault:secret/data/common/config#REMOTE_CONFIG_PATH
429
+ STANDARD_CONFIG_REMOTE_PATH: vault:secret/data/common/config#STANDARD_CONFIG_REMOTE_PATH
430
+ AUTH0_CC_CLIENT_ID: vault:secret/data/${site}/graphql-server/config#AUTH0_CC_CLIENT_ID
431
+ AUTH0_CC_CLIENT_SECRET: vault:secret/data/${site}/graphql-server/config#AUTH0_CC_CLIENT_SECRET
432
+ image:
433
+ repository: registry.paperout.com/docupace-graphql-server-dev-docker-local/docupace-graphql-server
434
+ tag: ${imageTag}
435
+ imagePullSecrets:
436
+ - name: jf-artifactory
437
+ ingress:
438
+ annotations:
439
+ external-dns.alpha.kubernetes.io/hostname: ${siteHost}
440
+ external-dns.alpha.kubernetes.io/zone: public
441
+ cert-manager.io/cluster-issuer: letsencrypt
442
+ nginx.ingress.kubernetes.io/proxy-buffer-size: 128k
443
+ enabled: true
444
+ className: nginx
445
+ hosts:
446
+ - host: ${siteHost}
447
+ paths:
448
+ - path: /api/graphql
449
+ pathType: Prefix
450
+ tls:
451
+ - hosts:
452
+ - ${siteHost}
453
+ secretName: dp-next-ui-cert
454
+ `.trim();
455
+
456
+ // Write configuration files
457
+ console.log("Writing ArgoCD GraphQL Server configuration files...");
458
+ await ensureDirectoryExists(path.resolve(`${repoPath}/dp/${site}`));
459
+
460
+ await fs.writeFile(`${repoPath}/dp/${site}/graphql-server.app.yaml`, graphQLServerAppYaml, (err) => {
461
+ if (err) {
462
+ console.error("Failed to write the file:", err);
463
+ } else {
464
+ console.log("File written successfully.");
465
+ }
466
+ });
467
+
468
+ await fs.writeFile(`${repoPath}/dp/${site}/graphql-server.values.yaml`, graphQLServerValuesYaml, (err) => {
469
+ if (err) {
470
+ console.error("Failed to write the file:", err);
471
+ } else {
472
+ console.log("File written successfully.");
473
+ }
474
+ });
475
+ console.log("Done!");
476
+ } catch (error) {
477
+ console.error("Error configuring GraphQL Server:", error);
478
+ }
479
+ }
480
+
481
+ export async function configureFromSite(fromSite, toSite, env, deployUI, deployGraphQLServer, useNewDomain) {
482
+ console.log(`Configuring Auth0 tenants and ArgoCD apps for site: ${toSite} in env: ${env} from site: ${fromSite}`);
483
+ // Common Secrets
484
+ const commonSecretsPath = getVaultSecretsConfigs(toSite).commonSecretsPath;
485
+ console.log(`commonSecretsPath => ${commonSecretsPath}`)
486
+ const commonSecrets = await getVaultSecrets(commonSecretsPath);
487
+
488
+ // Site Common Secrets
489
+ const siteCommonSecretsPath = getVaultSecretsConfigs(toSite).siteCommonSecretsPath;
490
+ console.log(`siteCommonSecretsPath => ${siteCommonSecretsPath}`)
491
+ const siteCommonSecrets = await getVaultSecrets(siteCommonSecretsPath);
492
+
493
+ const auth0Domain = `docupace-${env}-${toSite}.us.auth0.com`
494
+ const auth0ClientId = siteCommonSecrets.AUTH0_CLIENT_ID;
495
+ const auth0ClientSecret = siteCommonSecrets.AUTH0_CLIENT_SECRET;
496
+ const auth0Token = await getAuth0AuthToken(auth0Domain, auth0ClientId, auth0ClientSecret);
497
+
498
+ // UI app
499
+ const uiSecretsPath = getVaultSecretsConfigs(toSite).uiSecretsPath;
500
+ console.log(`uiSecretsPath => ${uiSecretsPath}`)
501
+
502
+ // GraphQL-Server app
503
+ const graphqlSecretsPath = getVaultSecretsConfigs(toSite).graphqlServerSecretsPath;
504
+ console.log(`graphqlSecretsPath => ${graphqlSecretsPath}`)
505
+
506
+ // Clone repositories
507
+ const repoPath = await cloneEnvRepository(env);
508
+ const templateRepoPath = await cloneRepository('template');
509
+ const auth0RepoPath = await cloneRepository('auth0-site-setup');
510
+
511
+ // Read deploy configs
512
+ const { deployConfig: deployUIConfig } = await readDeployConfig('ui', env, fromSite);
513
+ const uiImageTag = deployUIConfig.image.tag;
514
+
515
+ const { deployConfig: deployGraphQLServerConfig} = await readDeployConfig('graphql-server', env, fromSite);
516
+ const graphqlImageTag = deployGraphQLServerConfig.image.tag;
517
+
518
+ // File paths
519
+ const filePaths = {
520
+ clientJson: './auth0-site-setup/template/clients/docupace-connect.json',
521
+ databaseLoginJs: './auth0-site-setup/template/database-connections/docupace/login.js',
522
+ loginHtml: './auth0-site-setup/template/pages/login.html',
523
+ graphqlJson: './auth0-site-setup/template/clients/docupace-graphql.json',
524
+ uiJson: './auth0-site-setup/template/clients/docupace-ui-main.json',
525
+ databaseJson: './auth0-site-setup/template/database-connections/docupace/database.json',
526
+ twilioJson: './auth0-site-setup/template/guardian/providers/sms-twilio.json',
527
+ };
528
+
529
+ console.log(`Copying Latest UI Image Tag: ${deployUIConfig.image.tag} from site: ${fromSite} to site: ${toSite}`);
530
+ console.log(`Copying Latest GraphQL Server Image Tag: ${deployGraphQLServerConfig.image.tag} from site: ${fromSite} to site: ${toSite}`);
531
+
532
+ // Get latest commit ID from TEMPLATE_DIR
533
+ let shortCommitId;
534
+ try {
535
+ process.chdir(templateRepoPath);
536
+ shortCommitId = (await $`git log --pretty=format:'%h' -n 1`).stdout.trim();
537
+
538
+ if (!shortCommitId) {
539
+ console.error("Error: Latest Template commit ID is empty or not set");
540
+ }
541
+
542
+ console.log(`Latest Template commit ID: ${shortCommitId}`);
543
+ process.chdir('..'); // Return to the parent directory
544
+ } catch (error) {
545
+ console.error("Error retrieving the latest template commit ID:", error.message);
546
+ }
547
+
548
+ const envConfig = environmentConfig[env];
549
+
550
+ let CORE_URL,
551
+ SITE_HOST,
552
+ CORE_API_CONTEXT,
553
+ CONNECT_URL,
554
+ DOCUPACE_HOST;
555
+ if (useNewDomain) {
556
+ const newUrl = envConfig.newUrl(toSite);
557
+ CORE_URL = `${newUrl}/core`;
558
+ SITE_HOST = newUrl;
559
+ CORE_API_CONTEXT = "core";
560
+ CONNECT_URL = `${newUrl}/connect`;
561
+ DOCUPACE_HOST = envConfig.docupaceHost();
562
+ } else {
563
+ const oldUrl = envConfig.oldUrl(toSite);
564
+ CORE_URL = oldUrl;
565
+ SITE_HOST = oldUrl;
566
+ CORE_API_CONTEXT = toSite;
567
+ CONNECT_URL = `${oldUrl}_ui`;
568
+ }
569
+
570
+ await templateAuth0(SITE_HOST, CORE_API_CONTEXT, env, filePaths, deployUI, deployGraphQLServer, commonSecrets);
571
+ await importAuth0Templates('./auth0-site-setup/template', auth0Domain, auth0ClientId, auth0ClientSecret);
572
+
573
+ if (deployUI === 'true') {
574
+ await configureUI(SITE_HOST, CORE_URL, DOCUPACE_HOST, toSite, env, useNewDomain, auth0Domain, auth0ClientId, auth0ClientSecret, auth0Token, uiSecretsPath, uiImageTag, repoPath);
575
+ }
576
+
577
+ await configureGraphQLServer(SITE_HOST, CORE_URL, DOCUPACE_HOST, toSite, env, auth0Domain, auth0ClientId, auth0ClientSecret, auth0Token, graphqlSecretsPath, graphqlImageTag, shortCommitId, repoPath, commonSecrets);
578
+ await pushDeployConfig(repoPath, `Config update for ${toSite} from ${fromSite} with UI: ${uiImageTag} and GraphQL: ${graphqlImageTag}`);
579
+
580
+ await initializeAuth0Configuration({
581
+ initConfiguration: "true",
582
+ auth0Domain: auth0Domain,
583
+ auth0AuthToken: auth0Token,
584
+ coreApiIdentifier: commonSecrets.CORE_API_IDENTIFIER,
585
+ });
586
+ }
@@ -0,0 +1,107 @@
1
+ import axios from 'axios';
2
+
3
+ /**
4
+ * Fetch secrets from Vault.
5
+ * @param {string} vaultPath - The path in Vault to fetch secrets from.
6
+ * @returns {Promise<Object>} - The secret data as a JSON object.
7
+ */
8
+ export async function getVaultSecrets(vaultPath) {
9
+ if (!vaultPath) {
10
+ console.error("Error: VAULT_PATH is required.");
11
+ throw new Error("VAULT_PATH is required.");
12
+ }
13
+
14
+ const vaultToken = process.env.VAULT_TOKEN;
15
+ const vaultAddr = process.env.VAULT_ADDR;
16
+
17
+ if (!vaultToken || !vaultAddr) {
18
+ console.error("Error: VAULT_TOKEN and VAULT_ADDR must be set.");
19
+ throw new Error("VAULT_TOKEN and VAULT_ADDR must be set.");
20
+ }
21
+
22
+ try {
23
+ // Disable SSL verification globally by setting environment variable
24
+ if (process.env.VAULT_SKIP_VERIFY === 'true') {
25
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
26
+ }
27
+
28
+ // Fetch the secret from Vault
29
+ const response = await axios.get(`${vaultAddr}/v1/${vaultPath}`, {
30
+ headers: {
31
+ 'X-Vault-Token': vaultToken,
32
+ },
33
+ });
34
+
35
+ // Validate the response contains JSON data
36
+ const data = response.data;
37
+ if (data && typeof data === 'object') {
38
+ // console.log(`Secrets fetched successfully from Vault at ${JSON.stringify(data.data.data)})`);
39
+ return data.data.data;
40
+ } else {
41
+ console.error("Error: Invalid JSON received from Vault.");
42
+ throw new Error("Invalid JSON received from Vault.");
43
+ }
44
+ } catch (error) {
45
+ if (error.response) {
46
+ console.error(
47
+ `Error: Failed to connect to Vault server at ${vaultAddr}. Response: ${error.response.status} ${error.response.statusText}`
48
+ );
49
+ } else {
50
+ console.error(`Error: ${error.message}`);
51
+ }
52
+ // throw error;
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Update a secret in Vault.
58
+ * @param {string} vaultPath - The path in Vault where the secret should be updated.
59
+ * @param {Object} secretData - The secret data to be stored (as a JSON object).
60
+ * @returns {Promise<Object>} - The response from Vault as a JSON object.
61
+ */
62
+ export async function updateVaultSecrets(vaultPath, secretData) {
63
+ if (!vaultPath || !secretData) {
64
+ console.error("Usage: updateVaultSecret(vaultPath, secretData)");
65
+ throw new Error("Both vaultPath and secretData are required.");
66
+ }
67
+
68
+ const vaultToken = process.env.VAULT_TOKEN;
69
+ const vaultAddr = process.env.VAULT_ADDR;
70
+
71
+ if (!vaultToken || !vaultAddr) {
72
+ console.error("Error: VAULT_TOKEN and VAULT_ADDR must be set.");
73
+ throw new Error("VAULT_TOKEN and VAULT_ADDR must be set.");
74
+ }
75
+
76
+ try {
77
+ // Disable SSL verification globally if VAULT_SKIP_VERIFY is set
78
+ if (process.env.VAULT_SKIP_VERIFY === 'true') {
79
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
80
+ }
81
+
82
+ // Make the POST request to update the Vault secret
83
+ const response = await axios.post(
84
+ `${vaultAddr}/v1/${vaultPath}`,
85
+ secretData,
86
+ {
87
+ headers: {
88
+ 'X-Vault-Token': vaultToken,
89
+ 'Content-Type': 'application/json',
90
+ },
91
+ }
92
+ );
93
+
94
+ // Return the response from Vault
95
+ console.log(response.data);
96
+ return response.data;
97
+ } catch (error) {
98
+ if (error.response) {
99
+ console.error(
100
+ `Error: Failed to update secret at ${vaultPath}. Response: ${error.response.status} ${error.response.statusText}`
101
+ );
102
+ } else {
103
+ console.error(`Error: ${error.message}`);
104
+ }
105
+ // throw error;
106
+ }
107
+ }
package/src/next/cli.js CHANGED
@@ -15,7 +15,7 @@ const program = new Command();
15
15
 
16
16
  // GIT SHA computation
17
17
  import { $ } from 'zx';
18
- import {deployConnect, deployCore} from './jenkins.js';
18
+ import { deployCore } from './jenkins.js';
19
19
  import { runPipeline } from './pipline.js';
20
20
  const GIT_SHA = (await $`git log --pretty=format:'%h' -n 1`).stdout.trim();
21
21
 
@@ -69,15 +69,6 @@ program
69
69
  await deployCore(env, site, options.liquibase, options.branch);
70
70
  });
71
71
 
72
- program
73
- .command('deploy-connect <env> <site>')
74
- .description('Deploy Core')
75
- .option('-l, --liquibase <liquibase>', 'Application name', 'true')
76
- .option('-b, --branch <branch>', 'Branch', 'master')
77
- .action(async (env, site, options) => {
78
- await deployConnect(env, site, options.liquibase, options.branch);
79
- });
80
-
81
72
  program
82
73
  .command('deploy-core-pipeline <env> <site>')
83
74
  .description('Deploy Core')
@@ -2,25 +2,29 @@ export const environments = ['dev', 'qa', 'uat', 'stage', 'prod'];
2
2
 
3
3
  export const environmentConfig = {
4
4
  dev: {
5
- newUrl: (site) => `https://${site}.dev.dpai.tech`,
5
+ newUrl: (site) => `${site}.dev.dpai.tech`,
6
6
  oldUrl: (site) => `https://www.dev.docupaceinc.com/${site}`,
7
+ docupaceHost: () => 'www.dev.docupaceinc.com',
7
8
  },
8
9
  qa: {
9
- newUrl: (site) => `https://${site}.qa.dpai.tech`,
10
+ newUrl: (site) => `${site}.qa.dpai.tech`,
10
11
  oldUrl: (site) => `https://www.preprod.docupaceinc.com/${site}`,
12
+ docupaceHost: () => 'www.preprod.docupaceinc.com',
11
13
  },
12
14
  uat: {
13
- newUrl: (site) => `https://${site}.qa.dpai.tech`,
15
+ newUrl: (site) => `${site}.qa.dpai.tech`,
14
16
  oldUrl: (site) => `https://www2.paperout.com/${site}_uat`,
17
+ docupaceHost: () => 'www2.paperout.com',
15
18
  },
16
19
  stage: {
17
- newUrl: (site) => `https://${site}.stage.dpai.tech`,
20
+ newUrl: (site) => `${site}.stage.dpai.tech`,
18
21
  oldUrl: (site) => `https://www2.paperout.com/${site}_staging`,
22
+ docupaceHost: () => 'www2.paperout.com',
19
23
  },
20
-
21
24
  prod: {
22
- newUrl: (site) => `https://${site}.dpai.tech`,
25
+ newUrl: (site) => `${site}.dpai.tech`,
23
26
  oldUrl: (site) => `https://www2.paperout.com/${site}`,
27
+ docupaceHost: () => 'www2.paperout.com',
24
28
  },
25
29
  };
26
30
 
@@ -65,8 +69,16 @@ export const getBitbucketInfo = () => {
65
69
 
66
70
  export const getRepUrl = (repoName) => {
67
71
  const { username, password, workspace } = getBitbucketInfo();
68
- const repoUrl = `https://${username}:${password}@bitbucket.org/${workspace}/${repoName}.git`;
69
- return repoUrl;
72
+ return `https://${username}:${password}@bitbucket.org/${workspace}/${repoName}.git`;
70
73
  };
71
74
 
72
75
  export const jfRegistryUrl = 'registry.paperout.com';
76
+
77
+ export const getVaultSecretsConfigs = (site) => {
78
+ return {
79
+ commonSecretsPath: 'secret/data/common/config',
80
+ siteCommonSecretsPath: `secret/data/${site}/common/config`,
81
+ graphqlServerSecretsPath: `secret/data/${site}/graphql-server/config`,
82
+ uiSecretsPath: `secret/data/${site}/ui/config`
83
+ }
84
+ };
@@ -22,11 +22,40 @@ function getRepoLocalPath(env) {
22
22
  return { repoPath, repoName };
23
23
  }
24
24
 
25
- async function cloneEnvRepository(env) {
25
+ function getRepoLocalPathByRepoSlug(repoSlug) {
26
+ const repoName = `${repoSlug}`;
27
+ const repoPath = path.join(process.cwd(), repoName);
28
+ return { repoPath, repoName };
29
+ }
30
+
31
+ function cleanUpRepoPath(repoPath) {
32
+ // Check and handle repo directory
33
+ if (fs.existsSync(repoPath)) {
34
+ console.log(`${repoPath} directory exists. Removing it...`);
35
+ fs.rmSync(repoPath, {
36
+ recursive: true,
37
+ force: true
38
+ });
39
+ }
40
+ }
41
+
42
+ export async function cloneEnvRepository(env) {
26
43
  const { repoPath, repoName } = getRepoLocalPath(env);
27
44
  const repoUrl = getRepUrl(repoName);
28
45
  console.log(`Cloning repository: ${repoName}`);
29
- await $`git clone ${repoUrl}`;
46
+ await $`git clone --depth 1 ${repoUrl}`;
47
+ console.log(`Repository cloned to: ${repoPath}`);
48
+ return repoPath;
49
+ }
50
+
51
+ export async function cloneRepository(repoSlug) {
52
+ const { repoPath, repoName } = getRepoLocalPathByRepoSlug(repoSlug);
53
+ const repoUrl = getRepUrl(repoName);
54
+
55
+ await cleanUpRepoPath(repoPath)
56
+
57
+ console.log(`Cloning repository: ${repoName}`);
58
+ await $`git clone --depth 1 ${repoUrl}`;
30
59
  console.log(`Repository cloned to: ${repoPath}`);
31
60
  return repoPath;
32
61
  }
@@ -41,7 +70,7 @@ function getConfigPath(application, env, site) {
41
70
  return { repoPath, deployConfigFilePath };
42
71
  }
43
72
 
44
- async function readDeployConfig(application, env, site) {
73
+ export async function readDeployConfig(application, env, site) {
45
74
  const { deployConfigFilePath } = getConfigPath(application, env, site);
46
75
 
47
76
  let deployConfig;
@@ -244,9 +273,7 @@ export async function deployFromSite(
244
273
  ) {
245
274
  if (isDeployCore === 'true') {
246
275
  const branchName = await getCoreBranchName(fromEnv, fromSite);
247
-
248
- const coreEnv = toEnv == 'qa' ? 'preprod' : toEnv;
249
- await deployCore(coreEnv, toSite, 'true', branchName);
276
+ await deployCore(toEnv, toSite, 'true', branchName);
250
277
 
251
278
  // To be added back when splitting between on prem and in cloud
252
279
  /*await runPipeline('site-deploy', 'deploy-core', 'main', {
@@ -1,14 +1,9 @@
1
1
  import axios from 'axios';
2
2
 
3
- const CORE_JENKINS_URL = 'http://devops.corp.docupace.com';
4
- const CORE_JOB_NAME = 'auto-deploy-site';
5
- const CORE_USERNAME = process.env.CORE_JENKINS_USERNAME;
6
- const CORE_API_TOKEN = process.env.CORE_JENKINS_API_TOKEN;
7
-
8
- const CONNECT_JENKINS_URL = 'http://usdoc-s-buildui.corp.docupace.com/jenkins';
9
- const CONNECT_JOB_NAME = 'docupace_build_and_run_site_v2';
10
- const CONNECT_USERNAME = process.env.CONNECT_JENKINS_USERNAME;
11
- const CONNECT_API_TOKEN = process.env.CONNECT_JENKINS_API_TOKEN;
3
+ const JENKINS_URL = 'http://devops.corp.docupace.com';
4
+ const JOB_NAME = 'auto-deploy-site';
5
+ const USERNAME = process.env.CORE_JENKINS_USERNAME;
6
+ const API_TOKEN = process.env.CORE_JENKINS_API_TOKEN;
12
7
 
13
8
  export async function deployCore(env, site, liquibase, gitBranch) {
14
9
  const parameters = {
@@ -18,43 +13,14 @@ export async function deployCore(env, site, liquibase, gitBranch) {
18
13
  gitBranch,
19
14
  };
20
15
 
21
- return callJenkinsJob({
22
- jenkinsUrl: CORE_JENKINS_URL,
23
- jobName: CORE_JOB_NAME,
24
- auth: { username: CORE_USERNAME, password: CORE_API_TOKEN },
25
- parameters,
26
- });
27
- }
28
-
29
- export async function deployConnect(env, site, liquibase, branch) {
30
- const parameters = {
31
- BUILD_ENVIRONMENT: env,
32
- BUILD_SITE: site,
33
- RUN_LIQUIBASE: liquibase,
34
- };
35
-
36
- return callJenkinsJob({
37
- jenkinsUrl: CONNECT_JENKINS_URL,
38
- jobName: CONNECT_JOB_NAME,
39
- auth: { username: CONNECT_USERNAME, password: CONNECT_API_TOKEN },
40
- parameters,
41
- });
42
- }
43
-
44
- export async function callJenkinsJob({
45
- jenkinsUrl,
46
- jobName,
47
- auth,
48
- parameters,
49
- }) {
50
16
  try {
51
17
  // Trigger the job
52
18
  console.log('Triggering Jenkins job...');
53
19
  const buildResponse = await axios.post(
54
- `${jenkinsUrl}/job/${jobName}/buildWithParameters`,
20
+ `${JENKINS_URL}/job/${JOB_NAME}/buildWithParameters`,
55
21
  new URLSearchParams(parameters),
56
22
  {
57
- auth,
23
+ auth: { username: USERNAME, password: API_TOKEN },
58
24
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
59
25
  validateStatus: (status) => status === 201 || status === 302, // Accept 201 and 302 as valid statuses
60
26
  },
@@ -67,7 +33,7 @@ export async function callJenkinsJob({
67
33
  let jobUrl = null;
68
34
  while (!jobUrl) {
69
35
  const queueResponse = await axios.get(`${queueUrl}api/json`, {
70
- auth,
36
+ auth: { username: USERNAME, password: API_TOKEN },
71
37
  });
72
38
  jobUrl = queueResponse.data.executable?.url || null;
73
39
 
@@ -88,7 +54,7 @@ export async function callJenkinsJob({
88
54
  console.log('Streaming job output...');
89
55
  while (true) {
90
56
  const consoleResponse = await axios.get(consoleUrl, {
91
- auth,
57
+ auth: { username: USERNAME, password: API_TOKEN },
92
58
  responseType: 'text',
93
59
  });
94
60
 
@@ -99,16 +65,16 @@ export async function callJenkinsJob({
99
65
 
100
66
  // Check job status
101
67
  const jobResponse = await axios.get(`${jobUrl}api/json`, {
102
- auth,
68
+ auth: { username: USERNAME, password: API_TOKEN },
103
69
  });
104
70
  const result = jobResponse.data.result;
105
71
 
106
72
  if (result) {
107
73
  console.log(`\nJob completed with result: ${result}`);
108
74
  if (result === 'SUCCESS') {
109
- return;
75
+ process.exit(0);
110
76
  } else {
111
- throw new Error('Jenkins job failed');
77
+ process.exit(1);
112
78
  }
113
79
  }
114
80
 
@@ -117,6 +83,6 @@ export async function callJenkinsJob({
117
83
  }
118
84
  } catch (error) {
119
85
  console.error('Error:', error.message);
120
- throw error;
86
+ process.exit(1);
121
87
  }
122
88
  }