@adobe/helix-onedrive-support 6.2.0 → 7.0.0

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,7 +9,7 @@ jobs:
9
9
  runs-on: ubuntu-latest
10
10
  if: "!contains(github.event.head_commit.message, '[skip ci]')"
11
11
  steps:
12
- - uses: actions/checkout@v2
12
+ - uses: actions/checkout@v3
13
13
  - name: Use Node.js 14.x
14
14
  uses: actions/setup-node@v3
15
15
  with:
package/CHANGELOG.md CHANGED
@@ -1,3 +1,31 @@
1
+ # [7.0.0](https://github.com/adobe/helix-onedrive-support/compare/v6.2.2...v7.0.0) (2022-03-23)
2
+
3
+
4
+ ### Features
5
+
6
+ * add transparent tenant resolution ([dc59dbf](https://github.com/adobe/helix-onedrive-support/commit/dc59dbfc53d767593b82c845c753da3885560852))
7
+
8
+
9
+ ### BREAKING CHANGES
10
+
11
+ * API slightly refactored
12
+ - authorityUrl is now method: `getAuthorityIUrl`
13
+ - new method: `setAccessToken`
14
+
15
+ ## [6.2.2](https://github.com/adobe/helix-onedrive-support/compare/v6.2.1...v6.2.2) (2022-03-20)
16
+
17
+
18
+ ### Bug Fixes
19
+
20
+ * **deps:** update dependency @adobe/helix-fetch to v3.0.7 ([15f9380](https://github.com/adobe/helix-onedrive-support/commit/15f9380b04d28a68b1e39be38c8c913a0cf48fec))
21
+
22
+ ## [6.2.1](https://github.com/adobe/helix-onedrive-support/compare/v6.2.0...v6.2.1) (2022-03-16)
23
+
24
+
25
+ ### Bug Fixes
26
+
27
+ * use http1 for ms access ([#251](https://github.com/adobe/helix-onedrive-support/issues/251)) ([c91a629](https://github.com/adobe/helix-onedrive-support/commit/c91a629fa8c18c0dcdb2a0d21a225de940db05ea)), closes [#250](https://github.com/adobe/helix-onedrive-support/issues/250)
28
+
1
29
  # [6.2.0](https://github.com/adobe/helix-onedrive-support/compare/v6.1.5...v6.2.0) (2022-03-01)
2
30
 
3
31
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adobe/helix-onedrive-support",
3
- "version": "6.2.0",
3
+ "version": "7.0.0",
4
4
  "description": "Helix OneDrive Support",
5
5
  "main": "src/index.js",
6
6
  "types": "src/index.d.ts",
@@ -23,8 +23,9 @@
23
23
  },
24
24
  "homepage": "https://github.com/adobe/helix-onedrive-support#readme",
25
25
  "dependencies": {
26
- "@adobe/helix-fetch": "3.0.6",
27
- "adal-node": "https://github.com/adobe-rnd/azure-activedirectory-library-for-nodejs.git#adobe"
26
+ "@adobe/helix-fetch": "3.0.7",
27
+ "adal-node": "https://github.com/adobe-rnd/azure-activedirectory-library-for-nodejs.git#adobe",
28
+ "jose": "4.6.0"
28
29
  },
29
30
  "devDependencies": {
30
31
  "@adobe/eslint-config-helix": "1.3.2",
@@ -35,13 +36,13 @@
35
36
  "commitizen": "4.2.4",
36
37
  "cz-conventional-changelog": "3.3.0",
37
38
  "dotenv": "16.0.0",
38
- "eslint": "8.10.0",
39
+ "eslint": "8.11.0",
39
40
  "eslint-plugin-header": "3.1.1",
40
41
  "eslint-plugin-import": "2.25.4",
41
42
  "jsdoc-to-markdown": "7.1.1",
42
43
  "junit-report-builder": "3.0.0",
43
- "lint-staged": "12.3.4",
44
- "mocha": "9.2.1",
44
+ "lint-staged": "12.3.7",
45
+ "mocha": "9.2.2",
45
46
  "mocha-multi-reporters": "1.5.1",
46
47
  "nock": "13.2.4",
47
48
  "nyc": "15.1.0",
package/src/OneDrive.d.ts CHANGED
@@ -25,6 +25,7 @@ export declare interface OneDriveOptions {
25
25
  refreshToken?: string;
26
26
  log?: Logger;
27
27
  tenant?: string;
28
+ resource?: string;
28
29
  username?: string;
29
30
  password?: string;
30
31
 
@@ -44,6 +45,18 @@ export declare interface OneDriveOptions {
44
45
  * Note that the cache is only used, if the `noShareLinkCache` flag is `falsy`
45
46
  */
46
47
  shareLinkCache?: Map<string, DriveItem>,
48
+
49
+ /**
50
+ * Disables the cache for the tenant lookup.
51
+ * @default process.env.HELIX_ONEDRIVE_NO_TENANT_CACHE
52
+ */
53
+ noTenantCache?: boolean;
54
+
55
+ /**
56
+ * Map to use for the tenant lookup cache. If empty, a module-global cache will be used.
57
+ * Note that the cache is only used, if the `noTenantCache` flag is `falsy`
58
+ */
59
+ tenantCache?: Map<string, DriveItem>,
47
60
  }
48
61
 
49
62
  export declare interface GraphResult {
@@ -145,7 +158,7 @@ export declare class OneDrive extends EventEmitter {
145
158
  /**
146
159
  * the authority url for login.
147
160
  */
148
- authorityUrl: string;
161
+ getAuthorityUrl(): string;
149
162
 
150
163
  /**
151
164
  * Adds entries to the token cache
@@ -161,6 +174,14 @@ export declare class OneDrive extends EventEmitter {
161
174
  */
162
175
  login(onCode: Function): Promise<TokenResponse>;
163
176
 
177
+ /**
178
+ * Sets the access token to use for all requests. if the token is a valid JWT token,
179
+ * its `tid` claim is used a tenant (if no tenant is already set).
180
+ *
181
+ * @param {string} bearerToken
182
+ */
183
+ setAccessToken(bearerToken);
184
+
164
185
  getAccessToken(autoRefresh: boolean): Promise<TokenResponse>;
165
186
 
166
187
  createLoginUrl(): string;
package/src/OneDrive.js CHANGED
@@ -13,8 +13,9 @@
13
13
  // eslint-disable-next-line max-classes-per-file
14
14
  const EventEmitter = require('events');
15
15
  const { promisify } = require('util');
16
+ const jose = require('jose');
16
17
  const { AuthenticationContext, MemoryCache } = require('adal-node');
17
- const fetchAPI = require('@adobe/helix-fetch');
18
+ const { fetch, reset } = require('@adobe/helix-fetch').keepAliveNoCache({ userAgent: 'helix-fetch' });
18
19
 
19
20
  const Workbook = require('./Workbook.js');
20
21
  const StatusCodeError = require('./StatusCodeError.js');
@@ -22,17 +23,9 @@ const { driveItemFromURL, driveItemToURL } = require('./utils.js');
22
23
  const { splitByExtension, sanitize, editDistance } = require('./fuzzy-helper.js');
23
24
  const SharePointSite = require('./SharePointSite.js');
24
25
 
25
- const { fetch, reset } = process.env.HELIX_FETCH_FORCE_HTTP1
26
- ? fetchAPI.context({
27
- alpnProtocols: [fetchAPI.ALPN_HTTP1_1],
28
- userAgent: 'helix-fetch', // static user agent for test recordings
29
- })
30
- /* istanbul ignore next */
31
- : fetchAPI;
32
-
33
26
  const AZ_AUTHORITY_HOST_URL = 'https://login.windows.net';
34
27
  const AZ_DEFAULT_RESOURCE = 'https://graph.microsoft.com'; // '00000002-0000-0000-c000-000000000000'; ??
35
- const AZ_DEFAULT_TENANT = 'common';
28
+ const AZ_COMMON_TENANT = 'common';
36
29
 
37
30
  /**
38
31
  * the maximum subscription time in milliseconds
@@ -45,27 +38,23 @@ const MAX_SUBSCRIPTION_EXPIRATION_TIME = 4230 * 60 * 1000;
45
38
 
46
39
  /**
47
40
  * map that caches share item data. key is a sharing url, the value a drive item.
48
- * @type {Map<string, *>}
41
+ * @type {Map<string, string>}
49
42
  * @private
50
43
  */
51
44
  const globalShareLinkCache = new Map();
52
45
 
46
+ /**
47
+ * map that caches the tenant ids
48
+ * @type {Map<string, string>}
49
+ */
50
+ const globalTenantCache = new Map();
51
+
53
52
  /**
54
53
  * Helper class that facilitates accessing one drive.
55
54
  */
56
55
  class OneDrive extends EventEmitter {
57
56
  /**
58
57
  * @param {OneDriveOptions} opts Options
59
- * @param {string} opts.clientId The client id of the app
60
- * @param {string} [opts.clientSecret] The client secret of the app
61
- * @param {string} [opts.refreshToken] The refresh token.
62
- * @param {string} [opts.accessToken] The access token.
63
- * @param {string} [opts.username] Username for username/password authentication.
64
- * @param {string} [opts.password] Password for username/password authentication.
65
- * @param {number} [opts.expiresOn] Expiration time.
66
- * @param {Logger} [opts.log] A logger.
67
- * @param {boolean} [opts.localAuthCache] Whether to use local auth cache
68
- * @param {string} [opts.resource] Azure resource to authenticate against. defaults to MS Graph.
69
58
  */
70
59
  constructor(opts) {
71
60
  super(opts);
@@ -75,53 +64,109 @@ class OneDrive extends EventEmitter {
75
64
  this.username = opts.username || '';
76
65
  this.password = opts.password || '';
77
66
  this._log = opts.log || console;
78
- this.tenant = opts.tenant || AZ_DEFAULT_TENANT;
67
+ this.tenant = opts.tenant;
79
68
  this.resource = opts.resource || AZ_DEFAULT_RESOURCE;
69
+ this.localAuthCache = opts.localAuthCache;
80
70
 
81
71
  if (!opts.noShareLinkCache && !process.env.HELIX_ONEDRIVE_NO_SHARE_LINK_CACHE) {
72
+ /** @type {Map<string, string>} */
82
73
  this.shareLinkCache = opts.shareLinkCache || globalShareLinkCache;
83
74
  }
75
+ if (!opts.noTenantCache && !process.env.HELIX_ONEDRIVE_NO_TENANT_CACHE) {
76
+ /** @type {Map<string, string>} */
77
+ this.tenantCache = opts.tenantCache || globalTenantCache;
78
+ }
84
79
 
85
80
  if (!this.clientId) {
86
81
  throw new Error('Missing clientId.');
87
82
  }
88
- this.authContext = new AuthenticationContext(
89
- this.authorityUrl,
90
- undefined,
91
- opts.localAuthCache ? new MemoryCache() : undefined,
92
- );
93
- [
94
- 'acquireUserCode',
95
- 'acquireToken',
96
- 'acquireTokenWithDeviceCode',
97
- 'acquireTokenWithRefreshToken',
98
- 'acquireTokenWithUsernamePassword',
99
- 'acquireTokenWithClientCredentials',
100
- ].forEach((m) => {
101
- this.authContext[m] = promisify(this.authContext[m].bind(this.authContext));
102
- });
103
- const { cache } = this.authContext;
104
- if (opts.localAuthCache) {
105
- const originalAdd = cache.add;
106
- cache.add = (entries, cb) => {
107
- originalAdd.call(cache, entries, (...args) => {
108
- // eslint-disable-next-line no-underscore-dangle
109
- this.emit('tokens', cache._entries);
110
- cb(...args);
111
- });
112
- };
113
- const originalRemove = cache.remove;
114
- cache.remove = (entries, cb) => {
115
- originalRemove.call(cache, entries, (...args) => {
116
- // eslint-disable-next-line no-underscore-dangle
117
- this.emit('tokens', cache._entries);
118
- cb(...args);
119
- });
120
- };
121
- }
122
- cache.add.promise = promisify(cache.add.bind(cache));
123
- cache.remove.promise = promisify(cache.remove.bind(cache));
124
- cache.find.promise = promisify(cache.find.bind(cache));
83
+ }
84
+
85
+ /**
86
+ * Return the auth context
87
+ * @returns {AuthenticationContext}
88
+ */
89
+ async getAuthContext() {
90
+ if (!this.authContext) {
91
+ this.authContext = new AuthenticationContext(
92
+ this.getAuthorityUrl(),
93
+ undefined,
94
+ this.localAuthCache ? new MemoryCache() : undefined,
95
+ );
96
+ [
97
+ 'acquireUserCode',
98
+ 'acquireToken',
99
+ 'acquireTokenWithDeviceCode',
100
+ 'acquireTokenWithRefreshToken',
101
+ 'acquireTokenWithUsernamePassword',
102
+ 'acquireTokenWithClientCredentials',
103
+ ].forEach((m) => {
104
+ this.authContext[m] = promisify(this.authContext[m].bind(this.authContext));
105
+ });
106
+ const { cache } = this.authContext;
107
+ if (this.localAuthCache) {
108
+ const originalAdd = cache.add;
109
+ cache.add = (entries, cb) => {
110
+ originalAdd.call(cache, entries, (...args) => {
111
+ // eslint-disable-next-line no-underscore-dangle
112
+ this.emit('tokens', cache._entries);
113
+ cb(...args);
114
+ });
115
+ };
116
+ const originalRemove = cache.remove;
117
+ cache.remove = (entries, cb) => {
118
+ originalRemove.call(cache, entries, (...args) => {
119
+ // eslint-disable-next-line no-underscore-dangle
120
+ this.emit('tokens', cache._entries);
121
+ cb(...args);
122
+ });
123
+ };
124
+ }
125
+ cache.add.promise = promisify(cache.add.bind(cache));
126
+ cache.remove.promise = promisify(cache.remove.bind(cache));
127
+ cache.find.promise = promisify(cache.find.bind(cache));
128
+ }
129
+ return this.authContext;
130
+ }
131
+
132
+ async resolveTenant(tenantHost) {
133
+ const { log } = this;
134
+ const configUrl = `https://login.windows.net/${tenantHost}.onmicrosoft.com/.well-known/openid-configuration`;
135
+ const res = await fetch(configUrl);
136
+ if (!res.ok) {
137
+ log.info(`error fetching openid-configuration for ${tenantHost}: ${res.status}. Fallback to 'common'`);
138
+ return AZ_COMMON_TENANT;
139
+ }
140
+
141
+ const { issuer } = await res.json();
142
+ if (!issuer) {
143
+ log.info(`unable to extract tenant from openid-configuration for ${tenantHost}: no 'issuer'. Fallback to 'common'`);
144
+ return AZ_COMMON_TENANT;
145
+ }
146
+
147
+ // eslint-disable-next-line prefer-destructuring
148
+ const tenant = new URL(issuer).pathname.split('/')[1];
149
+ log.info(`fetched tenant information from for ${tenantHost}: ${tenant}`);
150
+ return tenant;
151
+ }
152
+
153
+ async initTenantFromShareLink(sharingUrl) {
154
+ if (this.tenant) {
155
+ return;
156
+ }
157
+ const { log } = this;
158
+ const [tenantHost] = new URL(sharingUrl).hostname.split('.');
159
+
160
+ if (this.tenantCache) {
161
+ this.tenant = this.tenantCache.get(tenantHost);
162
+ }
163
+ if (!this.tenant) {
164
+ this.tenant = await this.resolveTenant(tenantHost);
165
+ if (this.tenantCache) {
166
+ this.tenantCache.set(tenantHost, this.tenant);
167
+ }
168
+ }
169
+ log.info(`using tenant ${this.tenant} for ${tenantHost} from ${sharingUrl}`);
125
170
  }
126
171
 
127
172
  /**
@@ -138,7 +183,10 @@ class OneDrive extends EventEmitter {
138
183
  return this._log;
139
184
  }
140
185
 
141
- get authorityUrl() {
186
+ getAuthorityUrl() {
187
+ if (!this.tenant) {
188
+ throw new Error('unable to compute authority url. no tenant.');
189
+ }
142
190
  return `${AZ_AUTHORITY_HOST_URL}/${this.tenant}`;
143
191
  }
144
192
 
@@ -147,7 +195,7 @@ class OneDrive extends EventEmitter {
147
195
  */
148
196
  get authenticated() {
149
197
  // eslint-disable-next-line no-underscore-dangle
150
- return this.authContext.cache._entries.length > 0;
198
+ return this.authContext?.cache._entries.length > 0;
151
199
  }
152
200
 
153
201
  /**
@@ -156,7 +204,7 @@ class OneDrive extends EventEmitter {
156
204
  * @return this;
157
205
  */
158
206
  async loadTokenCache(entries) {
159
- return this.authContext.cache.add.promise(entries);
207
+ return (await this.getAuthContext()).cache.add.promise(entries);
160
208
  }
161
209
 
162
210
  /**
@@ -166,7 +214,8 @@ class OneDrive extends EventEmitter {
166
214
  * @returns {Promise<TokenResponse>}
167
215
  */
168
216
  async login(onCode) {
169
- const { log, authContext: context } = this;
217
+ const { log } = this;
218
+ const context = await this.getAuthContext();
170
219
 
171
220
  let code;
172
221
  try {
@@ -190,9 +239,35 @@ class OneDrive extends EventEmitter {
190
239
  }
191
240
 
192
241
  /**
242
+ * Sets the access token to use for all requests. if the token is a valid JWT token,
243
+ * its `tid` claim is used a tenant (if no tenant is already set).
244
+ *
245
+ * @param {string} bearerToken
193
246
  */
194
- async getAccessToken() {
195
- const { log, authContext: context } = this;
247
+ setAccessToken(bearerToken) {
248
+ const { log } = this;
249
+ this.accessToken = {
250
+ accessToken: bearerToken,
251
+ };
252
+ if (!this.tenant) {
253
+ try {
254
+ const { tid } = jose.decodeJwt(bearerToken);
255
+ if (tid) {
256
+ log.info(`using tenant from access token: ${tid}`);
257
+ this.tenant = tid;
258
+ }
259
+ } catch (e) {
260
+ log.warn(`unable to decode access token: ${e.message}`);
261
+ }
262
+ }
263
+ this.accessToken.tenantId = this.tenant;
264
+ }
265
+
266
+ /**
267
+ */
268
+ async fetchAccessToken() {
269
+ const { log } = this;
270
+ const context = await this.getAuthContext();
196
271
  try {
197
272
  return await context.acquireToken(this.resource, this.username, this.clientId);
198
273
  } catch (e) {
@@ -239,10 +314,17 @@ class OneDrive extends EventEmitter {
239
314
  }
240
315
  }
241
316
 
317
+ async getAccessToken() {
318
+ if (!this.accessToken) {
319
+ this.accessToken = await this.fetchAccessToken();
320
+ }
321
+ return this.accessToken;
322
+ }
323
+
242
324
  /**
243
325
  */
244
326
  createLoginUrl(redirectUri, state) {
245
- return `${this.authorityUrl}/oauth2/authorize?response_type=code&scope=/.default&client_id=${this.clientId}&redirect_uri=${redirectUri}&state=${state}&resource=${this.resource}`;
327
+ return `${this.getAuthorityUrl()}/oauth2/authorize?response_type=code&scope=/.default&client_id=${this.clientId}&redirect_uri=${redirectUri}&state=${state}&resource=${this.resource}`;
246
328
  }
247
329
 
248
330
  async augmentAndCacheResponse(response) {
@@ -267,7 +349,8 @@ class OneDrive extends EventEmitter {
267
349
  /**
268
350
  */
269
351
  async acquireToken(redirectUri, code) {
270
- const { log, authContext: context } = this;
352
+ const { log } = this;
353
+ const context = await this.getAuthContext();
271
354
  try {
272
355
  const resp = await context.acquireTokenWithAuthorizationCode(
273
356
  code,
@@ -350,6 +433,7 @@ class OneDrive extends EventEmitter {
350
433
  /**
351
434
  */
352
435
  async resolveShareLink(sharingUrl) {
436
+ await this.initTenantFromShareLink(sharingUrl);
353
437
  const link = OneDrive.encodeSharingUrl(sharingUrl);
354
438
  this.log.debug(`resolving sharelink ${sharingUrl} (${link})`);
355
439
  try {
@@ -376,6 +460,7 @@ class OneDrive extends EventEmitter {
376
460
  if (driveItem) {
377
461
  return driveItem;
378
462
  }
463
+ await this.initTenantFromShareLink(sharingUrl);
379
464
  if (this.shareLinkCache) {
380
465
  driveItem = this.shareLinkCache.get(sharingUrl);
381
466
  }
@@ -10,18 +10,9 @@
10
10
  * governing permissions and limitations under the License.
11
11
  */
12
12
 
13
- const fetchAPI = require('@adobe/helix-fetch');
13
+ const { fetch } = require('@adobe/helix-fetch').keepAliveNoCache({ userAgent: 'helix-fetch' });
14
14
  const StatusCodeError = require('./StatusCodeError.js');
15
15
 
16
- /* istanbul ignore next */
17
- const { fetch } = process.env.HELIX_FETCH_FORCE_HTTP1
18
- ? fetchAPI.context({
19
- alpnProtocols: [fetchAPI.ALPN_HTTP1_1],
20
- userAgent: 'helix-fetch', // static user agent for test recordings
21
- })
22
- /* istanbul ignore next */
23
- : fetchAPI;
24
-
25
16
  /**
26
17
  * Helper class accessing folders and files using the SharePoint V1 API.
27
18
  */