BlueGit

ict rusty-teams

Files

rusty-teams / crates / session / assets / fetch.js

fetch.js

fetch.js 10.5 KiB Download Raw
1(async ({requests, resource, scope, marginMs, concurrency, maxBytes, forceRefresh, nestedApp, tenant}) => {
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 if (sealed.length) {
23 const unsealEntries = __UNSEAL__;
24 const memo = (window.__rustyTeamsUnsealed = window.__rustyTeamsUnsealed || new Map());
25 for (const [key, entry] of await unsealEntries(sealed, memo)) {
26 take(key, entry);
27 opened++;
28 }
29 }
30 const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;
31 const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];
32 // Without a tenant the account's home tenant; a guest tenant is reached with the same account's refresh token.
33 const inTenant = (entry) => tenant ? entry.realm === tenant : (!entry.realm || entry.realm === homeTenant(entry));
34 const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {});
35 const acquire = async (resource, scope) => {
36 const base = resource.replace(/\/+$/, '');
37 const wanted = (base + '/' + scope).toLowerCase();
38 const short = scope.toLowerCase();
39 const underResource = (name) => normalize(name).startsWith(base.toLowerCase() + '/');
40 const grants = (scopes) => scopes.some(s => (scope === '.default' ? underResource(s) : covers(normalize(s), wanted))
41 || (base === 'https://graph.microsoft.com' && covers(s.toLowerCase(), short)));
42 const cacheKey = [base, nestedApp ? nestedApp.clientId : '', tenant || ''].join('|');
43 let token = null, expiresOn = 0;
44 for (const entry of forceRefresh ? [] : entries) {
45 if (entry.credentialType !== 'AccessToken' || (entry.tokenType && entry.tokenType !== 'Bearer')) continue;
46 if (nestedApp && entry.clientId !== nestedApp.clientId) continue;
47 if (!ownAccount(entry) || !inTenant(entry)) continue;
48 const expires = Number(entry.expiresOn) * 1000;
49 if (!grants((entry.target || '').split(' ')) || !fresh(expires) || expires <= expiresOn) continue;
50 token = entry.secret; expiresOn = expires;
51 }
52 const cached = cache[cacheKey];
53 if (!token && !forceRefresh && cached && fresh(cached.expires)) {
54 if (grants(cached.scopes)) token = cached.token;
55 else return {token: null, refreshError: `the app is not granted ${scope}`};
56 }
57 const refreshTokens = entries
58 .filter(entry => entry.credentialType === 'RefreshToken' && ownAccount(entry))
59 .filter(entry => !entry.expiresOn || Number(entry.expiresOn) * 1000 > Date.now())
60 .sort((first, second) => Number(second.lastUpdatedAt || 0) - Number(first.lastUpdatedAt || 0));
61 let refreshError = null;
62 for (const refreshToken of token ? [] : refreshTokens) {
63 const form = new URLSearchParams({
64 client_id: refreshToken.clientId, grant_type: 'refresh_token', refresh_token: refreshToken.secret,
65 scope: base + '/.default openid profile offline_access',
66 });
67 if (nestedApp) {
68 form.set('client_id', nestedApp.clientId);
69 form.set('brk_client_id', refreshToken.clientId);
70 form.set('redirect_uri', nestedApp.redirectUri);
71 form.set('brk_redirect_uri', nestedApp.brokerRedirectUri);
72 }
73 try {
74 const response = await fetch(`https://login.microsoftonline.com/${tenant || homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`,
75 {method: 'POST', body: form});
76 const answer = await response.json();
77 if (!response.ok) { refreshError = [answer.error || `HTTP ${response.status}`, (answer.error_description || '').split(/\r?\n/)[0]].filter(Boolean).join(': '); continue; }
78 const scopes = (answer.scope || '').split(' ');
79 cache[cacheKey] = {token: answer.access_token, scopes, expires: Date.now() + answer.expires_in * 1000};
80 if (grants(scopes)) { token = answer.access_token; break; }
81 refreshError = `the app is not granted ${scope}`;
82 } catch (error) {
83 refreshError = String(error);
84 }
85 }
86 return {token, refreshError};
87 };
88 const {token, refreshError} = await acquire(resource, scope);
89 const page = {visibility: document.visibilityState, plain, sealed: sealed.length, opened};
90 if (!token) return {noToken: true, refreshError, page};
91 const exchange = (request) => new Promise((resolve) => {
92 const separator = '\u001e';
93 const {handshake, invocations, doneTypes, timeoutMs} = request.signalr;
94 const received = [];
95 let socket = null, settled = false, shookHands = false;
96 const finish = (status) => {
97 if (settled) return;
98 settled = true;
99 clearTimeout(timer);
100 try { socket && socket.close(); } catch (error) {}
101 resolve({status, body: received});
102 };
103 const timer = setTimeout(() => finish(504), timeoutMs);
104 try {
105 socket = new WebSocket(request.url + (request.url.includes('?') ? '&' : '?') + 'access_token=' + encodeURIComponent(token));
106 } catch (error) {
107 clearTimeout(timer);
108 resolve({status: 0, body: String(error)});
109 return;
110 }
111 socket.onopen = () => socket.send(handshake + separator);
112 socket.onmessage = (event) => {
113 for (const part of String(event.data).split(separator)) {
114 let message;
115 try { message = part ? JSON.parse(part) : null; } catch (error) { message = null; }
116 if (!message) continue;
117 if (!shookHands) {
118 shookHands = true;
119 if (message.error) { received.push(message); finish(502); return; }
120 invocations.forEach((invocation) => socket.send(invocation + separator));
121 continue;
122 }
123 if (message.type === 6) { socket.send('{"type":6}' + separator); continue; }
124 received.push(message);
125 if (doneTypes.includes(message.type)) finish(200);
126 }
127 };
128 socket.onerror = () => finish(0);
129 socket.onclose = () => finish(received.length ? 200 : 0);
130 });
131 const converse = (request) => new Promise((resolve) => {
132 const {stages, placeholder, doneMarker, timeoutMs, keepaliveMs} = request.augloop;
133 const received = [];
134 let socket = null, settled = false, stage = 0, keepalive = null;
135 const finish = (status) => {
136 if (settled) return;
137 settled = true;
138 clearTimeout(timer);
139 clearInterval(keepalive);
140 try { socket && socket.close(); } catch (error) {}
141 resolve({status, body: received});
142 };
143 const timer = setTimeout(() => finish(504), timeoutMs);
144 const sendStage = () => {
145 for (const message of stages[stage].send) socket.send(message.split(placeholder).join(token));
146 };
147 try {
148 socket = new WebSocket(request.url);
149 } catch (error) {
150 clearTimeout(timer);
151 resolve({status: 0, body: String(error)});
152 return;
153 }
154 socket.onopen = () => {
155 socket.send('~');
156 keepalive = setInterval(() => socket.send('~'), keepaliveMs);
157 sendStage();
158 };
159 socket.onmessage = (event) => {
160 const text = String(event.data);
161 if (text === '~') return;
162 let message;
163 try { message = JSON.parse(text); } catch (error) { return; }
164 const messageId = String(message.messageId || '');
165 if (messageId.startsWith('s')) socket.send(JSON.stringify({H_: {T_: 'AugLoop_Session_Protocol_Response', B_: []}, messageId}));
166 received.push(message);
167 if (message.error) { finish(502); return; }
168 if (text.includes(doneMarker)) { finish(200); return; }
169 if (stage + 1 < stages.length && messageId === stages[stage].awaitMessageId) {
170 stage++;
171 sendStage();
172 }
173 };
174 socket.onerror = () => finish(0);
175 socket.onclose = () => finish(received.length ? 200 : 0);
176 });
177 const run = async (request) => {
178 if (request.signalr) return exchange(request);
179 if (request.augloop) return converse(request);
180 try {
181 let requestBody = request.body;
182 for (const extra of request.bodyTokens || []) {
183 const granted = await acquire(extra.resource, extra.scope);
184 if (!granted.token) return {status: 0, body: `no token for ${extra.resource}`};
185 requestBody = requestBody.split(extra.placeholder).join(granted.token);
186 }
187 const response = await fetch(request.url, {
188 method: request.method,
189 headers: request.anonymous ? request.headers : {Authorization: 'Bearer ' + token, ...request.headers},
190 body: request.bodyBase64 ? Uint8Array.from(atob(request.bodyBase64), (character) => character.charCodeAt(0)) : requestBody,
191 });
192 if (request.binary && response.ok) {
193 const bytes = new Uint8Array(await response.arrayBuffer());
194 if (bytes.length > maxBytes) return {status: 413, body: `download is ${bytes.length} bytes, over the ${maxBytes} limit`};
195 let binary = '';
196 for (let offset = 0; offset < bytes.length; offset += 0x8000) {
197 binary += String.fromCharCode.apply(null, bytes.subarray(offset, offset + 0x8000));
198 }
199 return {status: response.status, body: {base64: btoa(binary), contentType: response.headers.get('Content-Type')}};
200 }
201 const text = await response.text();
202 let body = text;
203 try { body = text ? JSON.parse(text) : null; } catch (error) {}
204 const location = response.headers.get('Location');
205 if (location) {
206 if (body === null || body === '') body = {location};
207 else if (typeof body === 'object' && body.location == null) body.location = location;
208 }
209 return {status: response.status, retryAfter: response.headers.get('Retry-After'), body};
210 } catch (error) {
211 return {status: 0, body: String(error)};
212 }
213 };
214 const results = new Array(requests.length);
215 let next = 0;
216 const worker = async () => { while (next < requests.length) { const index = next++; results[index] = await run(requests[index]); } };
217 await Promise.all(Array.from({length: Math.min(concurrency, requests.length)}, worker));
218 return {results};
219})