@quadient/skillshare 1.20.0 → 1.20.2
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.
- package/dist/teams-auth.js +127 -19
- package/package.json +1 -1
package/dist/teams-auth.js
CHANGED
|
@@ -14,7 +14,7 @@ export function decodeTeamsJwt(value) {
|
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
16
|
/** Select only credentials belonging to the Skillshare account. No full browser state leaves this machine. */
|
|
17
|
-
export function extractTeamsSession(state, expectedObjectId, now = Date.now(), allowExpired = false) {
|
|
17
|
+
export function extractTeamsSession(state, expectedObjectId, now = Date.now(), allowExpired = false, skypeOptional = false) {
|
|
18
18
|
if (!uuid.test(expectedObjectId))
|
|
19
19
|
throw new Error('The Microsoft account object id is missing. Sign in to Skillshare in the browser, then run skillshare teams login again.');
|
|
20
20
|
const stores = state.origins.filter(origin => origins.has(origin.origin));
|
|
@@ -91,7 +91,8 @@ export function extractTeamsSession(state, expectedObjectId, now = Date.now(), a
|
|
|
91
91
|
/^\.?(teams\.microsoft\.com|teams\.cloud\.microsoft)$/.test(cookie.domain)) && (allowExpired || Math.min(claims.exp * 1000, cookie.expires * 1000) > now + 30_000);
|
|
92
92
|
})
|
|
93
93
|
.sort((a, b) => b.expires - a.expires)[0];
|
|
94
|
-
|
|
94
|
+
// Teams web no longer always sets skypetoken_asm; the capture then exchanges the Spaces token for one.
|
|
95
|
+
if (!skype && !allowExpired && !skypeOptional)
|
|
95
96
|
return null;
|
|
96
97
|
if (skype)
|
|
97
98
|
tokens.skype = { value: skype.value, expiresAt: new Date(decodeTeamsJwt(skype.value).exp * 1000).toISOString() };
|
|
@@ -151,7 +152,14 @@ export async function captureTeamsLogin(options) {
|
|
|
151
152
|
await abortable(page.goto('https://teams.microsoft.com/v2/', { waitUntil: 'domcontentloaded', timeout: 60_000 }), signal);
|
|
152
153
|
let lastProgress = Date.now();
|
|
153
154
|
let lastRefresh = 0;
|
|
155
|
+
let lastAttemptFresh = false;
|
|
154
156
|
let resetCache = false;
|
|
157
|
+
let lastFailure = '';
|
|
158
|
+
let teamsOpenSince = null;
|
|
159
|
+
let stallRecovery = 'none';
|
|
160
|
+
const stallMs = options.stallMs ?? 60_000;
|
|
161
|
+
// Exchange through the Teams tab so the browser's network, proxy and certificate settings apply, as they do for Teams itself.
|
|
162
|
+
const exchangeSkype = (spacesToken) => browserSkypeExchange(page, spacesToken);
|
|
155
163
|
while (true) {
|
|
156
164
|
signal.throwIfAborted();
|
|
157
165
|
// Read the current Teams tab only. storageState visits every cached origin and can hang
|
|
@@ -170,18 +178,25 @@ export async function captureTeamsLogin(options) {
|
|
|
170
178
|
throw error;
|
|
171
179
|
}
|
|
172
180
|
const state = { origins: [local], cookies: await abortable(context.cookies(), signal) };
|
|
173
|
-
const session = extractTeamsSession(state, options.objectId);
|
|
174
|
-
if (session && !options.recover)
|
|
181
|
+
const session = extractTeamsSession(state, options.objectId, Date.now(), false, true);
|
|
182
|
+
if (session?.tokens.skype && !options.recover)
|
|
175
183
|
return session;
|
|
176
|
-
|
|
184
|
+
// Retry at once when Teams has just replaced stale cached tokens with fresh ones.
|
|
185
|
+
if (origins.has(new URL(page.url()).origin) && (Date.now() - lastRefresh > 30_000 || session && !lastAttemptFresh)) {
|
|
177
186
|
const cached = session ?? extractTeamsSession(state, options.objectId, Date.now(), true);
|
|
178
187
|
if (cached?.refreshToken) {
|
|
179
188
|
lastRefresh = Date.now();
|
|
189
|
+
lastAttemptFresh = !!session;
|
|
180
190
|
try {
|
|
181
|
-
return await abortable(refreshCapturedSession(cached, fetch, options.recover ?? false, signal), signal);
|
|
191
|
+
return await abortable(refreshCapturedSession(cached, fetch, options.recover ?? false, signal, exchangeSkype), signal);
|
|
182
192
|
}
|
|
183
|
-
catch {
|
|
193
|
+
catch (error) {
|
|
184
194
|
signal.throwIfAborted();
|
|
195
|
+
const failure = describeFailure(error);
|
|
196
|
+
if (failure !== lastFailure) {
|
|
197
|
+
lastFailure = failure;
|
|
198
|
+
options.onProgress?.(`Teams sign-in found, but the Teams API tokens could not be completed yet: ${failure} Retrying every 30 seconds.`);
|
|
199
|
+
}
|
|
185
200
|
if (options.recover && !resetCache) {
|
|
186
201
|
resetCache = true;
|
|
187
202
|
// Expired grants can coexist with valid access tokens. Remove only this account's MSAL
|
|
@@ -194,6 +209,27 @@ export async function captureTeamsLogin(options) {
|
|
|
194
209
|
}
|
|
195
210
|
}
|
|
196
211
|
}
|
|
212
|
+
// Time only while Teams itself is open; a Microsoft sign-in page means the user is still signing in.
|
|
213
|
+
teamsOpenSince = origins.has(new URL(page.url()).origin) ? teamsOpenSince ?? Date.now() : null;
|
|
214
|
+
if (!options.recover && teamsOpenSince !== null && Date.now() - teamsOpenSince > stallMs) {
|
|
215
|
+
if (stallRecovery === 'none') {
|
|
216
|
+
stallRecovery = 'reset';
|
|
217
|
+
options.onProgress?.('Teams has provided no API tokens for a minute. Clearing Teams web data in the Skillshare browser profile ' +
|
|
218
|
+
'(Microsoft sign-in cookies are kept) and reloading Teams.');
|
|
219
|
+
await abortable(clearTeamsWebData(page), signal);
|
|
220
|
+
await abortable(page.goto('https://teams.microsoft.com/v2/', { waitUntil: 'domcontentloaded', timeout: 60_000 }), signal);
|
|
221
|
+
teamsOpenSince = null;
|
|
222
|
+
lastRefresh = 0;
|
|
223
|
+
lastAttemptFresh = false;
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
if (stallRecovery === 'reset') {
|
|
227
|
+
stallRecovery = 'hinted';
|
|
228
|
+
options.onProgress?.('Teams still provides no API tokens. Press Ctrl+C, move the Skillshare browser profile aside and run skillshare teams login again; ' +
|
|
229
|
+
`you will sign in to Microsoft once more:\n mv ${JSON.stringify(options.profileDirectory)} ${JSON.stringify(options.profileDirectory + '.bak')}`);
|
|
230
|
+
lastProgress = Date.now();
|
|
231
|
+
}
|
|
232
|
+
}
|
|
197
233
|
if (Date.now() - lastProgress > 30_000) {
|
|
198
234
|
options.onProgress?.('Waiting for Teams sign-in and API tokens. Finish sign-in in the browser; open Teams search if needed.');
|
|
199
235
|
lastProgress = Date.now();
|
|
@@ -223,7 +259,7 @@ function abortable(operation, signal) {
|
|
|
223
259
|
});
|
|
224
260
|
}
|
|
225
261
|
/** The Teams web SPA may not request a search token until search is opened. Reuse its MSAL grant instead. */
|
|
226
|
-
export async function refreshCapturedSession(session, request = fetch, force = false, signal) {
|
|
262
|
+
export async function refreshCapturedSession(session, request = fetch, force = false, signal, exchangeSkype) {
|
|
227
263
|
if (!session.refreshToken)
|
|
228
264
|
throw new Error('A Teams refresh token is required to renew this session.');
|
|
229
265
|
const scopes = {
|
|
@@ -255,22 +291,94 @@ export async function refreshCapturedSession(session, request = fetch, force = f
|
|
|
255
291
|
session.refreshToken = data.refresh_token ?? session.refreshToken;
|
|
256
292
|
}
|
|
257
293
|
if (!session.tokens.skype || new Date(session.tokens.skype.expiresAt).getTime() <= Date.now() + 120_000) {
|
|
258
|
-
const
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
294
|
+
const spaces = session.tokens.spaces.value;
|
|
295
|
+
let skypeToken;
|
|
296
|
+
if (!exchangeSkype)
|
|
297
|
+
skypeToken = await fetchSkypeToken(spaces, request, signal);
|
|
298
|
+
else {
|
|
299
|
+
try {
|
|
300
|
+
skypeToken = await exchangeSkype(spaces);
|
|
301
|
+
}
|
|
302
|
+
catch (browserError) {
|
|
303
|
+
signal?.throwIfAborted();
|
|
304
|
+
try {
|
|
305
|
+
skypeToken = await fetchSkypeToken(spaces, request, signal);
|
|
306
|
+
}
|
|
307
|
+
catch (error) {
|
|
308
|
+
throw new Error(`${describeFailure(browserError)} Direct request: ${describeFailure(error)}`);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
const claims = decodeTeamsJwt(skypeToken);
|
|
268
313
|
if (claims?.skypeid?.replace(/^8:/, '').toLowerCase() !== `orgid:${session.objectId.toLowerCase()}` || claims.tid !== session.tenantId || !claims.exp)
|
|
269
314
|
throw new Error('The renewed Skype token belongs to a different account.');
|
|
270
|
-
session.tokens.skype = { value:
|
|
315
|
+
session.tokens.skype = { value: skypeToken, expiresAt: new Date(claims.exp * 1000).toISOString() };
|
|
271
316
|
}
|
|
272
317
|
return session;
|
|
273
318
|
}
|
|
319
|
+
async function fetchSkypeToken(spacesToken, request, signal) {
|
|
320
|
+
const response = await request('https://authsvc.teams.microsoft.com/v1.0/authz', {
|
|
321
|
+
method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${spacesToken}` },
|
|
322
|
+
body: '{}', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15_000)]) : AbortSignal.timeout(15_000), redirect: 'error',
|
|
323
|
+
});
|
|
324
|
+
if (!response.ok)
|
|
325
|
+
throw new Error(`Teams could not renew the Skype token (HTTP ${response.status}).`);
|
|
326
|
+
const data = await response.json();
|
|
327
|
+
if (typeof data.tokens?.skypeToken !== 'string')
|
|
328
|
+
throw new Error('Teams returned no Skype token.');
|
|
329
|
+
return data.tokens.skypeToken;
|
|
330
|
+
}
|
|
331
|
+
/** Teams web may no longer request a Skype token itself; ask its auth service from the signed-in Teams tab. */
|
|
332
|
+
async function browserSkypeExchange(page, spacesToken) {
|
|
333
|
+
if (!origins.has(new URL(page.url()).origin))
|
|
334
|
+
throw new Error('The Teams tab is not open.');
|
|
335
|
+
const result = await page.evaluate(async (token) => {
|
|
336
|
+
const failures = [];
|
|
337
|
+
for (const url of [`${location.origin}/api/authsvc/v1.0/authz`, 'https://authsvc.teams.microsoft.com/v1.0/authz']) {
|
|
338
|
+
try {
|
|
339
|
+
const response = await fetch(url, { method: 'POST', credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(15_000),
|
|
340
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }, body: '{}' });
|
|
341
|
+
if (!response.ok) {
|
|
342
|
+
failures.push(`HTTP ${response.status}`);
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
const data = await response.json();
|
|
346
|
+
if (typeof data.tokens?.skypeToken === 'string')
|
|
347
|
+
return { token: data.tokens.skypeToken, failures };
|
|
348
|
+
failures.push('no Skype token');
|
|
349
|
+
}
|
|
350
|
+
catch (error) {
|
|
351
|
+
failures.push(error instanceof Error ? error.name : 'request failed');
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return { token: '', failures };
|
|
355
|
+
}, spacesToken);
|
|
356
|
+
if (result.token)
|
|
357
|
+
return result.token;
|
|
358
|
+
throw new Error(`The Teams tab could not obtain a Skype token (${result.failures?.join(', ') || 'unknown'}).`);
|
|
359
|
+
}
|
|
360
|
+
/** Error text for progress output; includes network causes such as certificate errors, never request data. */
|
|
361
|
+
export function describeFailure(error) {
|
|
362
|
+
if (!(error instanceof Error))
|
|
363
|
+
return 'Unknown error.';
|
|
364
|
+
const cause = error.cause instanceof Error && error.cause.message && !error.message.includes(error.cause.message) ? ` (${error.cause.message})` : '';
|
|
365
|
+
return `${error.message}${cause}`.slice(0, 400);
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Teams web can stall on stale cached app data ("Almost there…", "There was a problem reaching this app"). Clear what Teams
|
|
369
|
+
* stores per origin in this dedicated profile, but keep cookies so Microsoft SSO signs Teams in again without a prompt.
|
|
370
|
+
*/
|
|
371
|
+
export async function clearTeamsWebData(page) {
|
|
372
|
+
const session = await page.context().newCDPSession(page);
|
|
373
|
+
try {
|
|
374
|
+
for (const origin of origins)
|
|
375
|
+
await session.send('Storage.clearDataForOrigin', { origin,
|
|
376
|
+
storageTypes: 'local_storage,indexeddb,service_workers,cache_storage,file_systems,websql,shader_cache' });
|
|
377
|
+
}
|
|
378
|
+
finally {
|
|
379
|
+
await session.detach().catch(() => { });
|
|
380
|
+
}
|
|
381
|
+
}
|
|
274
382
|
async function resetTeamsGrant(page, objectId, clientId) {
|
|
275
383
|
if (!origins.has(new URL(page.url()).origin))
|
|
276
384
|
return;
|