BlueGit

ict rusty-teams

Files

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

trouter.js

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