@quadient/skillshare 1.20.0 → 1.20.1

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.
Files changed (2) hide show
  1. package/dist/teams-auth.js +88 -19
  2. package/package.json +1 -1
@@ -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
- if (!skype && !allowExpired)
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,11 @@ 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
+ // Exchange through the Teams tab so the browser's network, proxy and certificate settings apply, as they do for Teams itself.
159
+ const exchangeSkype = (spacesToken) => browserSkypeExchange(page, spacesToken);
155
160
  while (true) {
156
161
  signal.throwIfAborted();
157
162
  // Read the current Teams tab only. storageState visits every cached origin and can hang
@@ -170,18 +175,25 @@ export async function captureTeamsLogin(options) {
170
175
  throw error;
171
176
  }
172
177
  const state = { origins: [local], cookies: await abortable(context.cookies(), signal) };
173
- const session = extractTeamsSession(state, options.objectId);
174
- if (session && !options.recover)
178
+ const session = extractTeamsSession(state, options.objectId, Date.now(), false, true);
179
+ if (session?.tokens.skype && !options.recover)
175
180
  return session;
176
- if (origins.has(new URL(page.url()).origin) && Date.now() - lastRefresh > 30_000) {
181
+ // Retry at once when Teams has just replaced stale cached tokens with fresh ones.
182
+ if (origins.has(new URL(page.url()).origin) && (Date.now() - lastRefresh > 30_000 || session && !lastAttemptFresh)) {
177
183
  const cached = session ?? extractTeamsSession(state, options.objectId, Date.now(), true);
178
184
  if (cached?.refreshToken) {
179
185
  lastRefresh = Date.now();
186
+ lastAttemptFresh = !!session;
180
187
  try {
181
- return await abortable(refreshCapturedSession(cached, fetch, options.recover ?? false, signal), signal);
188
+ return await abortable(refreshCapturedSession(cached, fetch, options.recover ?? false, signal, exchangeSkype), signal);
182
189
  }
183
- catch {
190
+ catch (error) {
184
191
  signal.throwIfAborted();
192
+ const failure = describeFailure(error);
193
+ if (failure !== lastFailure) {
194
+ lastFailure = failure;
195
+ options.onProgress?.(`Teams sign-in found, but the Teams API tokens could not be completed yet: ${failure} Retrying every 30 seconds.`);
196
+ }
185
197
  if (options.recover && !resetCache) {
186
198
  resetCache = true;
187
199
  // Expired grants can coexist with valid access tokens. Remove only this account's MSAL
@@ -223,7 +235,7 @@ function abortable(operation, signal) {
223
235
  });
224
236
  }
225
237
  /** 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) {
238
+ export async function refreshCapturedSession(session, request = fetch, force = false, signal, exchangeSkype) {
227
239
  if (!session.refreshToken)
228
240
  throw new Error('A Teams refresh token is required to renew this session.');
229
241
  const scopes = {
@@ -255,22 +267,79 @@ export async function refreshCapturedSession(session, request = fetch, force = f
255
267
  session.refreshToken = data.refresh_token ?? session.refreshToken;
256
268
  }
257
269
  if (!session.tokens.skype || new Date(session.tokens.skype.expiresAt).getTime() <= Date.now() + 120_000) {
258
- const response = await request('https://authsvc.teams.microsoft.com/v1.0/authz', {
259
- method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${session.tokens.spaces.value}` },
260
- body: '{}', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15_000)]) : AbortSignal.timeout(15_000), redirect: 'error',
261
- });
262
- if (!response.ok)
263
- throw new Error('Teams could not renew the Skype token.');
264
- const data = await response.json();
265
- if (!data.tokens?.skypeToken)
266
- throw new Error('Teams returned no Skype token.');
267
- const claims = decodeTeamsJwt(data.tokens.skypeToken);
270
+ const spaces = session.tokens.spaces.value;
271
+ let skypeToken;
272
+ if (!exchangeSkype)
273
+ skypeToken = await fetchSkypeToken(spaces, request, signal);
274
+ else {
275
+ try {
276
+ skypeToken = await exchangeSkype(spaces);
277
+ }
278
+ catch (browserError) {
279
+ signal?.throwIfAborted();
280
+ try {
281
+ skypeToken = await fetchSkypeToken(spaces, request, signal);
282
+ }
283
+ catch (error) {
284
+ throw new Error(`${describeFailure(browserError)} Direct request: ${describeFailure(error)}`);
285
+ }
286
+ }
287
+ }
288
+ const claims = decodeTeamsJwt(skypeToken);
268
289
  if (claims?.skypeid?.replace(/^8:/, '').toLowerCase() !== `orgid:${session.objectId.toLowerCase()}` || claims.tid !== session.tenantId || !claims.exp)
269
290
  throw new Error('The renewed Skype token belongs to a different account.');
270
- session.tokens.skype = { value: data.tokens.skypeToken, expiresAt: new Date(claims.exp * 1000).toISOString() };
291
+ session.tokens.skype = { value: skypeToken, expiresAt: new Date(claims.exp * 1000).toISOString() };
271
292
  }
272
293
  return session;
273
294
  }
295
+ async function fetchSkypeToken(spacesToken, request, signal) {
296
+ const response = await request('https://authsvc.teams.microsoft.com/v1.0/authz', {
297
+ method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${spacesToken}` },
298
+ body: '{}', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15_000)]) : AbortSignal.timeout(15_000), redirect: 'error',
299
+ });
300
+ if (!response.ok)
301
+ throw new Error(`Teams could not renew the Skype token (HTTP ${response.status}).`);
302
+ const data = await response.json();
303
+ if (typeof data.tokens?.skypeToken !== 'string')
304
+ throw new Error('Teams returned no Skype token.');
305
+ return data.tokens.skypeToken;
306
+ }
307
+ /** Teams web may no longer request a Skype token itself; ask its auth service from the signed-in Teams tab. */
308
+ async function browserSkypeExchange(page, spacesToken) {
309
+ if (!origins.has(new URL(page.url()).origin))
310
+ throw new Error('The Teams tab is not open.');
311
+ const result = await page.evaluate(async (token) => {
312
+ const failures = [];
313
+ for (const url of [`${location.origin}/api/authsvc/v1.0/authz`, 'https://authsvc.teams.microsoft.com/v1.0/authz']) {
314
+ try {
315
+ const response = await fetch(url, { method: 'POST', credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(15_000),
316
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }, body: '{}' });
317
+ if (!response.ok) {
318
+ failures.push(`HTTP ${response.status}`);
319
+ continue;
320
+ }
321
+ const data = await response.json();
322
+ if (typeof data.tokens?.skypeToken === 'string')
323
+ return { token: data.tokens.skypeToken, failures };
324
+ failures.push('no Skype token');
325
+ }
326
+ catch (error) {
327
+ failures.push(error instanceof Error ? error.name : 'request failed');
328
+ }
329
+ }
330
+ return { token: '', failures };
331
+ }, spacesToken);
332
+ if (result.token)
333
+ return result.token;
334
+ throw new Error(`The Teams tab could not obtain a Skype token (${result.failures?.join(', ') || 'unknown'}).`);
335
+ }
336
+ /** Error text for progress output; includes network causes such as certificate errors, never request data. */
337
+ export function describeFailure(error) {
338
+ if (!(error instanceof Error))
339
+ return 'Unknown error.';
340
+ const cause = error.cause instanceof Error && error.cause.message && !error.message.includes(error.cause.message) ? ` (${error.cause.message})` : '';
341
+ return `${error.message}${cause}`.slice(0, 400);
342
+ }
274
343
  async function resetTeamsGrant(page, objectId, clientId) {
275
344
  if (!origins.has(new URL(page.url()).origin))
276
345
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quadient/skillshare",
3
- "version": "1.20.0",
3
+ "version": "1.20.1",
4
4
  "description": "Skillshare CLI for installing and publishing Quadient skills",
5
5
  "type": "module",
6
6
  "bin": {