BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / assets / trouter.js

trouter.js

trouter.js 9.8 KiB Download Raw
1(() => {
2 const VERSION = 2;
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 PING_MS = 30000;
9 const SILENCE_LIMIT_MS = 100000;
10 const REREGISTER_MS = 40 * 60 * 1000;
11 const CONNECT_TIMEOUT_MS = 20000;
12 const MAX_BACKOFF_MS = 30000;
13 const MAX_QUEUE = 200;
14 const MAX_PRESENCE_ENTRIES = 1000;
15 const MAX_PRESENCE_FIELD = 128;
16
17 if (window.top !== window || !location.origin.startsWith('https://teams.')) return;
18 const existing = window[GLOBAL_NAME];
19 if (existing && existing.version === VERSION) return;
20 if (existing) existing.shutdown();
21
22 const loadEpid = () => {
23 try {
24 const stored = sessionStorage.getItem(EPID_KEY);
25 if (stored) return stored;
26 const created = crypto.randomUUID();
27 sessionStorage.setItem(EPID_KEY, created);
28 return created;
29 } catch (error) {
30 return crypto.randomUUID();
31 }
32 };
33
34 const state = {
35 token: null, host: null, epid: loadEpid(), socket: null, ready: false,
36 closed: false, ackCounter: 0, lastFrameAt: 0, registeredAt: 0, retry: 0, reconnectTimer: null, queue: [],
37 };
38
39 const flush = () => {
40 const sink = window[BINDING_NAME];
41 if (typeof sink !== 'function') return;
42 while (state.queue.length) {
43 try { sink(JSON.stringify(state.queue[0])); } catch (error) { return; }
44 state.queue.shift();
45 }
46 };
47 const forward = (message) => {
48 state.queue.push(message);
49 if (state.queue.length > MAX_QUEUE) state.queue.shift();
50 flush();
51 };
52 const status = (kind, detail) => forward({channel: 'status', kind, detail: detail || ''});
53 const announceEndpoint = () => forward({channel: 'endpoint', endpointId: state.epid, trouterUri: state.surl + '/unifiedPresenceService'});
54
55 const conversationOf = (resource) => {
56 const link = (resource && (resource.conversationLink || resource.to || resource.id)) || '';
57 const match = /conversations\/([^;\/?]+)/.exec(String(link));
58 const raw = match ? match[1] : String(link).split(';')[0];
59 try { return decodeURIComponent(raw); } catch (error) { return raw; }
60 };
61 const classify = (resourceType, messageType) => {
62 if (resourceType === 'NewMessage') {
63 if (/^Control\/(Clear)?Typing/.test(messageType)) return 'typing';
64 if (messageType === 'ThreadActivity/MemberConsumptionHorizonUpdate') return 'read_receipt';
65 if (/^ThreadActivity\//.test(messageType)) return 'thread_activity';
66 return /^Control\//.test(messageType) ? 'control' : 'new_message';
67 }
68 if (resourceType === 'MessageUpdate') return 'message_update';
69 if (resourceType === 'ThreadUpdate') return 'thread_update';
70 return 'other';
71 };
72 const forwardNotification = (path, body) => {
73 const receivedAt = Date.now();
74 if (path === 'unifiedPresenceService') {
75 const cut = (value) => (typeof value === 'string' ? value.slice(0, MAX_PRESENCE_FIELD) : null);
76 const entries = ((body && Array.isArray(body.presence)) ? body.presence : []).slice(0, MAX_PRESENCE_ENTRIES)
77 .map((entry) => ({mri: cut(entry && entry.mri), availability: cut(entry && entry.presence && entry.presence.availability),
78 activity: cut(entry && entry.presence && entry.presence.activity)}))
79 .filter((entry) => entry.mri && entry.availability);
80 if (entries.length) forward({channel: 'presence', entries});
81 return;
82 }
83 const resource = body && body.resource;
84 const resourceType = String((body && body.resourceType) || path || 'unknown').slice(0, 64);
85 const eventKind = path === 'messaging' ? classify(resourceType, String((resource && resource.messagetype) || '')) : 'other';
86 const messageLike = eventKind === 'new_message' || eventKind === 'message_update';
87 forward({
88 channel: 'event', resourceType, eventKind, receivedAt,
89 conversationId: resource ? conversationOf(resource) || null : null,
90 messageId: messageLike && resource.id ? String(resource.id) : null,
91 });
92 };
93
94 const parseFrame = (data) => {
95 const match = /^(\d):([^:]*):([^:]*)(?::([\s\S]*))?$/.exec(data);
96 return match ? {type: match[1], data: match[4] || ''} : null;
97 };
98 const send = (text) => { if (state.socket && state.socket.readyState === 1) state.socket.send(text); };
99 const sendEvent = (name, args) => send(`5:${++state.ackCounter}+::` + JSON.stringify({name, args}));
100 const activity = () => sendEvent('user.activity', [{state: 'active', cv: crypto.randomUUID()}]);
101
102 const register = async (surl) => {
103 state.surl = surl || state.surl;
104 const body = {
105 clientDescription: {appId: 'TeamsCDLWebWorker', aesKey: '', languageId: 'en-US', platform: 'chrome',
106 templateKey: 'TeamsCDLWebWorker_2.6', platformUIVersion: UI_VERSION},
107 registrationId: state.epid, nodeId: '',
108 transports: {TROUTER: [{context: '', path: state.surl, ttl: 3600}]},
109 };
110 const response = await fetch(REGISTRAR, {
111 method: 'POST', body: JSON.stringify(body),
112 headers: {Authorization: 'Bearer ' + state.token, 'X-MS-Migration': 'True',
113 'Content-Type': 'application/json', Accept: 'application/json, text/javascript'},
114 });
115 if (!response.ok) throw new Error('registrar_http_' + response.status);
116 state.registeredAt = Date.now();
117 };
118 const registerDetail = (error) => (/^registrar_http_\d+$/.test(error && error.message) ? error.message : 'registrar_failed');
119
120 const socketUrl = () => {
121 const clientInfo = JSON.stringify({cv: '2026.36.01.1', ua: 'TeamsCDL', hr: '', v: UI_VERSION});
122 return `wss://${state.host}/v4/c?tc=${encodeURIComponent(clientInfo)}&timeout=40&epid=${state.epid}`
123 + `&ccid=&cor_id=${crypto.randomUUID()}&con_num=${Date.now()}_0`;
124 };
125
126 const scheduleReconnect = () => {
127 if (state.closed || state.reconnectTimer) return;
128 state.retry++;
129 const delay = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** state.retry);
130 state.reconnectTimer = setTimeout(() => { state.reconnectTimer = null; connect(); }, delay);
131 };
132
133 const onFrame = async (socket, message) => {
134 state.lastFrameAt = Date.now();
135 const packet = parseFrame(String(message.data));
136 if (!packet) return;
137 if (packet.type === '1') {
138 send('5:::' + JSON.stringify({name: 'user.authenticate',
139 args: [{headers: {'X-Ms-Test-User': 'False', Authorization: 'Bearer ' + state.token, 'X-MS-Migration': 'True'}}]}));
140 } else if (packet.type === '2') {
141 send('2::');
142 } else if (packet.type === '5') {
143 let event;
144 try { event = JSON.parse(packet.data); } catch (error) { return; }
145 if (event.name === 'trouter.connected') {
146 try {
147 await register(event.args[0].surl);
148 activity();
149 state.ready = true;
150 state.retry = 0;
151 announceEndpoint();
152 status('connected');
153 } catch (error) {
154 status('error', registerDetail(error));
155 socket.close();
156 }
157 } else if (event.name === 'trouter.message_loss') {
158 sendEvent('trouter.processed_message_loss', event.args);
159 const dropped = (event.args && event.args[0] && event.args[0].droppedIndicators) || [];
160 status('message_loss', dropped.map((indicator) => String(indicator.tag)).join(',').slice(0, 200));
161 }
162 } else if (packet.type === '3') {
163 let request;
164 try { request = JSON.parse(packet.data); } catch (error) { return; }
165 send('3:::' + JSON.stringify({id: request.id, status: 200, headers: {}, body: ''}));
166 let body = null;
167 try { body = JSON.parse(request.body); } catch (error) {}
168 forwardNotification(String(request.url || '').replace(/^\/v4\/f\/[^/]+\//, ''), body);
169 }
170 };
171
172 const connect = () => {
173 if (state.closed || state.socket || !state.token || !state.host) return;
174 const socket = state.socket = new WebSocket(socketUrl());
175 state.ready = false;
176 state.lastFrameAt = Date.now();
177 const timer = setTimeout(() => { if (!state.ready) socket.close(); }, CONNECT_TIMEOUT_MS);
178 socket.onmessage = (message) => { onFrame(socket, message); };
179 socket.onerror = () => {};
180 socket.onclose = () => {
181 clearTimeout(timer);
182 if (state.socket !== socket) return;
183 const wasReady = state.ready;
184 state.socket = null;
185 state.ready = false;
186 if (!state.closed) status('disconnected', wasReady ? 'closed' : 'connect_failed');
187 scheduleReconnect();
188 };
189 };
190
191 const maintain = setInterval(() => {
192 if (!state.socket || state.socket.readyState !== 1) return;
193 if (Date.now() - state.lastFrameAt > SILENCE_LIMIT_MS) { state.socket.close(); return; }
194 sendEvent('ping', []);
195 activity();
196 if (state.ready && Date.now() - state.registeredAt > REREGISTER_MS) {
197 register().catch((error) => status('error', registerDetail(error)));
198 }
199 }, PING_MS);
200
201 const shutdown = () => {
202 state.closed = true;
203 clearInterval(maintain);
204 clearTimeout(state.reconnectTimer);
205 if (state.socket) state.socket.close();
206 if (window[GLOBAL_NAME] === api) delete window[GLOBAL_NAME];
207 };
208
209 const api = {
210 version: VERSION,
211 ensure: (config) => {
212 state.token = config.token;
213 state.host = config.host;
214 connect();
215 if (state.ready) {
216 announceEndpoint();
217 status('connected', 'reattached');
218 }
219 flush();
220 return state.ready ? 'ready' : state.socket ? 'connecting' : 'waiting';
221 },
222 shutdown,
223 stop: async () => {
224 let unregistered = null;
225 if (state.token) {
226 try {
227 const response = await fetch(`${REGISTRAR}/${state.epid}`, {
228 method: 'DELETE', headers: {Authorization: 'Bearer ' + state.token, 'X-MS-Migration': 'True'}});
229 unregistered = response.status;
230 } catch (error) {}
231 }
232 shutdown();
233 try { sessionStorage.removeItem(EPID_KEY); } catch (error) {}
234 return {unregistered};
235 },
236 };
237 window[GLOBAL_NAME] = api;
238})();