-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathaccount.ts
369 lines (304 loc) · 13.1 KB
/
account.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
import { StaticSiteARMResource, WebSiteManagementClient } from "@azure/arm-appservice";
import { GenericResourceExpanded, ResourceGroup, ResourceManagementClient } from "@azure/arm-resources";
import { Subscription, SubscriptionClient } from "@azure/arm-subscriptions";
import {
AzureCliCredential,
ChainedTokenCredential,
ClientSecretCredential,
DeviceCodeCredential,
EnvironmentCredential,
InteractiveBrowserCredential,
TokenCachePersistenceOptions,
TokenCredential,
useIdentityPlugin,
} from "@azure/identity";
import chalk from "chalk";
import ora from "ora";
import path from "node:path";
import { swaCLIEnv } from "./env.js";
import {
chooseProjectName,
chooseProjectSku,
chooseStaticSite,
wouldYouLikeToCreateStaticSite,
wouldYouLikeToOverrideStaticSite,
} from "./prompts.js";
import { swaCliPersistencePlugin } from "./swa-cli-persistence-plugin/index.js";
import { SWACLIPersistenceCachePlugin } from "./swa-cli-persistence-plugin/persistence-cache-plugin.js";
import { logger } from "./utils/logger.js";
import { dasherize } from "./utils/strings.js";
import { isRunningInDocker } from "./utils/docker.js";
const DEFAULT_AZURE_LOCATION = "West US 2";
export async function authenticateWithAzureIdentity(details: LoginDetails = {}, useKeychain = true, clearCache = false): Promise<TokenCredential> {
logger.silly("Executing authenticateWithAzureIdentity");
logger.silly({ details, useKeychain });
let tokenCachePersistenceOptions: TokenCachePersistenceOptions = {
enabled: false,
name: "swa-cli-persistence-plugin",
unsafeAllowUnencryptedStorage: false,
};
if (useKeychain === true) {
logger.silly("Keychain is enabled");
useIdentityPlugin(swaCliPersistencePlugin);
tokenCachePersistenceOptions.enabled = true;
if (clearCache) {
logger.silly("Clearing keychain credentials");
await new SWACLIPersistenceCachePlugin(tokenCachePersistenceOptions).clearCache();
}
} else {
logger.silly("Keychain is disabled");
tokenCachePersistenceOptions.enabled = false;
}
const browserCredential = new InteractiveBrowserCredential({
redirectUri: `http://localhost:31337`,
tokenCachePersistenceOptions,
tenantId: details.tenantId,
});
const deviceCredential = new DeviceCodeCredential({
tokenCachePersistenceOptions,
tenantId: details.tenantId,
});
const environmentCredential = new EnvironmentCredential();
const azureCliCredential = new AzureCliCredential({
tenantId: details.tenantId,
});
// Only use interactive browser credential if we're not running in docker
const credentials = isRunningInDocker()
? [environmentCredential, azureCliCredential, deviceCredential]
: [environmentCredential, azureCliCredential, browserCredential, deviceCredential];
if (details.tenantId && details.clientId && details.clientSecret) {
const clientSecretCredential = new ClientSecretCredential(details.tenantId, details.clientId, details.clientSecret, {
tokenCachePersistenceOptions,
});
// insert at the beginning of the array to ensure that it is tried first
credentials.unshift(clientSecretCredential);
}
return new ChainedTokenCredential(...credentials);
}
async function isResourceGroupExists(resourceGroup: string, subscriptionId: string, credentialChain: TokenCredential): Promise<boolean> {
const client = new ResourceManagementClient(credentialChain, subscriptionId);
try {
const rg = await client.resourceGroups.checkExistence(resourceGroup);
return rg.body;
} catch (error: any) {
if (error?.code?.includes("ResourceGroupNotFound")) {
return false;
}
throw new Error(error);
}
}
async function createResourceGroup(resourceGroup: string, credentialChain: TokenCredential, subscriptionId: string) {
const client = new ResourceManagementClient(credentialChain, subscriptionId);
const { AZURE_REGION_LOCATION } = swaCLIEnv();
const resourceGroupEnvelope: ResourceGroup = {
location: AZURE_REGION_LOCATION || DEFAULT_AZURE_LOCATION,
};
const result = await client.resourceGroups.createOrUpdate(resourceGroup, resourceGroupEnvelope);
logger.silly(result as any);
return result as GenericResourceExpanded;
}
async function gracefullyFail<T>(promise: Promise<T>, errorCode?: number): Promise<T | undefined> {
try {
return await promise;
} catch (error: any) {
if (errorCode === undefined || (error.statusCode && errorCode === error.statusCode)) {
logger.silly(`Caught error: ${error.message}`);
return undefined;
}
throw error;
}
}
async function createStaticSite(options: SWACLIConfig, credentialChain: TokenCredential, subscriptionId: string): Promise<StaticSiteARMResource> {
let { appName, resourceGroup } = options;
const maxProjectNameLength = 63; // azure convention is 64 characters (zero-indexed)
const defaultStaticSiteName = appName || dasherize(path.basename(process.cwd())).substring(0, maxProjectNameLength);
appName = await chooseProjectName(defaultStaticSiteName, maxProjectNameLength);
const sku = await chooseProjectSku();
resourceGroup = resourceGroup || `${appName}-rg`;
let spinner = ora("Creating a new project...").start();
// if the resource group does not exist, create it
if ((await isResourceGroupExists(resourceGroup, subscriptionId, credentialChain)) === false) {
logger.silly(`Resource group "${resourceGroup}" does not exist. Creating one...`);
// create the resource group
await createResourceGroup(resourceGroup, credentialChain, subscriptionId);
}
// create the static web app instance
try {
const websiteClient = new WebSiteManagementClient(credentialChain, subscriptionId);
const { AZURE_REGION_LOCATION } = swaCLIEnv();
const staticSiteEnvelope: StaticSiteARMResource = {
location: AZURE_REGION_LOCATION || DEFAULT_AZURE_LOCATION,
sku: { name: sku, tier: sku },
// these are mandatory, otherwise the static site will not be created
buildProperties: {
appLocation: "",
outputLocation: "",
apiLocation: "",
},
};
logger.silly(`Checking if project "${appName}" already exists...`);
// check if the static site already exists
const project = await gracefullyFail(websiteClient.staticSites.getStaticSite(resourceGroup, appName), 404);
const projectExists = project !== undefined;
if (projectExists) {
spinner.stop();
const confirm = await wouldYouLikeToOverrideStaticSite?.(appName);
if (confirm === false) {
return (await chooseOrCreateStaticSite(options, credentialChain, subscriptionId)) as StaticSiteARMResource;
}
}
if (projectExists) {
spinner.start(`Updating project "${appName}"...`);
}
logger.silly(`Creating static site "${appName}" in resource group "${resourceGroup}"...`);
const result = await websiteClient.staticSites.beginCreateOrUpdateStaticSiteAndWait(resourceGroup, appName, staticSiteEnvelope);
logger.silly(`Static site "${appName}" created successfully.`);
logger.silly(result as any);
if (result.id) {
if (projectExists) {
spinner.succeed(`Project "${appName}" updated successfully.`);
} else {
spinner.succeed(chalk.green("Project created successfully!"));
}
}
return result as StaticSiteARMResource;
} catch (error: any) {
spinner.fail(chalk.red("Project creation failed."));
logger.error(error.message, true);
return undefined as any;
}
}
async function chooseOrCreateStaticSite(
options: SWACLIConfig,
credentialChain: TokenCredential,
subscriptionId: string
): Promise<string | StaticSiteARMResource> {
const staticSites = await listStaticSites(credentialChain, subscriptionId);
// 1- when there are no static sites
if (staticSites.length === 0) {
const confirm = await wouldYouLikeToCreateStaticSite();
if (confirm) {
return (await createStaticSite(options, credentialChain, subscriptionId)) as StaticSiteARMResource;
} else {
logger.error("No projects found. Create a new project and try again.", true);
}
}
// 2- when there is only one static site
else if (staticSites.length === 1) {
logger.silly("Only one project found. Trying to use it if the name matches...");
const staticSite = staticSites[0];
if (options.appName === staticSite.name) {
return staticSite;
} else {
// if the name doesn't match, ask the user if they want to create a new project
const confirm = await wouldYouLikeToCreateStaticSite();
if (confirm) {
return (await createStaticSite(options, credentialChain, subscriptionId)) as StaticSiteARMResource;
} else {
logger.error(`The provided project name "${options.appName}" was not found.`, true);
}
}
}
// 3- when there are multiple static sites
if (options.appName) {
// if the user provided a project name, try to find it and use it
logger.silly(`Looking for project "${options.appName}"...`);
const staticSite = staticSites.find((s) => s.name === options.appName);
if (staticSite) {
return staticSite;
}
}
// otherwise, ask the user to choose one
const staticSite = await chooseStaticSite(staticSites, options.appName);
if (staticSite === "NEW") {
// if the user chose to create a new project, switch to the create project flow
return (await createStaticSite(options, credentialChain, subscriptionId)) as StaticSiteARMResource;
}
return staticSites.find((s) => s.name === staticSite) as StaticSiteARMResource;
}
export async function chooseOrCreateProjectDetails(
options: SWACLIConfig,
credentialChain: TokenCredential,
subscriptionId: string,
shouldPrintToken: boolean | undefined
) {
const staticSite = (await chooseOrCreateStaticSite(options, credentialChain, subscriptionId)) as StaticSiteARMResource;
logger.silly("Static site found!");
logger.silly({ staticSite });
if (staticSite && staticSite.id) {
if (!shouldPrintToken && staticSite.provider !== "Custom" && staticSite.provider !== "None" && staticSite.provider !== "SwaCli") {
// TODO: add a temporary warning message until we ship `swa link/unlink`
logger.error(`The project "${staticSite.name}" is linked to "${staticSite.provider}"!`);
logger.error(`Unlink the project from the "${staticSite.provider}" provider and try again.`, true);
return;
}
// in case we have a static site, we will use its resource group and name
// get resource group name from static site id:
// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/swa-resource-groupe-name/providers/Microsoft.Web/sites/swa-static-site
// 0 / 1 / 2 / 3 / 4
const resourceGroup = staticSite.id.split("/")[4];
const staticSiteName = staticSite.name;
return {
resourceGroup,
staticSiteName,
};
} else {
logger.error("No project found. Create a new project and try again.", true);
}
return;
}
export async function listTenants(credentialChain: TokenCredential) {
const client = new SubscriptionClient(credentialChain);
const tenants = [];
for await (let tenant of client.tenants.list()) {
tenants.push(tenant);
}
return tenants;
}
export async function listResourceGroups(credentialChain: TokenCredential, subscriptionId: string) {
const resourceGroups: GenericResourceExpanded[] = [];
const client = new ResourceManagementClient(credentialChain, subscriptionId);
for await (let resource of client.resources.list()) {
resourceGroups.push(resource);
}
return resourceGroups;
}
export async function listSubscriptions(credentialChain: TokenCredential) {
const subscriptionClient = new SubscriptionClient(credentialChain);
const subscriptions: Subscription[] = [];
for await (let subscription of subscriptionClient.subscriptions.list()) {
subscriptions.push(subscription);
}
return subscriptions;
}
export async function listStaticSites(credentialChain: TokenCredential, subscriptionId: string, resourceGroup?: string) {
const staticSites = [];
const websiteClient = new WebSiteManagementClient(credentialChain, subscriptionId);
let staticSiteList = websiteClient.staticSites.list();
if (resourceGroup) {
staticSiteList = websiteClient.staticSites.listStaticSitesByResourceGroup(resourceGroup);
}
for await (let staticSite of staticSiteList) {
staticSites.push(staticSite);
}
return staticSites.sort((a, b) => a.name?.localeCompare(b.name!)!);
}
export async function getStaticSiteDeployment(
credentialChain: TokenCredential,
subscriptionId: string,
resourceGroup: string,
staticSiteName: string
) {
if (!subscriptionId) {
logger.error("An Azure subscription is required to access your deployment token.", true);
}
if (!resourceGroup) {
logger.error("A resource group is required to access your deployment token.", true);
}
if (!staticSiteName) {
logger.error("A static site name is required to access your deployment token.", true);
}
const websiteClient = new WebSiteManagementClient(credentialChain, subscriptionId);
const deploymentTokenResponse = await websiteClient.staticSites.listStaticSiteSecrets(resourceGroup, staticSiteName);
return deploymentTokenResponse;
}