| 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 | const sealed = []; |
| 7 | let activeHome = null; |
| 8 | let opened = 0; |
| 9 | const take = (key, entry) => { |
| 10 | if (key.endsWith('active-account-filters') && entry.homeAccountId) activeHome = entry.homeAccountId; |
| 11 | if (typeof entry.secret === 'string') entries.push(entry); |
| 12 | }; |
| 13 | for (let index = 0; index < localStorage.length; index++) { |
| 14 | const key = localStorage.key(index); |
| 15 | let entry; |
| 16 | try { entry = JSON.parse(localStorage.getItem(key)); } catch (error) { continue; } |
| 17 | if (!entry || typeof entry !== 'object') continue; |
| 18 | if (entry.id && entry.nonce && entry.data) sealed.push([key, entry]); |
| 19 | else take(key, entry); |
| 20 | } |
| 21 | const plain = entries.length; |
| 22 | // Newer MSAL.js seals its localStorage cache: AES-GCM under a key from the msal.cache.encryption session cookie. |
| 23 | const unseal = async () => { |
| 24 | const cookie = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith('msal.cache.encryption=')); |
| 25 | let sealing = null; |
| 26 | try { sealing = cookie && JSON.parse(decodeURIComponent(cookie.slice(cookie.indexOf('=') + 1))); } catch (error) {} |
| 27 | if (!sealing || !sealing.key || !sealing.id) return; |
| 28 | const bytes = (text) => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=')), |
| 29 | (character) => character.charCodeAt(0)); |
| 30 | const memo = (window.__rustyTeamsUnsealed = window.__rustyTeamsUnsealed || new Map()); |
| 31 | const base = await crypto.subtle.importKey('raw', bytes(sealing.key), 'HKDF', false, ['deriveKey']); |
| 32 | for (const [key, entry] of sealed) { |
| 33 | if (entry.id !== sealing.id) continue; |
| 34 | if (!memo.has(entry.nonce)) { |
| 35 | // MSAL binds an entry to the client id in its key, or to an empty context when the key has none. |
| 36 | const contexts = [...(key.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) || []), '']; |
| 37 | for (const context of new Set(contexts)) { |
| 38 | try { |
| 39 | const derived = await crypto.subtle.deriveKey( |
| 40 | {name: 'HKDF', salt: bytes(entry.nonce), hash: 'SHA-256', info: new TextEncoder().encode(context)}, |
| 41 | base, {name: 'AES-GCM', length: 256}, false, ['decrypt']); |
| 42 | const data = await crypto.subtle.decrypt({name: 'AES-GCM', iv: new Uint8Array(12)}, derived, bytes(entry.data)); |
| 43 | memo.set(entry.nonce, JSON.parse(new TextDecoder().decode(data))); |
| 44 | break; |
| 45 | } catch (error) {} |
| 46 | } |
| 47 | } |
| 48 | if (memo.has(entry.nonce)) { |
| 49 | take(key, memo.get(entry.nonce)); |
| 50 | opened++; |
| 51 | } |
| 52 | } |
| 53 | }; |
| 54 | if (sealed.length) await unseal(); |
| 55 | const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome; |
| 56 | const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1]; |
| 57 | const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {}); |
| 58 | const acquire = async (resource, scope) => { |
| 59 | const base = resource.replace(/\/+$/, ''); |
| 60 | const wanted = (base + '/' + scope).toLowerCase(); |
| 61 | const short = scope.toLowerCase(); |
| 62 | const underResource = (name) => normalize(name).startsWith(base.toLowerCase() + '/'); |
| 63 | const grants = (scopes) => scopes.some(s => (scope === '.default' ? underResource(s) : covers(normalize(s), wanted)) |
| 64 | || (base === 'https://graph.microsoft.com' && covers(s.toLowerCase(), short))); |
| 65 | let token = null, expiresOn = 0; |
| 66 | for (const entry of forceRefresh ? [] : entries) { |
| 67 | if (entry.credentialType !== 'AccessToken' || (entry.tokenType && entry.tokenType !== 'Bearer')) continue; |
| 68 | if (!ownAccount(entry) || (entry.realm && entry.realm !== homeTenant(entry))) continue; |
| 69 | const expires = Number(entry.expiresOn) * 1000; |
| 70 | if (!grants((entry.target || '').split(' ')) || !fresh(expires) || expires <= expiresOn) continue; |
| 71 | token = entry.secret; expiresOn = expires; |
| 72 | } |
| 73 | const cached = cache[base]; |
| 74 | if (!token && !forceRefresh && cached && fresh(cached.expires)) { |
| 75 | if (grants(cached.scopes)) token = cached.token; |
| 76 | else return {token: null, refreshError: `the app is not granted ${scope}`}; |
| 77 | } |
| 78 | const refreshTokens = entries |
| 79 | .filter(entry => entry.credentialType === 'RefreshToken' && ownAccount(entry)) |
| 80 | .filter(entry => !entry.expiresOn || Number(entry.expiresOn) * 1000 > Date.now()) |
| 81 | .sort((first, second) => Number(second.lastUpdatedAt || 0) - Number(first.lastUpdatedAt || 0)); |
| 82 | let refreshError = null; |
| 83 | for (const refreshToken of token ? [] : refreshTokens) { |
| 84 | const form = new URLSearchParams({ |
| 85 | client_id: refreshToken.clientId, grant_type: 'refresh_token', refresh_token: refreshToken.secret, |
| 86 | scope: base + '/.default openid profile offline_access', |
| 87 | }); |
| 88 | try { |
| 89 | const response = await fetch(`https://login.microsoftonline.com/${homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`, |
| 90 | {method: 'POST', body: form}); |
| 91 | const answer = await response.json(); |
| 92 | if (!response.ok) { refreshError = answer.error || `HTTP ${response.status}`; continue; } |
| 93 | const scopes = (answer.scope || '').split(' '); |
| 94 | cache[base] = {token: answer.access_token, scopes, expires: Date.now() + answer.expires_in * 1000}; |
| 95 | if (grants(scopes)) { token = answer.access_token; break; } |
| 96 | refreshError = `the app is not granted ${scope}`; |
| 97 | } catch (error) { |
| 98 | refreshError = String(error); |
| 99 | } |
| 100 | } |
| 101 | return {token, refreshError}; |
| 102 | }; |
| 103 | const {token, refreshError} = await acquire(resource, scope); |
| 104 | const page = {visibility: document.visibilityState, plain, sealed: sealed.length, opened}; |
| 105 | if (!token) return {noToken: true, refreshError, page}; |
| 106 | const run = async (request) => { |
| 107 | try { |
| 108 | let requestBody = request.body; |
| 109 | for (const extra of request.bodyTokens || []) { |
| 110 | const granted = await acquire(extra.resource, extra.scope); |
| 111 | if (!granted.token) return {status: 0, body: `no token for ${extra.resource}`}; |
| 112 | requestBody = requestBody.split(extra.placeholder).join(granted.token); |
| 113 | } |
| 114 | const response = await fetch(request.url, { |
| 115 | method: request.method, |
| 116 | headers: request.anonymous ? request.headers : {Authorization: 'Bearer ' + token, ...request.headers}, |
| 117 | body: request.bodyBase64 ? Uint8Array.from(atob(request.bodyBase64), (character) => character.charCodeAt(0)) : requestBody, |
| 118 | }); |
| 119 | if (request.binary && response.ok) { |
| 120 | const bytes = new Uint8Array(await response.arrayBuffer()); |
| 121 | if (bytes.length > maxBytes) return {status: 413, body: `download is ${bytes.length} bytes, over the ${maxBytes} limit`}; |
| 122 | let binary = ''; |
| 123 | for (let offset = 0; offset < bytes.length; offset += 0x8000) { |
| 124 | binary += String.fromCharCode.apply(null, bytes.subarray(offset, offset + 0x8000)); |
| 125 | } |
| 126 | return {status: response.status, body: {base64: btoa(binary), contentType: response.headers.get('Content-Type')}}; |
| 127 | } |
| 128 | const text = await response.text(); |
| 129 | let body = text; |
| 130 | try { body = text ? JSON.parse(text) : null; } catch (error) {} |
| 131 | return {status: response.status, retryAfter: response.headers.get('Retry-After'), body}; |
| 132 | } catch (error) { |
| 133 | return {status: 0, body: String(error)}; |
| 134 | } |
| 135 | }; |
| 136 | const results = new Array(requests.length); |
| 137 | let next = 0; |
| 138 | const worker = async () => { while (next < requests.length) { const index = next++; results[index] = await run(requests[index]); } }; |
| 139 | await Promise.all(Array.from({length: Math.min(concurrency, requests.length)}, worker)); |
| 140 | return {results}; |
| 141 | }) |