@kwiz/node 1.0.15 → 1.0.19

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.
@@ -0,0 +1,24 @@
1
+ # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
2
+ # For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages
3
+
4
+ name: Node.js Package
5
+
6
+ on:
7
+ push:
8
+ tags:
9
+ - 'v*.*.*' # run every time we commit with a new version number
10
+
11
+ jobs:
12
+ build-publish-npm:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: actions/setup-node@v4
17
+ with:
18
+ node-version: 18
19
+ registry-url: https://registry.npmjs.org/
20
+ - run: npm ci
21
+ - run: npm run build
22
+ - run: npm run npm-publish
23
+ env:
24
+ NODE_AUTH_TOKEN: ${{secrets.KWIZ_NPM_TOKEN}}
package/.madgerc CHANGED
@@ -1,3 +1,3 @@
1
- {
2
- "fileExtensions": ["js", "ts"]
1
+ {
2
+ "fileExtensions": ["js", "ts"]
3
3
  }
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 KWIZ Corp
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2024 KWIZ Corp
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,2 +1,2 @@
1
- # node
2
- Common utilities for node applications
1
+ # node
2
+ Common utilities for node applications
@@ -3,3 +3,4 @@ export * from './auth/exports-index';
3
3
  export * from './graph/exports-index';
4
4
  export * from './storage/exports-index';
5
5
  export * from './axios';
6
+ export * from './get-with-cache';
@@ -19,4 +19,5 @@ __exportStar(require("./auth/exports-index"), exports);
19
19
  __exportStar(require("./graph/exports-index"), exports);
20
20
  __exportStar(require("./storage/exports-index"), exports);
21
21
  __exportStar(require("./axios"), exports);
22
+ __exportStar(require("./get-with-cache"), exports);
22
23
  //# sourceMappingURL=exports-index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"exports-index.js","sourceRoot":"","sources":["../src/exports-index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,sDAAoC;AACpC,uDAAqC;AACrC,wDAAsC;AACtC,0DAAwC;AACxC,0CAAwB"}
1
+ {"version":3,"file":"exports-index.js","sourceRoot":"","sources":["../src/exports-index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,sDAAoC;AACpC,uDAAqC;AACrC,wDAAsC;AACtC,0DAAwC;AACxC,0CAAwB;AACxB,mDAAiC"}
@@ -0,0 +1,12 @@
1
+ export declare function getWithCache<T>(worker: () => Promise<{
2
+ success: boolean;
3
+ value: T;
4
+ }>, info: {
5
+ /** seconds */
6
+ successCacheDuration: number;
7
+ /** seconds */
8
+ failedCacheDuration?: number;
9
+ /** must be unique for your call! function name, and parameters */
10
+ cacheKey: string;
11
+ forceRefresh?: boolean;
12
+ }): Promise<any>;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.getWithCache = void 0;
13
+ const common_1 = require("@kwiz/common");
14
+ const $$cache = {};
15
+ function getWithCache(worker, info) {
16
+ return __awaiter(this, void 0, void 0, function* () {
17
+ const now = new Date();
18
+ //purge old values
19
+ Object.keys($$cache).forEach(key => {
20
+ if ($$cache[key].expires < now)
21
+ delete $$cache[key];
22
+ });
23
+ let cached = info.forceRefresh ? null : $$cache[info.cacheKey];
24
+ if ((0, common_1.isNullOrUndefined)(cached)) {
25
+ const result = yield worker();
26
+ if (result.success) {
27
+ $$cache[info.cacheKey] = {
28
+ expires: new Date(new Date().getTime() + info.successCacheDuration * 1000),
29
+ value: result.value
30
+ };
31
+ }
32
+ else if (info.failedCacheDuration > 0) {
33
+ $$cache[info.cacheKey] = {
34
+ expires: new Date(new Date().getTime() + info.failedCacheDuration * 1000),
35
+ value: result.value
36
+ };
37
+ }
38
+ }
39
+ return $$cache[info.cacheKey].value;
40
+ });
41
+ }
42
+ exports.getWithCache = getWithCache;
43
+ //# sourceMappingURL=get-with-cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get-with-cache.js","sourceRoot":"","sources":["../src/get-with-cache.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,yCAA8D;AAE9D,MAAM,OAAO,GAA+C,EAAE,CAAC;AAE/D,SAAsB,YAAY,CAAI,MAAqD,EAAE,IAQ5F;;QACG,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,kBAAkB;QAClB,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;YAC/B,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC,OAAO,GAAG,GAAG;gBAAE,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC;QACxD,CAAC,CAAC,CAAC;QAEH,IAAI,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAE/D,IAAI,IAAA,0BAAiB,EAAC,MAAM,CAAC,EAAE,CAAC;YAC5B,MAAM,MAAM,GAAG,MAAM,MAAM,EAAE,CAAC;YAC9B,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;gBACjB,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG;oBACrB,OAAO,EAAE,IAAI,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC;oBAC1E,KAAK,EAAE,MAAM,CAAC,KAAK;iBACtB,CAAC;YACN,CAAC;iBACI,IAAI,IAAI,CAAC,mBAAmB,GAAG,CAAC,EAAE,CAAC;gBACpC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG;oBACrB,OAAO,EAAE,IAAI,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC;oBACzE,KAAK,EAAE,MAAM,CAAC,KAAK;iBACtB,CAAC;YACN,CAAC;QACL,CAAC;QACD,OAAO,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,KAAK,CAAC;IACxC,CAAC;CAAA;AAjCD,oCAiCC"}
@@ -1,27 +1,27 @@
1
- const glob = require('glob');
2
- const fs = require("fs-extra");
3
- const exportsFileName = "exports-index";
4
- const exportsFileNameWithExt = `${exportsFileName}.ts`;
5
- const exportsIndexFiles = glob.sync(`./src/**/${exportsFileNameWithExt}`);
6
- //loop every exportsIndexFiles and find any import to a directory, and replace with /exports-index
7
- console.time("fixing direcry imports");
8
- exportsIndexFiles.forEach(file => {
9
- var content = fs.readFileSync(file, "utf8").split("\n");
10
- var parentFolderContent = fs.readdirSync(file.replace(exportsFileNameWithExt, ''));
11
- var hasChanges = false;
12
- //loop every import - if it does not match a file in the folder, but matches a sub-folder - append exports-index to it
13
- content.forEach((line, idx) => {
14
- if (line.replace(/ /g, '').length > 0) {
15
- let importName = line.slice(line.indexOf('./') + 2, line.length - 2);
16
- if (parentFolderContent.includes(importName))//its a folder, otherwise it would be .ts
17
- {
18
- content[idx] = line.replace(`./${importName}`, `./${importName}/${exportsFileName}`);
19
- hasChanges = true;
20
- }
21
- }
22
- });
23
- if (hasChanges) {
24
- fs.writeFileSync(file, content.join('\n'));
25
- }
26
- });
1
+ const glob = require('glob');
2
+ const fs = require("fs-extra");
3
+ const exportsFileName = "exports-index";
4
+ const exportsFileNameWithExt = `${exportsFileName}.ts`;
5
+ const exportsIndexFiles = glob.sync(`./src/**/${exportsFileNameWithExt}`);
6
+ //loop every exportsIndexFiles and find any import to a directory, and replace with /exports-index
7
+ console.time("fixing direcry imports");
8
+ exportsIndexFiles.forEach(file => {
9
+ var content = fs.readFileSync(file, "utf8").split("\n");
10
+ var parentFolderContent = fs.readdirSync(file.replace(exportsFileNameWithExt, ''));
11
+ var hasChanges = false;
12
+ //loop every import - if it does not match a file in the folder, but matches a sub-folder - append exports-index to it
13
+ content.forEach((line, idx) => {
14
+ if (line.replace(/ /g, '').length > 0) {
15
+ let importName = line.slice(line.indexOf('./') + 2, line.length - 2);
16
+ if (parentFolderContent.includes(importName))//its a folder, otherwise it would be .ts
17
+ {
18
+ content[idx] = line.replace(`./${importName}`, `./${importName}/${exportsFileName}`);
19
+ hasChanges = true;
20
+ }
21
+ }
22
+ });
23
+ if (hasChanges) {
24
+ fs.writeFileSync(file, content.join('\n'));
25
+ }
26
+ });
27
27
  console.timeEnd("fixing direcry imports");
package/package.json CHANGED
@@ -1,78 +1,78 @@
1
- {
2
- "name": "@kwiz/node",
3
- "version": "1.0.15",
4
- "description": "KWIZ utilities and helpers for node applications",
5
- "module": "dist/index.js",
6
- "types": "dist/index.d.ts",
7
- "exports": {
8
- ".": {
9
- "types": "./dist/index.d.ts",
10
- "import": "./dist/index.js",
11
- "default": "./dist/index.js"
12
- },
13
- "./package.json": "./package.json"
14
- },
15
- "scripts": {
16
- "watch": "tsc -watch",
17
- "build": "npm run reindex-project && npm run test && tsc",
18
- "build-explain": "tsc --explainFiles",
19
- "check-dependencies": "madge --circular ./src",
20
- "create-link": "npm link",
21
- "test": "node --import tsx --test src",
22
- "npm-v-patch": "npm version patch",
23
- "npm-v-major": "npm version major",
24
- "npm-publish": "npm publish --access public",
25
- "reset-repo": "git fetch origin && git reset --hard origin/main",
26
- "__update-kwiz-packages": "npm install @kwiz/common@latest",
27
- "link-local-common": "npm link @kwiz/common",
28
- "reindex-project": "cti create ./src -i _dependencies -w -b -n -o exports-index.ts && node fix-folder-imports.js",
29
- "install-packages": "npm install azurite -g && npm ci",
30
- "startDevStorage": "azurite -s -l"
31
- },
32
- "repository": {
33
- "type": "git",
34
- "url": "git+https://github.com/KWizCom/node.git"
35
- },
36
- "keywords": [
37
- "KWIZ",
38
- "SharePoint",
39
- "SPO",
40
- "Teams",
41
- "Utilities",
42
- "Helpers",
43
- "Node"
44
- ],
45
- "author": "Shai Petel",
46
- "contributors": [
47
- "Shai Petel",
48
- "Kevin Vieira"
49
- ],
50
- "license": "MIT",
51
- "bugs": {
52
- "url": "https://github.com/KWizCom/node/issues",
53
- "email": "support@kwizcom.com"
54
- },
55
- "homepage": "https://github.com/KWizCom/node#readme",
56
- "private": false,
57
- "engines": {
58
- "node": ">=16"
59
- },
60
- "packageManager": "npm@9.5.1",
61
- "devDependencies": {
62
- "@types/node": "^18.19.21",
63
- "create-ts-index": "^1.14.0",
64
- "fs-extra": "^11.2.0",
65
- "madge": "^6.1.0",
66
- "tsx": "^4.7.1",
67
- "typescript": "^5.3.3"
68
- },
69
- "dependencies": {
70
- "@azure/data-tables": "^13.2.2",
71
- "@azure/msal-node": "^2.6.4",
72
- "@kwiz/common": "^1.0.19",
73
- "axios": "^1.6.7",
74
- "esbuild": "^0.19.12",
75
- "get-tsconfig": "^4.7.2",
76
- "resolve-pkg-maps": "^1.0.0"
77
- }
78
- }
1
+ {
2
+ "name": "@kwiz/node",
3
+ "version": "1.0.19",
4
+ "description": "KWIZ utilities and helpers for node applications",
5
+ "module": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "scripts": {
16
+ "watch": "tsc -watch",
17
+ "build": "npm run reindex-project && npm run test && tsc",
18
+ "build-explain": "tsc --explainFiles",
19
+ "check-dependencies": "madge --circular ./src",
20
+ "create-link": "npm link",
21
+ "test": "node --import tsx --test src",
22
+ "npm-v-patch": "npm version patch && git push origin main:main && git push --tags",
23
+ "npm-v-major": "npm version major && git push origin main:main && git push --tags",
24
+ "npm-publish": "npm publish --access public",
25
+ "reset-repo": "git fetch origin && git reset --hard origin/main",
26
+ "__update-kwiz-packages": "npm install @kwiz/common@latest",
27
+ "link-local-common": "npm link @kwiz/common",
28
+ "reindex-project": "cti create ./src -i _dependencies -w -b -n -o exports-index.ts && node fix-folder-imports.js",
29
+ "install-packages": "npm install azurite -g && npm ci",
30
+ "startDevStorage": "azurite -s -l"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/KWizCom/node.git"
35
+ },
36
+ "keywords": [
37
+ "KWIZ",
38
+ "SharePoint",
39
+ "SPO",
40
+ "Teams",
41
+ "Utilities",
42
+ "Helpers",
43
+ "Node"
44
+ ],
45
+ "author": "Shai Petel",
46
+ "contributors": [
47
+ "Shai Petel",
48
+ "Kevin Vieira"
49
+ ],
50
+ "license": "MIT",
51
+ "bugs": {
52
+ "url": "https://github.com/KWizCom/node/issues",
53
+ "email": "support@kwizcom.com"
54
+ },
55
+ "homepage": "https://github.com/KWizCom/node#readme",
56
+ "private": false,
57
+ "engines": {
58
+ "node": ">=16"
59
+ },
60
+ "packageManager": "npm@9.5.1",
61
+ "devDependencies": {
62
+ "@types/node": "^18.19.21",
63
+ "create-ts-index": "^1.14.0",
64
+ "fs-extra": "^11.2.0",
65
+ "madge": "^6.1.0",
66
+ "tsx": "^4.7.1",
67
+ "typescript": "^5.3.3"
68
+ },
69
+ "dependencies": {
70
+ "@azure/data-tables": "^13.2.2",
71
+ "@azure/msal-node": "^2.6.4",
72
+ "@kwiz/common": "^1.0.19",
73
+ "axios": "^1.6.7",
74
+ "esbuild": "^0.19.12",
75
+ "get-tsconfig": "^4.7.2",
76
+ "resolve-pkg-maps": "^1.0.0"
77
+ }
78
+ }
package/src/SPO/common.ts CHANGED
@@ -1,17 +1,17 @@
1
- import { AuthContextType, GetMSALSiteScope, ITenantInfo, isNullOrUndefined } from "@kwiz/common";
2
- import { GetMSALToken } from "../auth/msal";
3
- import { getAxiosConfigBearer } from "../axios";
4
-
5
- var auth: AuthContextType = null;
6
- export function ConfigureSPOAuth(config?: AuthContextType) {
7
- auth = config;
8
- }
9
- export async function getAxiosConfigSharePoint(tenantInfo: ITenantInfo, hostName: string, clearCache?: boolean) {
10
- if (isNullOrUndefined(auth)) throw Error("Call ConfigureSPOAuth first");
11
- // only certificate supported
12
- // DisableCustomAppAuthentication property, that disable this kind of auth., however it can be overriden using this command:
13
- // Set-SPOTenant -DisableCustomAppAuthentication $false
14
- let token = await GetMSALToken(tenantInfo, GetMSALSiteScope(hostName), auth, clearCache);
15
- let config = getAxiosConfigBearer(token, { contantType: "application/json; odata=nometadata" });
16
- return config;
1
+ import { AuthContextType, GetMSALSiteScope, ITenantInfo, isNullOrUndefined } from "@kwiz/common";
2
+ import { GetMSALToken } from "../auth/msal";
3
+ import { getAxiosConfigBearer } from "../axios";
4
+
5
+ var auth: AuthContextType = null;
6
+ export function ConfigureSPOAuth(config?: AuthContextType) {
7
+ auth = config;
8
+ }
9
+ export async function getAxiosConfigSharePoint(tenantInfo: ITenantInfo, hostName: string, clearCache?: boolean) {
10
+ if (isNullOrUndefined(auth)) throw Error("Call ConfigureSPOAuth first");
11
+ // only certificate supported
12
+ // DisableCustomAppAuthentication property, that disable this kind of auth., however it can be overriden using this command:
13
+ // Set-SPOTenant -DisableCustomAppAuthentication $false
14
+ let token = await GetMSALToken(tenantInfo, GetMSALSiteScope(hostName), auth, clearCache);
15
+ let config = getAxiosConfigBearer(token, { contantType: "application/json; odata=nometadata" });
16
+ return config;
17
17
  }
@@ -1,9 +1,9 @@
1
- import assert from 'assert/strict';
2
- import test from 'node:test';
3
- import { DiscoverTenantInfo } from "./discovery";
4
-
5
- test('DiscoverTenantInfo', async t => {
6
- const tenantName = "kwizcom.com";
7
- const tenantInfo = await DiscoverTenantInfo(tenantName);
8
- assert.strictEqual(tenantInfo.idOrName, "7d034656-be03-457d-8d82-60e90cf5f400");
1
+ import assert from 'assert/strict';
2
+ import test from 'node:test';
3
+ import { DiscoverTenantInfo } from "./discovery";
4
+
5
+ test('DiscoverTenantInfo', async t => {
6
+ const tenantName = "kwizcom.com";
7
+ const tenantInfo = await DiscoverTenantInfo(tenantName);
8
+ assert.strictEqual(tenantInfo.idOrName, "7d034656-be03-457d-8d82-60e90cf5f400");
9
9
  });
@@ -1,61 +1,61 @@
1
- import { $AzureEnvironment, GetAzureADLoginEndPoint, GetEnvironmentFromACSEndPoint, ITenantInfo, isNullOrEmptyString, isValidGuid, promiseOnce } from "@kwiz/common";
2
- import axios from "axios";
3
-
4
- export function DiscoverTenantInfo(hostName: string) {
5
- hostName = hostName.toLowerCase();
6
- return promiseOnce(`DiscoverTenantInfo|${hostName}`, async () => {
7
- let data: ITenantInfo = {
8
- environment: $AzureEnvironment.Production,
9
- idOrName: null,
10
- authorityUrl: null,
11
- valid: false
12
- };
13
-
14
- let tenantId: string = null;
15
- let friendlyName: string = null;
16
-
17
- try {
18
- if (hostName.indexOf(".sharepoint.") !== -1) {
19
- let hostParts = hostName.split('.');//should be xxx.sharepoint.com or xxx.sharepoint.us
20
- let firstHostPart = hostParts[0];
21
- let lastHostPart = hostParts[hostParts.length - 1] === "us" || hostParts[hostParts.length - 1] === "de" ? hostParts[hostParts.length - 1] : "com";
22
- if (firstHostPart.endsWith("-admin")) firstHostPart = firstHostPart.substring(0, firstHostPart.length - 6);
23
- friendlyName = `${firstHostPart}.onmicrosoft.${lastHostPart}`;
24
- }
25
- else friendlyName = hostName;//could be an exchange email domain, or bpos customer
26
-
27
- let config = await axios.get<{
28
- token_endpoint: string;//https://login.microsoftonline.com/7d034656-be03-457d-8d82-60e90cf5f400/oauth2/token
29
- cloud_instance_name: string;//microsoftonline.com
30
- token_endpoint_auth_methods_supported: string[];// ["client_secret_post", "private_key_jwt", "client_secret_basic"]
31
- response_modes_supported: string[];// ["query", "fragment", "form_post"]
32
- response_types_supported: string[];// ["code", "id_token", "code id_token", "token id_token", "token"]
33
- scopes_supported: string[];// ["openid"]
34
- issuer: string;//https://sts.windows.net/7d034656-be03-457d-8d82-60e90cf5f400/
35
- authorization_endpoint: string;//https://login.microsoftonline.com/7d034656-be03-457d-8d82-60e90cf5f400/oauth2/authorize
36
- device_authorization_endpoint: string;//https://login.microsoftonline.com/7d034656-be03-457d-8d82-60e90cf5f400/oauth2/devicecode
37
- end_session_endpoint: string;//https://login.microsoftonline.com/7d034656-be03-457d-8d82-60e90cf5f400/oauth2/logout
38
- userinfo_endpoint: string;//https://login.microsoftonline.com/7d034656-be03-457d-8d82-60e90cf5f400/openid/userinfo
39
- tenant_region_scope: string;//NA
40
- cloud_graph_host_name: string;//graph.windows.net
41
- msgraph_host: string;//graph.microsoft.com
42
- }>(`https://login.microsoftonline.com/${friendlyName}/v2.0/.well-known/openid-configuration`);
43
-
44
- let endpoint = config.data.token_endpoint;//https://xxxx/{tenant}/....
45
- tenantId = endpoint.replace("//", "/").split('/')[2];//replace :// with :/ split by / and take the second part.
46
- let instance = config.data.cloud_instance_name;//microsoftonline.us
47
-
48
- data.environment = GetEnvironmentFromACSEndPoint(instance);
49
- if (!isNullOrEmptyString(tenantId) || isValidGuid(tenantId))
50
- data.idOrName = tenantId;
51
- else
52
- data.idOrName = friendlyName;
53
-
54
- data.authorityUrl = `${GetAzureADLoginEndPoint(data.environment)}/${data.idOrName}`;
55
- data.valid = true;
56
- }
57
- catch (e) { }
58
-
59
- return data;
60
- });
1
+ import { $AzureEnvironment, GetAzureADLoginEndPoint, GetEnvironmentFromACSEndPoint, ITenantInfo, isNullOrEmptyString, isValidGuid, promiseOnce } from "@kwiz/common";
2
+ import axios from "axios";
3
+
4
+ export function DiscoverTenantInfo(hostName: string) {
5
+ hostName = hostName.toLowerCase();
6
+ return promiseOnce(`DiscoverTenantInfo|${hostName}`, async () => {
7
+ let data: ITenantInfo = {
8
+ environment: $AzureEnvironment.Production,
9
+ idOrName: null,
10
+ authorityUrl: null,
11
+ valid: false
12
+ };
13
+
14
+ let tenantId: string = null;
15
+ let friendlyName: string = null;
16
+
17
+ try {
18
+ if (hostName.indexOf(".sharepoint.") !== -1) {
19
+ let hostParts = hostName.split('.');//should be xxx.sharepoint.com or xxx.sharepoint.us
20
+ let firstHostPart = hostParts[0];
21
+ let lastHostPart = hostParts[hostParts.length - 1] === "us" || hostParts[hostParts.length - 1] === "de" ? hostParts[hostParts.length - 1] : "com";
22
+ if (firstHostPart.endsWith("-admin")) firstHostPart = firstHostPart.substring(0, firstHostPart.length - 6);
23
+ friendlyName = `${firstHostPart}.onmicrosoft.${lastHostPart}`;
24
+ }
25
+ else friendlyName = hostName;//could be an exchange email domain, or bpos customer
26
+
27
+ let config = await axios.get<{
28
+ token_endpoint: string;//https://login.microsoftonline.com/7d034656-be03-457d-8d82-60e90cf5f400/oauth2/token
29
+ cloud_instance_name: string;//microsoftonline.com
30
+ token_endpoint_auth_methods_supported: string[];// ["client_secret_post", "private_key_jwt", "client_secret_basic"]
31
+ response_modes_supported: string[];// ["query", "fragment", "form_post"]
32
+ response_types_supported: string[];// ["code", "id_token", "code id_token", "token id_token", "token"]
33
+ scopes_supported: string[];// ["openid"]
34
+ issuer: string;//https://sts.windows.net/7d034656-be03-457d-8d82-60e90cf5f400/
35
+ authorization_endpoint: string;//https://login.microsoftonline.com/7d034656-be03-457d-8d82-60e90cf5f400/oauth2/authorize
36
+ device_authorization_endpoint: string;//https://login.microsoftonline.com/7d034656-be03-457d-8d82-60e90cf5f400/oauth2/devicecode
37
+ end_session_endpoint: string;//https://login.microsoftonline.com/7d034656-be03-457d-8d82-60e90cf5f400/oauth2/logout
38
+ userinfo_endpoint: string;//https://login.microsoftonline.com/7d034656-be03-457d-8d82-60e90cf5f400/openid/userinfo
39
+ tenant_region_scope: string;//NA
40
+ cloud_graph_host_name: string;//graph.windows.net
41
+ msgraph_host: string;//graph.microsoft.com
42
+ }>(`https://login.microsoftonline.com/${friendlyName}/v2.0/.well-known/openid-configuration`);
43
+
44
+ let endpoint = config.data.token_endpoint;//https://xxxx/{tenant}/....
45
+ tenantId = endpoint.replace("//", "/").split('/')[2];//replace :// with :/ split by / and take the second part.
46
+ let instance = config.data.cloud_instance_name;//microsoftonline.us
47
+
48
+ data.environment = GetEnvironmentFromACSEndPoint(instance);
49
+ if (!isNullOrEmptyString(tenantId) || isValidGuid(tenantId))
50
+ data.idOrName = tenantId;
51
+ else
52
+ data.idOrName = friendlyName;
53
+
54
+ data.authorityUrl = `${GetAzureADLoginEndPoint(data.environment)}/${data.idOrName}`;
55
+ data.valid = true;
56
+ }
57
+ catch (e) { }
58
+
59
+ return data;
60
+ });
61
61
  }
package/src/auth/msal.ts CHANGED
@@ -1,44 +1,44 @@
1
- import { ConfidentialClientApplication } from "@azure/msal-node";
2
- import { AuthContextType, AuthenticationModes, ITenantInfo } from "@kwiz/common";
3
- //find tenant id? https://login.microsoftonline.com/kwizcom.onmicrosoft.com/.well-known/openid-configuration
4
- //https://stackoverflow.com/questions/54771270/msal-ad-token-not-valid-with-sharepoint-online-csom
5
-
6
- var apps: { [tenant: string]: ConfidentialClientApplication } = {};
7
-
8
- function GetApp(tenantInfo: ITenantInfo, auth: AuthContextType) {
9
- let key = `${tenantInfo.idOrName}|${auth.authenticationMode}`
10
- if (!apps[key]) {
11
- auth.authenticationMode === AuthenticationModes.clientSecret
12
- ? apps[key] = new ConfidentialClientApplication({
13
- auth: {
14
- clientId: auth.clientId,
15
- authority: tenantInfo.authorityUrl,
16
- clientSecret: auth.clientSecret
17
- },
18
-
19
- })
20
- : apps[key] = new ConfidentialClientApplication({
21
- auth: {
22
- clientId: auth.clientId,
23
- authority: tenantInfo.authorityUrl,
24
- clientCertificate: {
25
- thumbprint: auth.thumbprint,
26
- privateKey: auth.privateKey
27
- }
28
- },
29
-
30
- });
31
- }
32
- return apps[key];
33
- }
34
-
35
- /** client secret not supported by SharePoint, must use certificate */
36
- export async function GetMSALToken(tenantInfo: ITenantInfo, scope: string, auth: AuthContextType, clearCache?: boolean) {
37
- const app = GetApp(tenantInfo, auth);
38
- if (clearCache)
39
- app.clearCache();
40
- let token = await app.acquireTokenByClientCredential({
41
- scopes: [`${scope}/.default`]
42
- });
43
- return token.accessToken;
1
+ import { ConfidentialClientApplication } from "@azure/msal-node";
2
+ import { AuthContextType, AuthenticationModes, ITenantInfo } from "@kwiz/common";
3
+ //find tenant id? https://login.microsoftonline.com/kwizcom.onmicrosoft.com/.well-known/openid-configuration
4
+ //https://stackoverflow.com/questions/54771270/msal-ad-token-not-valid-with-sharepoint-online-csom
5
+
6
+ var apps: { [tenant: string]: ConfidentialClientApplication } = {};
7
+
8
+ function GetApp(tenantInfo: ITenantInfo, auth: AuthContextType) {
9
+ let key = `${tenantInfo.idOrName}|${auth.authenticationMode}`
10
+ if (!apps[key]) {
11
+ auth.authenticationMode === AuthenticationModes.clientSecret
12
+ ? apps[key] = new ConfidentialClientApplication({
13
+ auth: {
14
+ clientId: auth.clientId,
15
+ authority: tenantInfo.authorityUrl,
16
+ clientSecret: auth.clientSecret
17
+ },
18
+
19
+ })
20
+ : apps[key] = new ConfidentialClientApplication({
21
+ auth: {
22
+ clientId: auth.clientId,
23
+ authority: tenantInfo.authorityUrl,
24
+ clientCertificate: {
25
+ thumbprint: auth.thumbprint,
26
+ privateKey: auth.privateKey
27
+ }
28
+ },
29
+
30
+ });
31
+ }
32
+ return apps[key];
33
+ }
34
+
35
+ /** client secret not supported by SharePoint, must use certificate */
36
+ export async function GetMSALToken(tenantInfo: ITenantInfo, scope: string, auth: AuthContextType, clearCache?: boolean) {
37
+ const app = GetApp(tenantInfo, auth);
38
+ if (clearCache)
39
+ app.clearCache();
40
+ let token = await app.acquireTokenByClientCredential({
41
+ scopes: [`${scope}/.default`]
42
+ });
43
+ return token.accessToken;
44
44
  }