| 1 | (() => { |
| 2 | const VERSION = 6; |
| 3 | const GLOBAL_NAME = '__chatsvcTrouter'; |
| 4 | const BINDING_NAME = '__chatsvcRealtime'; |
| 5 | const EPID_KEY = '__chatsvcEpid'; |
| 6 | const REGISTRAR = 'https://teams.cloud.microsoft/registrar/prod/V2/registrations'; |
| 7 | const UI_VERSION = '1415/26091712213'; |
| 8 | const WORKER_REGISTRATION = {appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}; |
| 9 | const CALLING_REGISTRATION = {appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}; |
| 10 | const PING_MS = 30000; |
| 11 | const SILENCE_LIMIT_MS = 100000; |
| 12 | const REREGISTER_MS = 40 * 60 * 1000; |
| 13 | const CONNECT_TIMEOUT_MS = 20000; |
| 14 | const MAX_BACKOFF_MS = 30000; |
| 15 | const ACTIVITY_DEBOUNCE_MS = 1000; |
| 16 | const ACTIVITY_ACK_TIMEOUT_MS = 10000; |
| 17 | const MAX_QUEUE = 200; |
| 18 | const MAX_PRESENCE_ENTRIES = 1000; |
| 19 | const MAX_PRESENCE_FIELD = 128; |
| 20 | const MAX_SENDER_NAME = 256; |
| 21 | const FORWARD_CALLBACKS = false; |
| 22 | const RINGABLE = false; |
| 23 | const CALLBACK_PREFIX = 'callAgent/'; |
| 24 | const CALLBACK_REPLY_TIMEOUT_MS = 5000; |
| 25 | |
| 26 | if (window.top !== window || !location.origin.startsWith('https://teams.')) return; |
| 27 | const existing = window[GLOBAL_NAME]; |
| 28 | if (existing && existing.version === VERSION) return; |
| 29 | if (existing) existing.shutdown(); |
| 30 | |
| 31 | const loadEpid = () => { |
| 32 | try { |
| 33 | const stored = sessionStorage.getItem(EPID_KEY); |
| 34 | if (stored) return stored; |
| 35 | const created = crypto.randomUUID(); |
| 36 | sessionStorage.setItem(EPID_KEY, created); |
| 37 | return created; |
| 38 | } catch (error) { |
| 39 | return crypto.randomUUID(); |
| 40 | } |
| 41 | }; |
| 42 | |
| 43 | const state = { |
| 44 | token: null, host: null, epid: loadEpid(), socket: null, ready: false, |
| 45 | closed: false, activity: 'inactive', sentActivity: null, activityAckId: 0, activityTimer: null, activityResendTimer: null, pendingReplies: new Map(), ackCounter: 0, lastFrameAt: 0, registeredAt: 0, retry: 0, reconnectTimer: null, queue: [], |
| 46 | }; |
| 47 | |
| 48 | const flush = () => { |
| 49 | const sink = window[BINDING_NAME]; |
| 50 | if (typeof sink !== 'function') return; |
| 51 | while (state.queue.length) { |
| 52 | try { sink(JSON.stringify(state.queue[0])); } catch (error) { return; } |
| 53 | state.queue.shift(); |
| 54 | } |
| 55 | }; |
| 56 | const forward = (message) => { |
| 57 | state.queue.push(message); |
| 58 | if (state.queue.length > MAX_QUEUE) state.queue.shift(); |
| 59 | flush(); |
| 60 | }; |
| 61 | const status = (kind, detail) => forward({channel: 'status', kind, detail: detail || ''}); |
| 62 | const announceEndpoint = () => forward({channel: 'endpoint', endpointId: state.epid, trouterUri: state.surl + '/unifiedPresenceService'}); |
| 63 | const headerValue = (headers, name) => { |
| 64 | const key = Object.keys(headers || {}).find((candidate) => candidate.toLowerCase() === name.toLowerCase()); |
| 65 | return key === undefined ? null : String(headers[key]); |
| 66 | }; |
| 67 | const answer = (id, status, body) => { |
| 68 | const pending = state.pendingReplies.get(id); |
| 69 | if (pending === undefined) return false; |
| 70 | clearTimeout(pending.timer); |
| 71 | state.pendingReplies.delete(id); |
| 72 | send('3:::' + JSON.stringify({id, status, headers: pending.headers, body: body || ''})); |
| 73 | return true; |
| 74 | }; |
| 75 | const forwardCallback = (request, path) => { |
| 76 | const headers = request.headers || {}; |
| 77 | const echoed = {}; |
| 78 | for (const name of ['X-Microsoft-Skype-Chain-ID', 'trouter-request']) { |
| 79 | const value = headerValue(headers, name); |
| 80 | if (value !== null) echoed[name] = value; |
| 81 | } |
| 82 | const correlation = headerValue(headers, 'MS-CV'); |
| 83 | if (correlation !== null) echoed['MS-CV'] = correlation + '.0'; |
| 84 | const timer = setTimeout(() => answer(request.id, 200, ''), CALLBACK_REPLY_TIMEOUT_MS); |
| 85 | state.pendingReplies.set(request.id, {timer, headers: echoed}); |
| 86 | forward({channel: 'callback', requestId: request.id, path, |
| 87 | contentEncoding: headerValue(headers, 'X-Microsoft-Skype-Content-Encoding'), |
| 88 | body: typeof request.body === 'string' ? request.body : JSON.stringify(request.body === undefined ? null : request.body)}); |
| 89 | }; |
| 90 | |
| 91 | const conversationOf = (resource) => { |
| 92 | const link = (resource && (resource.conversationLink || resource.to || resource.id)) || ''; |
| 93 | const match = /conversations\/([^;\/?]+)/.exec(String(link)); |
| 94 | const raw = match ? match[1] : String(link).split(';')[0]; |
| 95 | try { return decodeURIComponent(raw); } catch (error) { return raw; } |
| 96 | }; |
| 97 | const classify = (resourceType, messageType) => { |
| 98 | if (resourceType === 'NewMessage') { |
| 99 | if (/^Control\/(Clear)?Typing/.test(messageType)) return 'typing'; |
| 100 | if (messageType === 'ThreadActivity/MemberConsumptionHorizonUpdate') return 'read_receipt'; |
| 101 | if (messageType === 'ThreadActivity/PinnedItemsUpdate') return 'pins_changed'; |
| 102 | if (/^ThreadActivity\//.test(messageType)) return 'thread_activity'; |
| 103 | return /^Control\//.test(messageType) ? 'control' : 'new_message'; |
| 104 | } |
| 105 | if (resourceType === 'MessageUpdate') return 'message_update'; |
| 106 | if (resourceType === 'ThreadUpdate') return 'thread_update'; |
| 107 | return 'other'; |
| 108 | }; |
| 109 | const typingDetails = (resource) => { |
| 110 | const sender = /\/contacts\/8:orgid:([0-9a-f-]{1,64})\/?$/i.exec(String((resource && resource.from) || '')); |
| 111 | const name = resource && resource.imdisplayname; |
| 112 | return { |
| 113 | typing: /^Control\/ClearTyping/.test(String((resource && resource.messagetype) || '')) ? 'clear' : 'start', |
| 114 | senderId: sender ? sender[1] : null, |
| 115 | senderName: typeof name === 'string' ? name.slice(0, MAX_SENDER_NAME) : null, |
| 116 | }; |
| 117 | }; |
| 118 | const forwardNotification = (path, body) => { |
| 119 | const receivedAt = Date.now(); |
| 120 | if (path === 'unifiedPresenceService') { |
| 121 | const cut = (value) => (typeof value === 'string' ? value.slice(0, MAX_PRESENCE_FIELD) : null); |
| 122 | const entries = ((body && Array.isArray(body.presence)) ? body.presence : []).slice(0, MAX_PRESENCE_ENTRIES) |
| 123 | .map((entry) => ({mri: cut(entry && entry.mri), availability: cut(entry && entry.presence && entry.presence.availability), |
| 124 | activity: cut(entry && entry.presence && entry.presence.activity), |
| 125 | outOfOffice: !!(entry && entry.presence && entry.presence.calendarData && entry.presence.calendarData.isOutOfOffice)})) |
| 126 | .filter((entry) => entry.mri && entry.availability); |
| 127 | if (entries.length) forward({channel: 'presence', entries}); |
| 128 | return; |
| 129 | } |
| 130 | const resource = body && body.resource; |
| 131 | const resourceType = String((body && body.resourceType) || path || 'unknown').slice(0, 64); |
| 132 | const eventKind = path === 'messaging' ? classify(resourceType, String((resource && resource.messagetype) || '')) : 'other'; |
| 133 | const messageLike = eventKind === 'new_message' || eventKind === 'message_update'; |
| 134 | forward({ |
| 135 | channel: 'event', resourceType, eventKind, receivedAt, |
| 136 | conversationId: resource ? conversationOf(resource) || null : null, |
| 137 | messageId: messageLike && resource.id ? String(resource.id) : null, |
| 138 | ...(eventKind === 'typing' ? typingDetails(resource) : {}), |
| 139 | }); |
| 140 | }; |
| 141 | |
| 142 | const parseFrame = (data) => { |
| 143 | const match = /^(\d):([^:]*):([^:]*)(?::([\s\S]*))?$/.exec(data); |
| 144 | return match ? {type: match[1], data: match[4] || ''} : null; |
| 145 | }; |
| 146 | const send = (text) => { if (state.socket && state.socket.readyState === 1) state.socket.send(text); }; |
| 147 | const sendEvent = (name, args) => send(`5:${++state.ackCounter}+::` + JSON.stringify({name, args})); |
| 148 | const transmitActivity = (resend) => { |
| 149 | clearTimeout(state.activityTimer); |
| 150 | clearTimeout(state.activityResendTimer); |
| 151 | if (!state.ready) return; |
| 152 | sendEvent('user.activity', [{state: state.activity, cv: crypto.randomUUID()}]); |
| 153 | state.sentActivity = state.activity; |
| 154 | state.activityAckId = state.ackCounter; |
| 155 | if (!resend) state.activityResendTimer = setTimeout(() => transmitActivity(true), ACTIVITY_ACK_TIMEOUT_MS); |
| 156 | }; |
| 157 | const setActivity = (next) => { |
| 158 | if (next !== 'active' && next !== 'inactive') return; |
| 159 | state.activity = next; |
| 160 | clearTimeout(state.activityTimer); |
| 161 | if (!state.ready || next === state.sentActivity) return; |
| 162 | state.activityTimer = setTimeout(() => transmitActivity(false), ACTIVITY_DEBOUNCE_MS); |
| 163 | }; |
| 164 | const acknowledgeActivity = (data) => { |
| 165 | if (Number.parseInt(data, 10) === state.activityAckId) clearTimeout(state.activityResendTimer); |
| 166 | }; |
| 167 | |
| 168 | const register = async (surl) => { |
| 169 | state.surl = surl || state.surl; |
| 170 | const registration = RINGABLE ? CALLING_REGISTRATION : WORKER_REGISTRATION; |
| 171 | const body = { |
| 172 | clientDescription: {appId: registration.appId, aesKey: '', languageId: 'en-US', platform: 'chrome', |
| 173 | templateKey: registration.templateKey, platformUIVersion: UI_VERSION, |
| 174 | ...(RINGABLE ? {productContext: ''} : {})}, |
| 175 | registrationId: state.epid, nodeId: '', |
| 176 | transports: {TROUTER: [{context: '', path: state.surl, ttl: 3600}]}, |
| 177 | }; |
| 178 | const response = await fetch(REGISTRAR, { |
| 179 | method: 'POST', body: JSON.stringify(body), |
| 180 | headers: {Authorization: 'Bearer ' + state.token, 'X-MS-Migration': 'True', |
| 181 | 'Content-Type': 'application/json', Accept: 'application/json, text/javascript'}, |
| 182 | }); |
| 183 | if (!response.ok) throw new Error('registrar_http_' + response.status); |
| 184 | state.registeredAt = Date.now(); |
| 185 | }; |
| 186 | const registerDetail = (error) => (/^registrar_http_\d+$/.test(error && error.message) ? error.message : 'registrar_failed'); |
| 187 | |
| 188 | const socketUrl = () => { |
| 189 | const clientInfo = JSON.stringify({cv: '2026.36.01.1', ua: 'TeamsCDL', hr: '', v: UI_VERSION}); |
| 190 | return `wss://${state.host}/v4/c?tc=${encodeURIComponent(clientInfo)}&timeout=40&epid=${state.epid}` |
| 191 | + `&ccid=&cor_id=${crypto.randomUUID()}&con_num=${Date.now()}_0`; |
| 192 | }; |
| 193 | |
| 194 | const scheduleReconnect = () => { |
| 195 | if (state.closed || state.reconnectTimer) return; |
| 196 | state.retry++; |
| 197 | const delay = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** state.retry); |
| 198 | state.reconnectTimer = setTimeout(() => { state.reconnectTimer = null; connect(); }, delay); |
| 199 | }; |
| 200 | |
| 201 | const onFrame = async (socket, message) => { |
| 202 | state.lastFrameAt = Date.now(); |
| 203 | const packet = parseFrame(String(message.data)); |
| 204 | if (!packet) return; |
| 205 | if (packet.type === '1') { |
| 206 | send('5:::' + JSON.stringify({name: 'user.authenticate', |
| 207 | args: [{headers: {'X-Ms-Test-User': 'False', Authorization: 'Bearer ' + state.token, 'X-MS-Migration': 'True'}}]})); |
| 208 | } else if (packet.type === '2') { |
| 209 | send('2::'); |
| 210 | } else if (packet.type === '5') { |
| 211 | let event; |
| 212 | try { event = JSON.parse(packet.data); } catch (error) { return; } |
| 213 | if (event.name === 'trouter.connected') { |
| 214 | try { |
| 215 | await register(event.args[0].surl); |
| 216 | state.ready = true; |
| 217 | transmitActivity(false); |
| 218 | state.retry = 0; |
| 219 | announceEndpoint(); |
| 220 | status('connected'); |
| 221 | } catch (error) { |
| 222 | status('error', registerDetail(error)); |
| 223 | socket.close(); |
| 224 | } |
| 225 | } else if (event.name === 'trouter.message_loss') { |
| 226 | sendEvent('trouter.processed_message_loss', event.args); |
| 227 | const dropped = (event.args && event.args[0] && event.args[0].droppedIndicators) || []; |
| 228 | status('message_loss', dropped.map((indicator) => String(indicator.tag)).join(',').slice(0, 200)); |
| 229 | } |
| 230 | } else if (packet.type === '6') { |
| 231 | acknowledgeActivity(packet.data); |
| 232 | } else if (packet.type === '3') { |
| 233 | let request; |
| 234 | try { request = JSON.parse(packet.data); } catch (error) { return; } |
| 235 | const path = String(request.url || '').replace(/^\/v4\/f\/[^/]+\//, ''); |
| 236 | if (FORWARD_CALLBACKS && path.startsWith(CALLBACK_PREFIX)) { |
| 237 | forwardCallback(request, path); |
| 238 | return; |
| 239 | } |
| 240 | send('3:::' + JSON.stringify({id: request.id, status: 200, headers: {}, body: ''})); |
| 241 | let body = null; |
| 242 | try { body = JSON.parse(request.body); } catch (error) {} |
| 243 | if (FORWARD_CALLBACKS && body && typeof body.evt === 'number') { |
| 244 | forward({channel: 'callback', requestId: request.id, path: '', contentEncoding: null, |
| 245 | body: typeof request.body === 'string' ? request.body : JSON.stringify(request.body)}); |
| 246 | return; |
| 247 | } |
| 248 | forwardNotification(path, body); |
| 249 | } |
| 250 | }; |
| 251 | |
| 252 | const connect = () => { |
| 253 | if (state.closed || state.socket || !state.token || !state.host) return; |
| 254 | const socket = state.socket = new WebSocket(socketUrl()); |
| 255 | state.ready = false; |
| 256 | state.lastFrameAt = Date.now(); |
| 257 | const timer = setTimeout(() => { if (!state.ready) socket.close(); }, CONNECT_TIMEOUT_MS); |
| 258 | socket.onmessage = (message) => { onFrame(socket, message); }; |
| 259 | socket.onerror = () => {}; |
| 260 | socket.onclose = () => { |
| 261 | clearTimeout(timer); |
| 262 | if (state.socket !== socket) return; |
| 263 | const wasReady = state.ready; |
| 264 | state.socket = null; |
| 265 | state.ready = false; |
| 266 | clearTimeout(state.activityTimer); |
| 267 | clearTimeout(state.activityResendTimer); |
| 268 | if (!state.closed) status('disconnected', wasReady ? 'closed' : 'connect_failed'); |
| 269 | scheduleReconnect(); |
| 270 | }; |
| 271 | }; |
| 272 | |
| 273 | const maintain = setInterval(() => { |
| 274 | if (!state.socket || state.socket.readyState !== 1) return; |
| 275 | if (Date.now() - state.lastFrameAt > SILENCE_LIMIT_MS) { state.socket.close(); return; } |
| 276 | sendEvent('ping', []); |
| 277 | if (state.ready && Date.now() - state.registeredAt > REREGISTER_MS) { |
| 278 | register().catch((error) => status('error', registerDetail(error))); |
| 279 | } |
| 280 | }, PING_MS); |
| 281 | |
| 282 | const shutdown = () => { |
| 283 | state.closed = true; |
| 284 | clearInterval(maintain); |
| 285 | clearTimeout(state.reconnectTimer); |
| 286 | clearTimeout(state.activityTimer); |
| 287 | clearTimeout(state.activityResendTimer); |
| 288 | for (const pending of state.pendingReplies.values()) clearTimeout(pending.timer); |
| 289 | state.pendingReplies.clear(); |
| 290 | if (state.socket) state.socket.close(); |
| 291 | if (window[GLOBAL_NAME] === api) delete window[GLOBAL_NAME]; |
| 292 | }; |
| 293 | |
| 294 | const api = { |
| 295 | version: VERSION, |
| 296 | ensure: (config) => { |
| 297 | state.token = config.token; |
| 298 | state.host = config.host; |
| 299 | setActivity(config.activity); |
| 300 | connect(); |
| 301 | if (state.ready) { |
| 302 | announceEndpoint(); |
| 303 | status('connected', 'reattached'); |
| 304 | } |
| 305 | flush(); |
| 306 | return state.ready ? 'ready' : state.socket ? 'connecting' : 'waiting'; |
| 307 | }, |
| 308 | shutdown, |
| 309 | setActivity, |
| 310 | resendActivity: () => transmitActivity(false), |
| 311 | reply: (id, status, body) => answer(id, status, body), |
| 312 | stop: async () => { |
| 313 | let unregistered = null; |
| 314 | if (state.token) { |
| 315 | try { |
| 316 | const response = await fetch(`${REGISTRAR}/${state.epid}`, { |
| 317 | method: 'DELETE', headers: {Authorization: 'Bearer ' + state.token, 'X-MS-Migration': 'True'}}); |
| 318 | unregistered = response.status; |
| 319 | } catch (error) {} |
| 320 | } |
| 321 | shutdown(); |
| 322 | try { sessionStorage.removeItem(EPID_KEY); } catch (error) {} |
| 323 | return {unregistered}; |
| 324 | }, |
| 325 | }; |
| 326 | window[GLOBAL_NAME] = api; |
| 327 | })(); |