@pnp/cli-microsoft365 10.0.0-beta.7dfc31a → 10.0.0-beta.e925c1c

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.
@@ -9,10 +9,10 @@ import { v4 } from 'uuid';
9
9
  import auth from '../../../../Auth.js';
10
10
  import request from '../../../../request.js';
11
11
  import { accessToken } from '../../../../utils/accessToken.js';
12
- import { odata } from '../../../../utils/odata.js';
12
+ import { entraApp } from '../../../../utils/entraApp.js';
13
13
  import GraphCommand from '../../../base/GraphCommand.js';
14
- import commands from '../../commands.js';
15
14
  import aadCommands from '../../aadCommands.js';
15
+ import commands from '../../commands.js';
16
16
  class EntraAppAddCommand extends GraphCommand {
17
17
  get name() {
18
18
  return commands.APP_ADD;
@@ -27,7 +27,6 @@ class EntraAppAddCommand extends GraphCommand {
27
27
  super();
28
28
  _EntraAppAddCommand_instances.add(this);
29
29
  this.appName = '';
30
- this.appPermissions = [];
31
30
  __classPrivateFieldGet(this, _EntraAppAddCommand_instances, "m", _EntraAppAddCommand_initTelemetry).call(this);
32
31
  __classPrivateFieldGet(this, _EntraAppAddCommand_instances, "m", _EntraAppAddCommand_initOptions).call(this);
33
32
  __classPrivateFieldGet(this, _EntraAppAddCommand_instances, "m", _EntraAppAddCommand_initValidators).call(this);
@@ -35,16 +34,38 @@ class EntraAppAddCommand extends GraphCommand {
35
34
  }
36
35
  async commandAction(logger, args) {
37
36
  await this.showDeprecationWarning(logger, aadCommands.APP_ADD, commands.APP_ADD);
37
+ if (!args.options.name && this.manifest) {
38
+ args.options.name = this.manifest.name;
39
+ }
40
+ this.appName = args.options.name;
38
41
  try {
39
- const apis = await this.resolveApis(args, logger);
40
- let appInfo = await this.createAppRegistration(args, apis, logger);
42
+ const apis = await entraApp.resolveApis({
43
+ options: args.options,
44
+ manifest: this.manifest,
45
+ logger,
46
+ verbose: this.verbose,
47
+ debug: this.debug
48
+ });
49
+ let appInfo = await entraApp.createAppRegistration({
50
+ options: args.options,
51
+ apis,
52
+ logger,
53
+ verbose: this.verbose,
54
+ debug: this.debug
55
+ });
41
56
  // based on the assumption that we're adding Microsoft Entra app to the current
42
57
  // directory. If we in the future extend the command with allowing
43
58
  // users to create Microsoft Entra app in a different directory, we'll need to
44
59
  // adjust this
45
60
  appInfo.tenantId = accessToken.getTenantIdFromAccessToken(auth.connection.accessTokens[auth.defaultResource].accessToken);
46
61
  appInfo = await this.updateAppFromManifest(args, appInfo);
47
- appInfo = await this.grantAdminConsent(appInfo, args.options.grantAdminConsent, logger);
62
+ appInfo = await entraApp.grantAdminConsent({
63
+ appInfo,
64
+ appPermissions: entraApp.appPermissions,
65
+ adminConsent: args.options.grantAdminConsent,
66
+ logger,
67
+ debug: this.debug
68
+ });
48
69
  appInfo = await this.configureUri(args, appInfo, logger);
49
70
  appInfo = await this.configureSecret(args, appInfo, logger);
50
71
  const _appInfo = await this.saveAppInfo(args, appInfo, logger);
@@ -62,128 +83,45 @@ class EntraAppAddCommand extends GraphCommand {
62
83
  this.handleRejectedODataJsonPromise(err);
63
84
  }
64
85
  }
65
- async createAppRegistration(args, apis, logger) {
66
- const applicationInfo = {
67
- displayName: args.options.name,
68
- signInAudience: args.options.multitenant ? 'AzureADMultipleOrgs' : 'AzureADMyOrg'
69
- };
70
- if (!applicationInfo.displayName && this.manifest) {
71
- applicationInfo.displayName = this.manifest.name;
72
- }
73
- this.appName = applicationInfo.displayName;
74
- if (apis.length > 0) {
75
- applicationInfo.requiredResourceAccess = apis;
76
- }
77
- if (args.options.redirectUris) {
78
- applicationInfo[args.options.platform] = {
79
- redirectUris: args.options.redirectUris.split(',').map(u => u.trim())
80
- };
81
- }
82
- if (args.options.implicitFlow) {
83
- if (!applicationInfo.web) {
84
- applicationInfo.web = {};
85
- }
86
- applicationInfo.web.implicitGrantSettings = {
87
- enableAccessTokenIssuance: true,
88
- enableIdTokenIssuance: true
89
- };
90
- }
91
- if (args.options.certificateFile || args.options.certificateBase64Encoded) {
92
- const certificateBase64Encoded = await this.getCertificateBase64Encoded(args, logger);
93
- const newKeyCredential = {
94
- type: "AsymmetricX509Cert",
95
- usage: "Verify",
96
- displayName: args.options.certificateDisplayName,
97
- key: certificateBase64Encoded
98
- };
99
- applicationInfo.keyCredentials = [newKeyCredential];
100
- }
101
- if (args.options.allowPublicClientFlows) {
102
- applicationInfo.isFallbackPublicClient = true;
86
+ async configureSecret(args, appInfo, logger) {
87
+ if (!args.options.withSecret || (appInfo.secrets && appInfo.secrets.length > 0)) {
88
+ return appInfo;
103
89
  }
104
90
  if (this.verbose) {
105
- await logger.logToStderr(`Creating Microsoft Entra app registration...`);
106
- }
107
- const createApplicationRequestOptions = {
108
- url: `${this.resource}/v1.0/myorganization/applications`,
109
- headers: {
110
- accept: 'application/json;odata.metadata=none'
111
- },
112
- responseType: 'json',
113
- data: applicationInfo
114
- };
115
- return request.post(createApplicationRequestOptions);
116
- }
117
- async grantAdminConsent(appInfo, adminConsent, logger) {
118
- if (!adminConsent || this.appPermissions.length === 0) {
119
- return appInfo;
91
+ await logger.logToStderr(`Configure Microsoft Entra app secret...`);
120
92
  }
121
- const sp = await this.createServicePrincipal(appInfo.appId);
122
- if (this.debug) {
123
- await logger.logToStderr("Service principal created, returned object id: " + sp.id);
93
+ const secret = await this.createSecret({ appObjectId: appInfo.id });
94
+ if (!appInfo.secrets) {
95
+ appInfo.secrets = [];
124
96
  }
125
- const tasks = [];
126
- this.appPermissions.forEach(async (permission) => {
127
- if (permission.scope.length > 0) {
128
- tasks.push(this.grantOAuth2Permission(sp.id, permission.resourceId, permission.scope.join(' ')));
129
- if (this.debug) {
130
- await logger.logToStderr(`Admin consent granted for following resource ${permission.resourceId}, with delegated permissions: ${permission.scope.join(',')}`);
131
- }
132
- }
133
- permission.resourceAccess.filter(access => access.type === "Role").forEach(async (access) => {
134
- tasks.push(this.addRoleToServicePrincipal(sp.id, permission.resourceId, access.id));
135
- if (this.debug) {
136
- await logger.logToStderr(`Admin consent granted for following resource ${permission.resourceId}, with application permission: ${access.id}`);
137
- }
138
- });
139
- });
140
- await Promise.all(tasks);
97
+ appInfo.secrets.push(secret);
141
98
  return appInfo;
142
99
  }
143
- async addRoleToServicePrincipal(objectId, resourceId, appRoleId) {
100
+ async createSecret({ appObjectId, displayName = undefined, expirationDate = undefined }) {
101
+ let secretExpirationDate = expirationDate;
102
+ if (!secretExpirationDate) {
103
+ secretExpirationDate = new Date();
104
+ secretExpirationDate.setFullYear(secretExpirationDate.getFullYear() + 1);
105
+ }
106
+ const secretName = displayName ?? 'Default';
144
107
  const requestOptions = {
145
- url: `${this.resource}/v1.0/myorganization/servicePrincipals/${objectId}/appRoleAssignments`,
146
- headers: {
147
- 'Content-Type': 'application/json'
148
- },
149
- responseType: 'json',
150
- data: {
151
- appRoleId: appRoleId,
152
- principalId: objectId,
153
- resourceId: resourceId
154
- }
155
- };
156
- return request.post(requestOptions);
157
- }
158
- async grantOAuth2Permission(appId, resourceId, scopeName) {
159
- const grantAdminConsentApplicationRequestOptions = {
160
- url: `${this.resource}/v1.0/myorganization/oauth2PermissionGrants`,
108
+ url: `${this.resource}/v1.0/myorganization/applications/${appObjectId}/addPassword`,
161
109
  headers: {
162
- accept: 'application/json;odata.metadata=none'
110
+ 'content-type': 'application/json'
163
111
  },
164
112
  responseType: 'json',
165
113
  data: {
166
- clientId: appId,
167
- consentType: "AllPrincipals",
168
- principalId: null,
169
- resourceId: resourceId,
170
- scope: scopeName
114
+ passwordCredential: {
115
+ displayName: secretName,
116
+ endDateTime: secretExpirationDate.toISOString()
117
+ }
171
118
  }
172
119
  };
173
- return request.post(grantAdminConsentApplicationRequestOptions);
174
- }
175
- async createServicePrincipal(appId) {
176
- const requestOptions = {
177
- url: `${this.resource}/v1.0/myorganization/servicePrincipals`,
178
- headers: {
179
- 'content-type': 'application/json'
180
- },
181
- data: {
182
- appId: appId
183
- },
184
- responseType: 'json'
120
+ const response = await request.post(requestOptions);
121
+ return {
122
+ displayName: secretName,
123
+ value: response.secretText
185
124
  };
186
- return request.post(requestOptions);
187
125
  }
188
126
  async updateAppFromManifest(args, appInfo) {
189
127
  if (!args.options.manifest) {
@@ -423,180 +361,6 @@ class EntraAppAddCommand extends GraphCommand {
423
361
  await request.patch(requestOptions);
424
362
  return appInfo;
425
363
  }
426
- async resolveApis(args, logger) {
427
- if (!args.options.apisDelegated && !args.options.apisApplication
428
- && (typeof this.manifest?.requiredResourceAccess === 'undefined' || this.manifest.requiredResourceAccess.length === 0)) {
429
- return [];
430
- }
431
- if (this.verbose) {
432
- await logger.logToStderr('Resolving requested APIs...');
433
- }
434
- const servicePrincipals = await odata.getAllItems(`${this.resource}/v1.0/myorganization/servicePrincipals?$select=appId,appRoles,id,oauth2PermissionScopes,servicePrincipalNames`);
435
- let resolvedApis = [];
436
- try {
437
- if (args.options.apisDelegated || args.options.apisApplication) {
438
- resolvedApis = await this.getRequiredResourceAccessForApis(servicePrincipals, args.options.apisDelegated, 'Scope', logger);
439
- if (this.verbose) {
440
- await logger.logToStderr(`Resolved delegated permissions: ${JSON.stringify(resolvedApis, null, 2)}`);
441
- }
442
- const resolvedApplicationApis = await this.getRequiredResourceAccessForApis(servicePrincipals, args.options.apisApplication, 'Role', logger);
443
- if (this.verbose) {
444
- await logger.logToStderr(`Resolved application permissions: ${JSON.stringify(resolvedApplicationApis, null, 2)}`);
445
- }
446
- // merge resolved application APIs onto resolved delegated APIs
447
- resolvedApplicationApis.forEach(resolvedRequiredResource => {
448
- const requiredResource = resolvedApis.find(api => api.resourceAppId === resolvedRequiredResource.resourceAppId);
449
- if (requiredResource) {
450
- requiredResource.resourceAccess.push(...resolvedRequiredResource.resourceAccess);
451
- }
452
- else {
453
- resolvedApis.push(resolvedRequiredResource);
454
- }
455
- });
456
- }
457
- else {
458
- const manifestApis = this.manifest.requiredResourceAccess;
459
- manifestApis.forEach(manifestApi => {
460
- resolvedApis.push(manifestApi);
461
- const app = servicePrincipals.find(servicePrincipals => servicePrincipals.appId === manifestApi.resourceAppId);
462
- if (app) {
463
- manifestApi.resourceAccess.forEach((res => {
464
- const resourceAccessPermission = {
465
- id: res.id,
466
- type: res.type
467
- };
468
- const oAuthValue = app.oauth2PermissionScopes.find(scp => scp.id === res.id)?.value;
469
- this.updateAppPermissions(app.id, resourceAccessPermission, oAuthValue);
470
- }));
471
- }
472
- });
473
- }
474
- if (this.verbose) {
475
- await logger.logToStderr(`Merged delegated and application permissions: ${JSON.stringify(resolvedApis, null, 2)}`);
476
- await logger.logToStderr(`App role assignments: ${JSON.stringify(this.appPermissions.flatMap(permission => permission.resourceAccess.filter(access => access.type === "Role")), null, 2)}`);
477
- await logger.logToStderr(`OAuth2 permissions: ${JSON.stringify(this.appPermissions.flatMap(permission => permission.scope), null, 2)}`);
478
- }
479
- return resolvedApis;
480
- }
481
- catch (e) {
482
- throw e;
483
- }
484
- }
485
- async getRequiredResourceAccessForApis(servicePrincipals, apis, scopeType, logger) {
486
- if (!apis) {
487
- return [];
488
- }
489
- const resolvedApis = [];
490
- const requestedApis = apis.split(',').map(a => a.trim());
491
- for (const api of requestedApis) {
492
- const pos = api.lastIndexOf('/');
493
- const permissionName = api.substr(pos + 1);
494
- const servicePrincipalName = api.substr(0, pos);
495
- if (this.debug) {
496
- await logger.logToStderr(`Resolving ${api}...`);
497
- await logger.logToStderr(`Permission name: ${permissionName}`);
498
- await logger.logToStderr(`Service principal name: ${servicePrincipalName}`);
499
- }
500
- const servicePrincipal = servicePrincipals.find(sp => (sp.servicePrincipalNames.indexOf(servicePrincipalName) > -1 ||
501
- sp.servicePrincipalNames.indexOf(`${servicePrincipalName}/`) > -1));
502
- if (!servicePrincipal) {
503
- throw `Service principal ${servicePrincipalName} not found`;
504
- }
505
- const scopesOfType = scopeType === 'Scope' ? servicePrincipal.oauth2PermissionScopes : servicePrincipal.appRoles;
506
- const permission = scopesOfType.find(scope => scope.value === permissionName);
507
- if (!permission) {
508
- throw `Permission ${permissionName} for service principal ${servicePrincipalName} not found`;
509
- }
510
- let resolvedApi = resolvedApis.find(a => a.resourceAppId === servicePrincipal.appId);
511
- if (!resolvedApi) {
512
- resolvedApi = {
513
- resourceAppId: servicePrincipal.appId,
514
- resourceAccess: []
515
- };
516
- resolvedApis.push(resolvedApi);
517
- }
518
- const resourceAccessPermission = {
519
- id: permission.id,
520
- type: scopeType
521
- };
522
- resolvedApi.resourceAccess.push(resourceAccessPermission);
523
- this.updateAppPermissions(servicePrincipal.id, resourceAccessPermission, permission.value);
524
- }
525
- return resolvedApis;
526
- }
527
- updateAppPermissions(spId, resourceAccessPermission, oAuth2PermissionValue) {
528
- // During API resolution, we store globally both app role assignments and oauth2permissions
529
- // So that we'll be able to parse them during the admin consent process
530
- let existingPermission = this.appPermissions.find(oauth => oauth.resourceId === spId);
531
- if (!existingPermission) {
532
- existingPermission = {
533
- resourceId: spId,
534
- resourceAccess: [],
535
- scope: []
536
- };
537
- this.appPermissions.push(existingPermission);
538
- }
539
- if (resourceAccessPermission.type === 'Scope' && oAuth2PermissionValue && !existingPermission.scope.find(scp => scp === oAuth2PermissionValue)) {
540
- existingPermission.scope.push(oAuth2PermissionValue);
541
- }
542
- if (!existingPermission.resourceAccess.find(res => res.id === resourceAccessPermission.id)) {
543
- existingPermission.resourceAccess.push(resourceAccessPermission);
544
- }
545
- }
546
- async configureSecret(args, appInfo, logger) {
547
- if (!args.options.withSecret || (appInfo.secrets && appInfo.secrets.length > 0)) {
548
- return appInfo;
549
- }
550
- if (this.verbose) {
551
- await logger.logToStderr(`Configure Microsoft Entra app secret...`);
552
- }
553
- const secret = await this.createSecret({ appObjectId: appInfo.id });
554
- if (!appInfo.secrets) {
555
- appInfo.secrets = [];
556
- }
557
- appInfo.secrets.push(secret);
558
- return appInfo;
559
- }
560
- async createSecret({ appObjectId, displayName = undefined, expirationDate = undefined }) {
561
- let secretExpirationDate = expirationDate;
562
- if (!secretExpirationDate) {
563
- secretExpirationDate = new Date();
564
- secretExpirationDate.setFullYear(secretExpirationDate.getFullYear() + 1);
565
- }
566
- const secretName = displayName ?? 'Default';
567
- const requestOptions = {
568
- url: `${this.resource}/v1.0/myorganization/applications/${appObjectId}/addPassword`,
569
- headers: {
570
- 'content-type': 'application/json'
571
- },
572
- responseType: 'json',
573
- data: {
574
- passwordCredential: {
575
- displayName: secretName,
576
- endDateTime: secretExpirationDate.toISOString()
577
- }
578
- }
579
- };
580
- const response = await request.post(requestOptions);
581
- return {
582
- displayName: secretName,
583
- value: response.secretText
584
- };
585
- }
586
- async getCertificateBase64Encoded(args, logger) {
587
- if (args.options.certificateBase64Encoded) {
588
- return args.options.certificateBase64Encoded;
589
- }
590
- if (this.debug) {
591
- await logger.logToStderr(`Reading existing ${args.options.certificateFile}...`);
592
- }
593
- try {
594
- return fs.readFileSync(args.options.certificateFile, { encoding: 'base64' });
595
- }
596
- catch (e) {
597
- throw new Error(`Error reading certificate file: ${e}. Please add the certificate using base64 option '--certificateBase64Encoded'.`);
598
- }
599
- }
600
364
  async saveAppInfo(args, appInfo, logger) {
601
365
  if (!args.options.save) {
602
366
  return appInfo;
@@ -1,6 +1,11 @@
1
1
  const settingsNames = {
2
2
  authType: 'authType',
3
3
  autoOpenLinksInBrowser: 'autoOpenLinksInBrowser',
4
+ clientId: 'clientId',
5
+ clientSecret: 'clientSecret',
6
+ clientCertificateFile: 'clientCertificateFile',
7
+ clientCertificateBase64Encoded: 'clientCertificateBase64Encoded',
8
+ clientCertificatePassword: 'clientCertificatePassword',
4
9
  copyDeviceCodeToClipboard: 'copyDeviceCodeToClipboard',
5
10
  csvEscape: 'csvEscape',
6
11
  csvHeader: 'csvHeader',
@@ -16,7 +21,8 @@ const settingsNames = {
16
21
  prompt: 'prompt',
17
22
  promptListPageSize: 'promptListPageSize',
18
23
  showHelpOnFailure: 'showHelpOnFailure',
19
- showSpinner: 'showSpinner'
24
+ showSpinner: 'showSpinner',
25
+ tenantId: 'tenantId'
20
26
  };
21
27
  export { settingsNames };
22
28
  //# sourceMappingURL=settingsNames.js.map