Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Linted/Formatted all msal-node samples #7450

Merged
merged 4 commits into from
Dec 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions samples/e2eTestUtils/src/LabConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { MsidApp } from "./MsidApp";
import { MsidLab } from "./MsidLab";

export type LabConfig = {
user: MsidUser,
app: MsidApp,
lab: MsidLab
user: MsidUser;
app: MsidApp;
lab: MsidLab;
};
18 changes: 9 additions & 9 deletions samples/e2eTestUtils/src/MsidApp.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
export type MsidApp = {
appName?: string,
appId?: string,
authority?: string,
b2cAuthorities?: string,
defaultScopes?: string,
appRoles?: string,
multitenantApp?: string,
clientSecret?: string,
clientCertificate?: string
appName?: string;
appId?: string;
authority?: string;
b2cAuthorities?: string;
defaultScopes?: string;
appRoles?: string;
multitenantApp?: string;
clientSecret?: string;
clientCertificate?: string;
};
18 changes: 9 additions & 9 deletions samples/e2eTestUtils/src/MsidLab.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
export type MsidLab = {
labName?: string,
region?: string,
id?: number,
tenantId?: string,
federationProvider?: string,
azureEnvironment?: string,
credentialKeyVaultKeyName?: string,
authority?: string,
adfsEndpoint?: string
labName?: string;
region?: string;
id?: number;
tenantId?: string;
federationProvider?: string;
azureEnvironment?: string;
credentialKeyVaultKeyName?: string;
authority?: string;
adfsEndpoint?: string;
};
14 changes: 7 additions & 7 deletions samples/msal-node-samples/AGC-README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ The non-AGC E2E tests are not able to be run in the AGCE. In order to run - and
The following seven environment variables must be set in powershell before running the AGC E2E tests. They can be set via the following commands:

1. $env:GRAPH_URL = "The URL of Microsoft Graph API"
This can be found in the Microsoft Entra admin center in the application's App Registration
Important to note: "/v1.0/me" and "/.default" should not be appended to the end of the URL.
These parts of the URL are already accounted for in the E2E tests.
This can be found in the Microsoft Entra admin center in the application's App Registration
Important to note: "/v1.0/me" and "/.default" should not be appended to the end of the URL.
These parts of the URL are already accounted for in the E2E tests.

2. $env:AUTHORITY = "The URL that indicates a directory that MSAL can request tokens from."
This can be found in the Microsoft Entra admin center in the application's App Registration
This can be found in the Microsoft Entra admin center in the application's App Registration

3. $env:KEY_VAULT_URL = "The URL to the key vault where the test user's credentials are stored"

Expand All @@ -17,8 +17,8 @@ This can be found in the Microsoft Entra admin center in the application's App R
5. $env:AZURE_CLIENT_ID = "The application (client) ID registered in the Microsoft Entra tenant"

6. $env:AZURE_CLIENT_SECRET = "The client secret for the registered application"
It is important to note that the AZURE_CLIENT_ID and AZURE_CLIENT_SECRET values will change depending on if the E2E test is utilizing a confidential or public client.
It is important to note that the AZURE_CLIENT_ID and AZURE_CLIENT_SECRET values will change depending on if the E2E test is utilizing a confidential or public client.

7. $env:NODE_EXTRA_CA_CERTS = "pathToCert"
Certificate chains in the AGC are re-signed with an AGC Certificate Authority certificate. NodeJS does not interact with Windows to get a list of Certificate Authorities to trust. Therefore, you must use the NODE_EXTRA_CA_CERTS environment variable to pass the chain of certificates that was re-signed by the AGC certificate.
The following article provides more context and shows how to re-chain the certificates: https://medium.com/zowe/zowe-cli-providing-node-extra-ca-certs-117727d936e5.
Certificate chains in the AGC are re-signed with an AGC Certificate Authority certificate. NodeJS does not interact with Windows to get a list of Certificate Authorities to trust. Therefore, you must use the NODE_EXTRA_CA_CERTS environment variable to pass the chain of certificates that was re-signed by the AGC certificate.
The following article provides more context and shows how to re-chain the certificates: https://medium.com/zowe/zowe-cli-providing-node-extra-ca-certs-117727d936e5.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License

import Main from './Main';
Main.main();
import Main from "./Main";
Main.main();
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,9 @@ export default class AuthProvider {
* A loopback server of your own implementation, which can have custom logic
* such as attempting to listen on a given port if it is available.
*/
const customLoopbackClient = await CustomLoopbackClient.initialize(3874);
const customLoopbackClient = await CustomLoopbackClient.initialize(
3874
);

// opens a browser instance via Electron shell API
const openBrowser = async (url: any) => {
Expand All @@ -141,7 +143,7 @@ export default class AuthProvider {
errorTemplate: fs
.readFileSync("./public/errorTemplate.html", "utf8")
.toString(),
loopbackClient: customLoopbackClient // overrides default loopback client
loopbackClient: customLoopbackClient, // overrides default loopback client
};

const authResponse =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import { ICachePlugin, TokenCacheContext } from "@azure/msal-node";
import * as fs from "fs";
import { CACHE_LOCATION } from "./Constants";



export const cachePlugin = (CACHE_LOCATION: string): ICachePlugin => {
const beforeCacheAccess = async (cacheContext: TokenCacheContext) => {
return new Promise<void>(async (resolve, reject) => {
Expand All @@ -27,7 +25,7 @@ export const cachePlugin = (CACHE_LOCATION: string): ICachePlugin => {
(err) => {
if (err) {
reject();
}
}
}
);
}
Expand All @@ -42,7 +40,7 @@ export const cachePlugin = (CACHE_LOCATION: string): ICachePlugin => {
(err) => {
if (err) {
console.log(err);
}
}
}
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@
// Add here the endpoints for MS Graph API services you would like to use.
export const GRAPH_CONFIG = {
GRAPH_ME_ENDPT: "/me",
GRAPH_MAIL_ENDPT: "/me/messages"
GRAPH_MAIL_ENDPT: "/me/messages",
};


export enum IpcMessages {
SHOW_WELCOME_MESSAGE = "SHOW_WELCOME_MESSAGE",
LOGIN = "LOGIN",
Expand All @@ -23,7 +22,7 @@ export enum IpcMessages {

export const APPLICATION_DIMENSIONS = {
WIDTH: 1000,
HEIGHT: 1000
}
HEIGHT: 1000,
};

export const CACHE_LOCATION = "./data/cache.json";
export const CACHE_LOCATION = "./data/cache.json";
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
*/

import http from "http";
import { ILoopbackClient, ServerAuthorizationCodeResponse } from "@azure/msal-node";
import {
ILoopbackClient,
ServerAuthorizationCodeResponse,
} from "@azure/msal-node";

/**
* Implements ILoopbackClient interface to listen for authZ code response.
Expand All @@ -25,13 +28,17 @@ export class CustomLoopbackClient implements ILoopbackClient {
* @param logger
* @returns
*/
static async initialize(preferredPort: number | undefined): Promise<CustomLoopbackClient> {
static async initialize(
preferredPort: number | undefined
): Promise<CustomLoopbackClient> {
const loopbackClient = new CustomLoopbackClient();

if (preferredPort === 0 || preferredPort === undefined) {
return loopbackClient;
}
const isPortAvailable = await loopbackClient.isPortAvailable(preferredPort);
const isPortAvailable = await loopbackClient.isPortAvailable(
preferredPort
);

if (isPortAvailable) {
loopbackClient.port = preferredPort;
Expand All @@ -46,40 +53,67 @@ export class CustomLoopbackClient implements ILoopbackClient {
* @param errorTemplate
* @returns
*/
async listenForAuthCode(successTemplate?: string, errorTemplate?: string): Promise<ServerAuthorizationCodeResponse> {
async listenForAuthCode(
successTemplate?: string,
errorTemplate?: string
): Promise<ServerAuthorizationCodeResponse> {
if (!!this.server) {
throw new Error('Loopback server already exists. Cannot create another.')
throw new Error(
"Loopback server already exists. Cannot create another."
);
}

const authCodeListener = new Promise<ServerAuthorizationCodeResponse>((resolve, reject) => {
this.server = http.createServer(async (req: http.IncomingMessage, res: http.ServerResponse) => {
const url = req.url;
if (!url) {
res.end(errorTemplate || "Error occurred loading redirectUrl");
reject(new Error('Loopback server callback was invoked without a url. This is unexpected.'));
return;
} else if (url === "/") {
res.end(successTemplate || "Auth code was successfully acquired. You can close this window now.");
return;
}

const authCodeResponse = CustomLoopbackClient.getDeserializedQueryString(url);
if (authCodeResponse.code) {
const redirectUri = await this.getRedirectUri();
res.writeHead(302, { location: redirectUri }); // Prevent auth code from being saved in the browser history
res.end();
}
resolve(authCodeResponse);
});
this.server.listen(this.port);
});
const authCodeListener = new Promise<ServerAuthorizationCodeResponse>(
(resolve, reject) => {
this.server = http.createServer(
async (
req: http.IncomingMessage,
res: http.ServerResponse
) => {
const url = req.url;
if (!url) {
res.end(
errorTemplate ||
"Error occurred loading redirectUrl"
);
reject(
new Error(
"Loopback server callback was invoked without a url. This is unexpected."
)
);
return;
} else if (url === "/") {
res.end(
successTemplate ||
"Auth code was successfully acquired. You can close this window now."
);
return;
}

const authCodeResponse =
CustomLoopbackClient.getDeserializedQueryString(
url
);
if (authCodeResponse.code) {
const redirectUri = await this.getRedirectUri();
res.writeHead(302, { location: redirectUri }); // Prevent auth code from being saved in the browser history
res.end();
}
resolve(authCodeResponse);
}
);
this.server.listen(this.port);
}
);

// Wait for server to be listening
await new Promise<void>((resolve) => {
let ticks = 0;
const id = setInterval(() => {
if ((5000 / 100) < ticks) {
throw new Error('Timed out waiting for auth code listener to be registered.');
if (5000 / 100 < ticks) {
throw new Error(
"Timed out waiting for auth code listener to be registered."
);
}

if (this.server.listening) {
Expand All @@ -99,13 +133,15 @@ export class CustomLoopbackClient implements ILoopbackClient {
*/
getRedirectUri(): string {
if (!this.server) {
throw new Error('No loopback server exists yet.')
throw new Error("No loopback server exists yet.");
}

const address = this.server.address();
if (!address || typeof address === "string" || !address.port) {
this.closeServer();
throw new Error('Loopback server address is not type string. This is unexpected.')
throw new Error(
"Loopback server address is not type string. This is unexpected."
);
}

const port = address && address.port;
Expand All @@ -128,8 +164,9 @@ export class CustomLoopbackClient implements ILoopbackClient {
* @returns
*/
isPortAvailable(port: number): Promise<boolean> {
return new Promise(resolve => {
const server = http.createServer()
return new Promise((resolve) => {
const server = http
.createServer()
.listen(port, () => {
server.close();
resolve(true);
Expand All @@ -154,9 +191,7 @@ export class CustomLoopbackClient implements ILoopbackClient {
const parsedQueryString = this.parseQueryString(query);
// If ? symbol was not present, above will return empty string, so give original query value
const deserializedQueryString: ServerAuthorizationCodeResponse =
this.queryStringToObject(
parsedQueryString || query
);
this.queryStringToObject(parsedQueryString || query);
// Check if deserialization didn't work
if (!deserializedQueryString) {
throw "Unable to deserialize query string";
Expand Down Expand Up @@ -185,7 +220,7 @@ export class CustomLoopbackClient implements ILoopbackClient {
* @param query
*/
static queryStringToObject(query: string): ServerAuthorizationCodeResponse {
const obj: {[key:string]:string} = {};
const obj: { [key: string]: string } = {};
const params = query.split("&");
const decode = (s: string) => decodeURIComponent(s.replace(/\+/g, " "));
params.forEach((pair) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,22 @@
* Graph data about the user.
*/
export type UserInfo = {
businessPhones?: Array<string>,
displayName?: string,
givenName?: string,
id?: string,
jobTitle?: string,
mail?: string,
mobilePhone?: string,
officeLocation?: string,
preferredLanguage?: string,
surname?: string,
userPrincipalName?: string
businessPhones?: Array<string>;
displayName?: string;
givenName?: string;
id?: string;
jobTitle?: string;
mail?: string;
mobilePhone?: string;
officeLocation?: string;
preferredLanguage?: string;
surname?: string;
userPrincipalName?: string;
};


/**
* Mail data from MS Graph
*/
export type MailInfo = {
value?: Array<any>
value?: Array<any>;
};
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export default class Main {
// Windows and Linux will quit the application when all windows are closed. In macOS requires explicit quitting
if (process.platform !== "darwin") {
Main.application.quit();
}
}
}

private static requestSingleInstance(): void {
Expand Down Expand Up @@ -91,7 +91,7 @@ export default class Main {
if (Main.mainWindow) {
if (Main.mainWindow.isMinimized()) {
Main.mainWindow.restore();
}
}
Main.mainWindow.focus();
}
}
Expand Down Expand Up @@ -137,7 +137,6 @@ export default class Main {
Main.mainWindow.webContents.send(message, payload);
}


private static async attemptSSOSilent(): Promise<void> {
const tokenRequest = {
scopes: authConfig.resourceApi.scopes,
Expand Down
Loading
Loading