| 1 | (async ({requests, resource, scope, marginMs, concurrency, maxBytes, forceRefresh}) => { |
| 2 | const fresh = (expires) => expires > Date.now() + marginMs; |
| 3 | const normalize = (value) => value.toLowerCase().replace(/\/\/+(?=[^/]*$)/, '/'); |
| 4 | const covers = (value, name) => value === name || value === name + '.all'; |
| 5 | const entries = []; |
| 6 | let activeHome = null; |
| 7 | for (let index = 0; index < localStorage.length; index++) { |
| 8 | const key = localStorage.key(index); |
| 9 | let entry; |
| 10 | try { entry = JSON.parse(localStorage.getItem(key)); } catch (error) { continue; } |
| 11 | if (!entry || typeof entry !== 'object') continue; |
| 12 | if (key.endsWith('active-account-filters') && entry.homeAccountId) activeHome = entry.homeAccountId; |
| 13 | if (typeof entry.secret === 'string') entries.push(entry); |
| 14 | } |
| 15 | const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome; |
| 16 | const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1]; |
| 17 | const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {}); |
| 18 | const acquire = async (resource, scope) => { |
| 19 | const base = resource.replace(/\/+$/, ''); |
| 20 | const wanted = (base + '/' + scope).toLowerCase(); |
| 21 | const short = scope.toLowerCase(); |
| 22 | const underResource = (name) => normalize(name).startsWith(base.toLowerCase() + '/'); |
| 23 | const grants = (scopes) => scopes.some(s => (scope === '.default' ? underResource(s) : covers(normalize(s), wanted)) |
| 24 | || (base === 'https://graph.microsoft.com' && covers(s.toLowerCase(), short))); |
| 25 | let token = null, expiresOn = 0; |
| 26 | for (const entry of forceRefresh ? [] : entries) { |
| 27 | if (entry.credentialType !== 'AccessToken' || (entry.tokenType && entry.tokenType !== 'Bearer')) continue; |
| 28 | if (!ownAccount(entry) || (entry.realm && entry.realm !== homeTenant(entry))) continue; |
| 29 | const expires = Number(entry.expiresOn) * 1000; |
| 30 | if (!grants((entry.target || '').split(' ')) || !fresh(expires) || expires <= expiresOn) continue; |
| 31 | token = entry.secret; expiresOn = expires; |
| 32 | } |
| 33 | const cached = cache[base]; |
| 34 | if (!token && !forceRefresh && cached && fresh(cached.expires)) { |
| 35 | if (grants(cached.scopes)) token = cached.token; |
| 36 | else return {token: null, refreshError: `the app is not granted ${scope}`}; |
| 37 | } |
| 38 | const refreshTokens = entries |
| 39 | .filter(entry => entry.credentialType === 'RefreshToken' && ownAccount(entry)) |
| 40 | .filter(entry => !entry.expiresOn || Number(entry.expiresOn) * 1000 > Date.now()) |
| 41 | .sort((first, second) => Number(second.lastUpdatedAt || 0) - Number(first.lastUpdatedAt || 0)); |
| 42 | let refreshError = null; |
| 43 | for (const refreshToken of token ? [] : refreshTokens) { |
| 44 | const form = new URLSearchParams({ |
| 45 | client_id: refreshToken.clientId, grant_type: 'refresh_token', refresh_token: refreshToken.secret, |
| 46 | scope: base + '/.default openid profile offline_access', |
| 47 | }); |
| 48 | try { |
| 49 | const response = await fetch(`https://login.microsoftonline.com/${homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`, |
| 50 | {method: 'POST', body: form}); |
| 51 | const answer = await response.json(); |
| 52 | if (!response.ok) { refreshError = answer.error || `HTTP ${response.status}`; continue; } |
| 53 | const scopes = (answer.scope || '').split(' '); |
| 54 | cache[base] = {token: answer.access_token, scopes, expires: Date.now() + answer.expires_in * 1000}; |
| 55 | if (grants(scopes)) { token = answer.access_token; break; } |
| 56 | refreshError = `the app is not granted ${scope}`; |
| 57 | } catch (error) { |
| 58 | refreshError = String(error); |
| 59 | } |
| 60 | } |
| 61 | return {token, refreshError}; |
| 62 | }; |
| 63 | const {token, refreshError} = await acquire(resource, scope); |
| 64 | if (!token) return {noToken: true, refreshError}; |
| 65 | const run = async (request) => { |
| 66 | try { |
| 67 | let requestBody = request.body; |
| 68 | for (const extra of request.bodyTokens || []) { |
| 69 | const granted = await acquire(extra.resource, extra.scope); |
| 70 | if (!granted.token) return {status: 0, body: `no token for ${extra.resource}`}; |
| 71 | requestBody = requestBody.split(extra.placeholder).join(granted.token); |
| 72 | } |
| 73 | const response = await fetch(request.url, { |
| 74 | method: request.method, |
| 75 | headers: request.anonymous ? request.headers : {Authorization: 'Bearer ' + token, ...request.headers}, |
| 76 | body: request.bodyBase64 ? Uint8Array.from(atob(request.bodyBase64), (character) => character.charCodeAt(0)) : requestBody, |
| 77 | }); |
| 78 | if (request.binary && response.ok) { |
| 79 | const bytes = new Uint8Array(await response.arrayBuffer()); |
| 80 | if (bytes.length > maxBytes) return {status: 413, body: `download is ${bytes.length} bytes, over the ${maxBytes} limit`}; |
| 81 | let binary = ''; |
| 82 | for (let offset = 0; offset < bytes.length; offset += 0x8000) { |
| 83 | binary += String.fromCharCode.apply(null, bytes.subarray(offset, offset + 0x8000)); |
| 84 | } |
| 85 | return {status: response.status, body: {base64: btoa(binary), contentType: response.headers.get('Content-Type')}}; |
| 86 | } |
| 87 | const text = await response.text(); |
| 88 | let body = text; |
| 89 | try { body = text ? JSON.parse(text) : null; } catch (error) {} |
| 90 | return {status: response.status, retryAfter: response.headers.get('Retry-After'), body}; |
| 91 | } catch (error) { |
| 92 | return {status: 0, body: String(error)}; |
| 93 | } |
| 94 | }; |
| 95 | const results = new Array(requests.length); |
| 96 | let next = 0; |
| 97 | const worker = async () => { while (next < requests.length) { const index = next++; results[index] = await run(requests[index]); } }; |
| 98 | await Promise.all(Array.from({length: Math.min(concurrency, requests.length)}, worker)); |
| 99 | return {results}; |
| 100 | }) |