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P,OAAO,CAAE,SAAS;YAC7B,MAAM,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM;YACvB,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,aAAa,EAAE,IAAI,CAAC,SAAS,CAAC,SAAS;YACvC,mBAAmB,EAAE,MAAM,EAAE,uBAAuB;SACrD,CAAC;QAEF,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,SAAU,CAAC,cAAc,CAAC,qBAAqB,CAAC,CAAC;QAE7E,IAAI;YACF,4FAA4F;YAC5F,MAAM,0BAA0B,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC;SACpF;QAAC,OAAO,CAAM,EAAE;YACf,MAAM,IAAI,0BAA0B,CAClC,yEAAyE,CAAC,CAAC,OAAO,EAAE,CACrF,CAAC;SACH;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\n\nimport { AccessToken } from \"@azure/core-auth\";\n\nimport { Socket } from \"net\";\nimport http from \"http\";\nimport open from \"open\";\nimport stoppable from \"stoppable\";\n\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\nimport { CredentialUnavailableError } from \"../../errors\";\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { msalToPublic } from \"../utils\";\n\n/**\n * Options that can be passed to configure MSAL to handle authentication through opening a browser window.\n * @internal\n */\nexport interface MSALOpenBrowserOptions extends MsalNodeOptions {\n redirectUri: string;\n loginHint?: string;\n}\n\n/**\n * A call to open(), but mockable\n * @internal\n */\nexport const interactiveBrowserMockable = {\n open,\n};\n\n/**\n * This MSAL client sets up a web server to listen for redirect callbacks, then calls to the MSAL's public application's `acquireTokenByDeviceCode` during `doGetToken`\n * to trigger the authentication flow, and then respond based on the values obtained from the redirect callback\n * @internal\n */\nexport class MsalOpenBrowser extends MsalNode {\n private redirectUri: string;\n private port: number;\n private hostname: string;\n private loginHint?: string;\n\n constructor(options: MSALOpenBrowserOptions) {\n super(options);\n this.logger = credentialLogger(\"Node.js MSAL Open Browser\");\n this.redirectUri = options.redirectUri;\n this.loginHint = options.loginHint;\n\n const url = new URL(this.redirectUri);\n this.port = parseInt(url.port);\n if (isNaN(this.port)) {\n this.port = 80;\n }\n this.hostname = url.hostname;\n }\n\n private async acquireTokenByCode(\n request: msalNode.AuthorizationCodeRequest\n ): Promise {\n return this.publicApp!.acquireTokenByCode(request);\n }\n\n protected doGetToken(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise {\n return new Promise((resolve, reject) => {\n const socketToDestroy: Socket[] = [];\n\n const requestListener = (req: http.IncomingMessage, res: http.ServerResponse): void => {\n if (!req.url) {\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n return;\n }\n let url: URL;\n try {\n url = new URL(req.url, this.redirectUri);\n } catch (e: any) {\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n return;\n }\n const tokenRequest: msalNode.AuthorizationCodeRequest = {\n code: url.searchParams.get(\"code\")!,\n redirectUri: this.redirectUri,\n scopes: scopes,\n authority: options?.authority,\n codeVerifier: this.pkceCodes?.verifier,\n };\n\n this.acquireTokenByCode(tokenRequest)\n .then((authResponse) => {\n if (authResponse?.account) {\n this.account = msalToPublic(this.clientId, authResponse.account);\n }\n const successMessage = `Authentication Complete. You can close the browser and return to the application.`;\n if (authResponse && authResponse.expiresOn) {\n const expiresOnTimestamp = authResponse?.expiresOn.valueOf();\n res.writeHead(200);\n res.end(successMessage);\n this.logger.getToken.info(formatSuccess(scopes));\n\n resolve({\n expiresOnTimestamp,\n token: authResponse.accessToken,\n });\n } else {\n const errorMessage = formatError(\n scopes,\n `${url.searchParams.get(\"error\")}. ${url.searchParams.get(\"error_description\")}`\n );\n res.writeHead(500);\n res.end(errorMessage);\n this.logger.getToken.info(errorMessage);\n\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n }\n cleanup();\n return;\n })\n .catch(() => {\n const errorMessage = formatError(\n scopes,\n `${url.searchParams.get(\"error\")}. ${url.searchParams.get(\"error_description\")}`\n );\n res.writeHead(500);\n res.end(errorMessage);\n this.logger.getToken.info(errorMessage);\n\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n cleanup();\n });\n };\n\n const app = http.createServer(requestListener);\n const server = stoppable(app);\n\n const listen = app.listen(this.port, this.hostname, () =>\n this.logger.info(`InteractiveBrowserCredential listening on port ${this.port}!`)\n );\n\n function cleanup(): void {\n if (listen) {\n listen.close();\n }\n\n for (const socket of socketToDestroy) {\n socket.destroy();\n }\n\n if (server) {\n server.close();\n server.stop();\n }\n }\n\n app.on(\"connection\", (socket) => socketToDestroy.push(socket));\n\n app.on(\"error\", (err) => {\n cleanup();\n const code = (err as any).code;\n if (code === \"EACCES\" || code === \"EADDRINUSE\") {\n reject(\n new CredentialUnavailableError(\n [\n `InteractiveBrowserCredential: Access denied to port ${this.port}.`,\n `Try sending a redirect URI with a different port, as follows:`,\n '`new InteractiveBrowserCredential({ redirectUri: \"http://localhost:1337\" })`',\n ].join(\" \")\n )\n );\n } else {\n reject(\n new CredentialUnavailableError(\n `InteractiveBrowserCredential: Failed to start the necessary web server. Error: ${err.message}`\n )\n );\n }\n });\n\n app.on(\"listening\", () => {\n const openPromise = this.openAuthCodeUrl(scopes, options);\n\n const abortSignal = options?.abortSignal;\n if (abortSignal) {\n abortSignal.addEventListener(\"abort\", () => {\n cleanup();\n reject(new Error(\"Aborted\"));\n });\n }\n\n openPromise.then().catch((e) => {\n cleanup();\n reject(e);\n });\n });\n });\n }\n\n private pkceCodes?: {\n verifier: string;\n challenge: string;\n };\n\n private async openAuthCodeUrl(\n scopeArray: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise {\n // Initialize CryptoProvider instance\n const cryptoProvider = new msalNode.CryptoProvider();\n // Generate PKCE Codes before starting the authorization flow\n this.pkceCodes = await cryptoProvider.generatePkceCodes();\n\n const authCodeUrlParameters: msalNode.AuthorizationUrlRequest = {\n scopes: scopeArray,\n correlationId: options?.correlationId,\n redirectUri: this.redirectUri,\n authority: options?.authority,\n claims: options?.claims,\n loginHint: this.loginHint,\n codeChallenge: this.pkceCodes.challenge,\n codeChallengeMethod: \"S256\", // Use SHA256 Algorithm\n };\n\n const response = await this.publicApp!.getAuthCodeUrl(authCodeUrlParameters);\n\n try {\n // A new instance on macOS only which allows it to not hang, does not fix the issue on linux\n await interactiveBrowserMockable.open(response, { wait: true, newInstance: true });\n } catch (e: any) {\n throw new CredentialUnavailableError(\n `InteractiveBrowserCredential: Could not open a browser window. Error: ${e.message}`\n );\n }\n }\n}\n"]}