| 1 | (async ({requests, resource, scope, marginMs, concurrency, maxBytes, forceRefresh, nestedApp}) => { |
| 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 | const cacheKey = nestedApp ? base + '|' + nestedApp.clientId : base; |
| 66 | let token = null, expiresOn = 0; |
| 67 | for (const entry of forceRefresh ? [] : entries) { |
| 68 | if (entry.credentialType !== 'AccessToken' || (entry.tokenType && entry.tokenType !== 'Bearer')) continue; |
| 69 | if (nestedApp && entry.clientId !== nestedApp.clientId) continue; |
| 70 | if (!ownAccount(entry) || (entry.realm && entry.realm !== homeTenant(entry))) continue; |
| 71 | const expires = Number(entry.expiresOn) * 1000; |
| 72 | if (!grants((entry.target || '').split(' ')) || !fresh(expires) || expires <= expiresOn) continue; |
| 73 | token = entry.secret; expiresOn = expires; |
| 74 | } |
| 75 | const cached = cache[cacheKey]; |
| 76 | if (!token && !forceRefresh && cached && fresh(cached.expires)) { |
| 77 | if (grants(cached.scopes)) token = cached.token; |
| 78 | else return {token: null, refreshError: `the app is not granted ${scope}`}; |
| 79 | } |
| 80 | const refreshTokens = entries |
| 81 | .filter(entry => entry.credentialType === 'RefreshToken' && ownAccount(entry)) |
| 82 | .filter(entry => !entry.expiresOn || Number(entry.expiresOn) * 1000 > Date.now()) |
| 83 | .sort((first, second) => Number(second.lastUpdatedAt || 0) - Number(first.lastUpdatedAt || 0)); |
| 84 | let refreshError = null; |
| 85 | for (const refreshToken of token ? [] : refreshTokens) { |
| 86 | const form = new URLSearchParams({ |
| 87 | client_id: refreshToken.clientId, grant_type: 'refresh_token', refresh_token: refreshToken.secret, |
| 88 | scope: base + '/.default openid profile offline_access', |
| 89 | }); |
| 90 | if (nestedApp) { |
| 91 | form.set('client_id', nestedApp.clientId); |
| 92 | form.set('brk_client_id', refreshToken.clientId); |
| 93 | form.set('redirect_uri', nestedApp.redirectUri); |
| 94 | form.set('brk_redirect_uri', nestedApp.brokerRedirectUri); |
| 95 | } |
| 96 | try { |
| 97 | const response = await fetch(`https://login.microsoftonline.com/${homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`, |
| 98 | {method: 'POST', body: form}); |
| 99 | const answer = await response.json(); |
| 100 | if (!response.ok) { refreshError = answer.error || `HTTP ${response.status}`; continue; } |
| 101 | const scopes = (answer.scope || '').split(' '); |
| 102 | cache[cacheKey] = {token: answer.access_token, scopes, expires: Date.now() + answer.expires_in * 1000}; |
| 103 | if (grants(scopes)) { token = answer.access_token; break; } |
| 104 | refreshError = `the app is not granted ${scope}`; |
| 105 | } catch (error) { |
| 106 | refreshError = String(error); |
| 107 | } |
| 108 | } |
| 109 | return {token, refreshError}; |
| 110 | }; |
| 111 | const {token, refreshError} = await acquire(resource, scope); |
| 112 | const page = {visibility: document.visibilityState, plain, sealed: sealed.length, opened}; |
| 113 | if (!token) return {noToken: true, refreshError, page}; |
| 114 | const exchange = (request) => new Promise((resolve) => { |
| 115 | const separator = '\u001e'; |
| 116 | const {handshake, invocations, doneTypes, timeoutMs} = request.signalr; |
| 117 | const received = []; |
| 118 | let socket = null, settled = false, shookHands = false; |
| 119 | const finish = (status) => { |
| 120 | if (settled) return; |
| 121 | settled = true; |
| 122 | clearTimeout(timer); |
| 123 | try { socket && socket.close(); } catch (error) {} |
| 124 | resolve({status, body: received}); |
| 125 | }; |
| 126 | const timer = setTimeout(() => finish(504), timeoutMs); |
| 127 | try { |
| 128 | socket = new WebSocket(request.url + (request.url.includes('?') ? '&' : '?') + 'access_token=' + encodeURIComponent(token)); |
| 129 | } catch (error) { |
| 130 | clearTimeout(timer); |
| 131 | resolve({status: 0, body: String(error)}); |
| 132 | return; |
| 133 | } |
| 134 | socket.onopen = () => socket.send(handshake + separator); |
| 135 | socket.onmessage = (event) => { |
| 136 | for (const part of String(event.data).split(separator)) { |
| 137 | let message; |
| 138 | try { message = part ? JSON.parse(part) : null; } catch (error) { message = null; } |
| 139 | if (!message) continue; |
| 140 | if (!shookHands) { |
| 141 | shookHands = true; |
| 142 | if (message.error) { received.push(message); finish(502); return; } |
| 143 | invocations.forEach((invocation) => socket.send(invocation + separator)); |
| 144 | continue; |
| 145 | } |
| 146 | if (message.type === 6) { socket.send('{"type":6}' + separator); continue; } |
| 147 | received.push(message); |
| 148 | if (doneTypes.includes(message.type)) finish(200); |
| 149 | } |
| 150 | }; |
| 151 | socket.onerror = () => finish(0); |
| 152 | socket.onclose = () => finish(received.length ? 200 : 0); |
| 153 | }); |
| 154 | const converse = (request) => new Promise((resolve) => { |
| 155 | const {stages, placeholder, doneMarker, timeoutMs, keepaliveMs} = request.augloop; |
| 156 | const received = []; |
| 157 | let socket = null, settled = false, stage = 0, keepalive = null; |
| 158 | const finish = (status) => { |
| 159 | if (settled) return; |
| 160 | settled = true; |
| 161 | clearTimeout(timer); |
| 162 | clearInterval(keepalive); |
| 163 | try { socket && socket.close(); } catch (error) {} |
| 164 | resolve({status, body: received}); |
| 165 | }; |
| 166 | const timer = setTimeout(() => finish(504), timeoutMs); |
| 167 | const sendStage = () => { |
| 168 | for (const message of stages[stage].send) socket.send(message.split(placeholder).join(token)); |
| 169 | }; |
| 170 | try { |
| 171 | socket = new WebSocket(request.url); |
| 172 | } catch (error) { |
| 173 | clearTimeout(timer); |
| 174 | resolve({status: 0, body: String(error)}); |
| 175 | return; |
| 176 | } |
| 177 | socket.onopen = () => { |
| 178 | socket.send('~'); |
| 179 | keepalive = setInterval(() => socket.send('~'), keepaliveMs); |
| 180 | sendStage(); |
| 181 | }; |
| 182 | socket.onmessage = (event) => { |
| 183 | const text = String(event.data); |
| 184 | if (text === '~') return; |
| 185 | let message; |
| 186 | try { message = JSON.parse(text); } catch (error) { return; } |
| 187 | const messageId = String(message.messageId || ''); |
| 188 | if (messageId.startsWith('s')) socket.send(JSON.stringify({H_: {T_: 'AugLoop_Session_Protocol_Response', B_: []}, messageId})); |
| 189 | received.push(message); |
| 190 | if (message.error) { finish(502); return; } |
| 191 | if (text.includes(doneMarker)) { finish(200); return; } |
| 192 | if (stage + 1 < stages.length && messageId === stages[stage].awaitMessageId) { |
| 193 | stage++; |
| 194 | sendStage(); |
| 195 | } |
| 196 | }; |
| 197 | socket.onerror = () => finish(0); |
| 198 | socket.onclose = () => finish(received.length ? 200 : 0); |
| 199 | }); |
| 200 | const run = async (request) => { |
| 201 | if (request.signalr) return exchange(request); |
| 202 | if (request.augloop) return converse(request); |
| 203 | try { |
| 204 | let requestBody = request.body; |
| 205 | for (const extra of request.bodyTokens || []) { |
| 206 | const granted = await acquire(extra.resource, extra.scope); |
| 207 | if (!granted.token) return {status: 0, body: `no token for ${extra.resource}`}; |
| 208 | requestBody = requestBody.split(extra.placeholder).join(granted.token); |
| 209 | } |
| 210 | const response = await fetch(request.url, { |
| 211 | method: request.method, |
| 212 | headers: request.anonymous ? request.headers : {Authorization: 'Bearer ' + token, ...request.headers}, |
| 213 | body: request.bodyBase64 ? Uint8Array.from(atob(request.bodyBase64), (character) => character.charCodeAt(0)) : requestBody, |
| 214 | }); |
| 215 | if (request.binary && response.ok) { |
| 216 | const bytes = new Uint8Array(await response.arrayBuffer()); |
| 217 | if (bytes.length > maxBytes) return {status: 413, body: `download is ${bytes.length} bytes, over the ${maxBytes} limit`}; |
| 218 | let binary = ''; |
| 219 | for (let offset = 0; offset < bytes.length; offset += 0x8000) { |
| 220 | binary += String.fromCharCode.apply(null, bytes.subarray(offset, offset + 0x8000)); |
| 221 | } |
| 222 | return {status: response.status, body: {base64: btoa(binary), contentType: response.headers.get('Content-Type')}}; |
| 223 | } |
| 224 | const text = await response.text(); |
| 225 | let body = text; |
| 226 | try { body = text ? JSON.parse(text) : null; } catch (error) {} |
| 227 | const location = response.headers.get('Location'); |
| 228 | if (body === null && location) body = {location}; |
| 229 | return {status: response.status, retryAfter: response.headers.get('Retry-After'), body}; |
| 230 | } catch (error) { |
| 231 | return {status: 0, body: String(error)}; |
| 232 | } |
| 233 | }; |
| 234 | const results = new Array(requests.length); |
| 235 | let next = 0; |
| 236 | const worker = async () => { while (next < requests.length) { const index = next++; results[index] = await run(requests[index]); } }; |
| 237 | await Promise.all(Array.from({length: Math.min(concurrency, requests.length)}, worker)); |
| 238 | return {results}; |
| 239 | }) |