Always Stay Online and Active on Slack with WebSocket Framejacking
Even though Slack is on a dedicated monitor beside you, if you’re not focused on it you’ll appear “away” and “not at your computer”. Do you subconsciously think team members are sleeping when they appear away at 10 am? Let’s always be active until we close the Slack tab or manually set ourselves as away. This is fair: Slack is open somewhere, so we are active.
By changing just four characters in Slack, we can always stay active without going inactive, even after hours and hours with a minimized browser.
Are There Existing Solutions?
Let’s see what kinds of solutions exist or we can think of before we analyze an extremely simple and effective solution.
One solution requires giving away your user name and password to an online service that pretends to be you just enough to convince Slack you are active. Who is to know how safe this is? This doesn’t work for Enterprise Slack that uses SSO authentication.
Another solution is to open Slack in the foreground on your phone and never let your phone sleep. You’ll need a phone and charger.
Yet another solution is to open the Slack desktop app and use a mouse jiggler to prove to Slack you are active and awake. You’d need hardware or some way to nudge your mouse now and then, plus the desktop app.
Others have even written Python, Java, NodeJS, etc. code to generate faux user activity via the Slack API with a personal API key. This seems like a neat idea, but the API changes now and then, and it is unclear how to how to change the user status. We like don’t have Enterprise Slack access to the API.
You might consider writing a self-refreshing iframe
that just loads Slack over and over again. Slack sets the X-Frame-Options
header to sameorigin
, so Slack will not even load in an iframe. Good thinking, though.
Another interesting solution is to fire up a web-testing framework like Selenium to load a headless browser that “clicks” around Slack now and again. Some steps are needed to enter your credentials (and hope the UI doesn’t change and a Captcha doesn’t appear), plus the programming knowledge required is high. This likely doesn’t work with Enterprise Slack and SSO authentication.
Let’s Arrive at a Neat Solution Together
As a rewarding read, let’s arrive at this solution together by asking ourselves some questions.
Let’s open Chrome DevTools and watch the console, XHR network requests, and WebSocket frames.
We see that when the browser loses focus and then is made active again, some console messages appear, but there are no similar WebSocket messages.
Let’s try that. We can easily remove all blur
event listeners using DevTools like so.
When we focus on another window or minimize the Slack window, no blur
events fire. So far, so good. Now we wait for thirty minutes to see if we go inactive.
Some time goes by …
Darn. We went inactive. Let’s see what network requests took place.
There were no unusual XHR requests, but there are some interesting WebSocket frames.
Did you notice these messages are response frames? We’ve now learned the server told us that we went inactive, but no browser event effectuated it.
Let see if there are any interesting messages when we return to an inactive Slack window.
The server again told us we became active when we entered the browser window.
Let’s click around the Slack channels and type some messages and observe the WebSocket.
We see a common typing message when we initiate typing. We also see an uncommon tickle message occurring when the browser goes out of focus then back in focus followed by a click. These are the only two innocuous events to signal activity.
No. There is a sequential id
in the sent message frames. We cannot replay one of these messages under a JavaScript setInterval()
, for example.
id
in the sequence for spoofing?We could be clever and try to keep track of the current sequence id, then replay a doctored activity message with an id++
. We’d likely invalidate the next message with the genuine id
, or even enter a race condition with an asynchronous invocation in the Slack web Service Worker.
Here is the logic used to keep track of the sequence ids if you are curious.
It’s unclear if the sequence id is synchronized across new WebSockets, or if the sequences are reset or otherwise independent. Besides, Slack can modify its implementation at any time, say to send even-numbered sequence ids instead. Let’s not be over-clever with the sequence ids and move forward on the assumption we cannot predict the sequence.
Let’s look at some background messages and see what candidates there are for framejacking (my term for hijacking a WebSocket frame). A WebSocket, being a stream, may have a message fitting in a single frame, which is the case for most Slack messages. Let’s look.
Ping! Every ten seconds or so a ping is sent to the server and a pong is received. A ping message has the same format as the tickle message.
Let’s see if we can spoof a tickle message by changing the four characters “ping” to “tickle” in framejacked ping messages every few minutes (more on that soon). Possibly simple and elegant.
Yes and no. Granted, it’s trivial to MITM WebSockets, known as intercepting, and make modifications. To save you a few hours, I’ll tell you that WebSockets close and open and are even killed over time, so effort needs to be invested to ensure we always framejack the correct socket.
setInterval()
for framejacking all sockets?No. I’ll save you yet more time. Over the day, many sockets may be instantiated so many setInterval
timers would be pending, and stacked internal timers can behave poorly, especially if variable references go out of scope in the meantime.
A wiser implementation is to not use timers as all and make use of timestamps whereby each incoming message kicks off some elapsed-time check to initiate the faux activity.
Yes. WebSockets use a heartbeat protocol to know to keep the socket open on the server. Slack uses a ten-second ping-pong challenge with sequential messages, and the client-side JavaScript has a pong watchdog that will close the socket if one pong is missed.
Here, every ten seconds a check for a pong
with the same id as the ping
is performed. If a matching pong
is not found within ninety seconds, the client closes the socket. There is more logic in the send()
method involving a buffer, but one missing pong
will hold up the check.
Let’s not interfere with the Slack JavaScript or try to hack private variables. Should we prevent the socket from being closed? Here is an experiment I ran by editing the cache of a Slack JavaScript file.
What happened is no more pings were sent after one ping
was framejacked and then Slack just stopped working a short while later.
Instead, let’s intercept the ping
, massage it into a tickle
, and “receive” a well-crafted pong
into the WebSocket layer so the client-side JavaScript is satisfied.
It’s trivial to spoof a pong
from the DevTools console, but we shouldn’t be satisfied sending a simple JSON string as a pong
, though; let’s really forge a trusted EventMessage
with all the trappings and attributes of a real message received on the wire. This makes it future-proof as well.
To save you yet more time, one cannot just forge a trusted EventMessage
object (a real message received by WebSocket) and modify it; some engineering needs to be done to tamper with a read-only event message to return a valid pong
, such as making the data
attribute writeable.
It’s okay to admit that forging a trusted message is exciting. What we’ve done is saved a reference to a real pong
(which we cannot easily clone), and made the data attribute writeable.
Yes. Slack uses a Service Worker that runs in the background in its own thread outside the rendering thread. Web Service Workers are responsible for sending alerts, updating charts, syncing data, and more.
Here is a console log of the script functioning well while the browser is minimized and hidden.
The Slack: Always Stay Active Script
We only need Chrome (or Brave) with a popular1 browser extension called Tampermonkey to inject some JavaScript just on Slack pages.
This started as a proof of concept but expanded to include visual feedback and integrity checks to indicate if Slack changed something pertinent to our workflow. You can even remotely stop the script on all your browsers on different machines. You can still set yourself away manually as well. The script is laid out so it is easy to follow and verify its safety. Enjoy.
Quick Start
A thin orange line appears while Slack boots, then it becomes green when active.
If it goes red, internal sanity checks have failed so Slack has changed something major. This is designed to be future-proof, but if Slack changes tickle
to, say, caress
or nudge
, then that is a breaking change to which we can still adapt.
Advanced Features
Send yourself these messages to control the script across all of your open Slack windows.
sigkill!
– close all your open Slack windows.sighup!
– refresh all your open Slack windows.
Console Commands
You can test out the script from the DevTools console with the following invocations:
slackasa.ticklenow()
– Framejack the next pong to signal activity now.slackasa.listsockets()
– List all the open sockets and timestamps.slackasa.reload()
– Reload the page.
Installation Steps
Step 1. Add Tampermonkey to Chrome.
Step 2. Create a new empty userscript without saving.
Step 3. Copy and paste the script at the bottom of the page. Save. Close Tampermonkey.
Step 4. Visit Slack. Find the Tampermonkey icon, and enable Tempermonkey and the ‘Slack: Always Stay Active’ userscript. Reload Slack.
Discussion
This started out as a mental exercise in finding a way to keep Slack active. Personally, I’m on web Slack all the time with it open on several computers and my phone, so at least once every thirty minutes I cause activity.
However, sometimes I’m engrossed in my IDE for long stretches and even though Slack is on a dedicated monitor beside me, I look “away” and “not at my computer” – far from it. Does this happen to you too?
Full Script
This was written and developed in vanilla JavaScript in the Tampermonkey script editor in my spare time over the weekend. Encapsulation isn’t perfect as it’s not transpiled from TypeScript. The goal is to make it easy to read and understand. Why not publish this script? To require users to examine the code and verify it is safe as a habit. If you share this script, kindly attribute it. Thank you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 | // ==UserScript== // @name Slack: Always Stay Active // @namespace https://ericdraken.com/slack-always-stay-active // @version 1.0.1 // @description Always stay active on Slack. // @author Eric Draken (ericdraken.com) // @match https://app.slack.com/client/* // @icon https://www.google.com/s2/favicons?domain=slack.com // @grant unsafeWindow // @run-at document-start // ==/UserScript== /* eslint-disable no-proto */ /* eslint-disable accessor-pairs */ /* eslint-disable no-global-assign */ ((window, mutateEvent) => { 'use strict'; const INACTIVE_THRESHOLD_SECS = 60 * 5; const PING_THRESHOLD_SECS = 60; const PAGE_ERROR_THRESHOLD = 10; const GREEN = '#2bac76'; const YELLOW = '#ac7f2b'; const RED = '#ac3e2b'; const GREY = '#d0d0d0'; /** Do not change below this line **/ const APPNAME = 'SLACK_ASA'; const PING_MSG = {"type": "ping", "id": null}; const PONG_MSG = {"type": "pong", "reply_to": null}; const TYPING_MSG = {"type": "typing", "channel": null, "id": null}; const TICKLE_MSG = {"type": "tickle", "id": null}; const PRESENCE_ACTIVE_MSG = {"type": "presence_change", "presence": "active", "users": [null]}; const PRESENCE_AWAY_MSG = {"type": "presence_change", "presence": "away", "users": [null]}; const MANUAL_PRESENCE_ACTIVE_MSG = {"type": "manual_presence_change", "presence": "active"}; const MANUAL_PRESENCE_AWAY_MSG = {"type": "manual_presence_change", "presence": "away"}; const TEXT_MSG = {"type": "message", "user": null, "text": null}; const PULSE_CLASS = 'asa-pulse'; let errorCount = 0; let userId = '--not set--'; // Prefix our messages with the app name and WS id for console filtering const protoConsole = { _socketId: '', _console: window.console || false, _doLog(level, color, ...args) { const ind = this._socketId !== '' ? `[${this._socketId}]` : ''; this._console && this._console[level](`%c${APPNAME}${ind}:`, `color: ${color}`, ...args); }, log(...args) { this._doLog('log', GREEN, ...args); }, info(...args) { this._doLog('info', GREEN, ...args); }, error(...args) { this._doLog('error', RED, ...args); }, debug(...args) { this._doLog('debug', YELLOW, ...args); } }; // Root logger const console = Object.assign({}, protoConsole, {_socketId: ''}); const statusDiv = { id: 'SAA229064402df15c8079ac', // Something random _div: null, getStatusDiv() { if (this._div && this._div.style) { return this._div; } this._div = document.createElement('div'); this._div.id = this.id; this._div.style.cssText = '' + 'display:block;position:fixed;overflow:hidden;' + 'top:0;left:0;width:100%;height:2px;opacity:0.5;' + 'z-index:2147483647;background:#fff;' document.body.appendChild(this._div); // Animation - pulse effect on the banner const style = document.createElement('style'); style.innerHTML = ` .${PULSE_CLASS} { animation-direction: normal; animation: asapulse linear 1s 1; } @keyframes asapulse { 0% { -webkit-transform:scale(1); -moz-transform:scale(1); -ms-transform:scale(1); -o-transform:scale(1); transform:scale(1); } 70% { -webkit-transform:scale(4); -moz-transform:scale(4); -ms-transform:scale(4); -o-transform:scale(4); transform:scale(4); } 100% { -webkit-transform:scale(1); -moz-transform:scale(1); -ms-transform:scale(1); -o-transform:scale(1); transform:scale(1); } }`; document.head.appendChild(style); return this._div; }, setActive() { const div = this.getStatusDiv(); if (div.dataset.bg !== GREEN) { console.log('Set active'); } div.dataset.bg = div.style.background = GREEN; }, setAway() { const div = this.getStatusDiv(); if (div.dataset.bg !== GREY) { console.log('Set away'); } div.dataset.bg = div.style.background = GREY; }, setBooting() { const div = this.getStatusDiv(); div.style.background = YELLOW; this.doPulse(); console.debug('Set booting'); }, setProblem(e) { const div = this.getStatusDiv(); div.style.background = RED; this.doPulse(); console.error(`Problem: ${e}`); }, doPulse() { const div = this.getStatusDiv(); div.classList.remove(PULSE_CLASS); div.getClientRects(); // Trigger a reflow div.classList.add(PULSE_CLASS); console.debug('Do pulse'); } }; // Of all the multiple XHR objects, only intercept the boot request's user id const xhrProtoOpen = window.XMLHttpRequest.prototype.open; window.XMLHttpRequest.prototype.open = function () { const that = this; if (window.XMLHttpRequest.prototype.open !== xhrProtoOpen) { window.XMLHttpRequest.prototype.open = xhrProtoOpen; that.addEventListener('load', (ev) => { const xConsole = Object.assign({}, protoConsole, {_socketId: 'XHR'}); const bootData = JSON.parse(ev.currentTarget.responseText); // Get the logged-in user id try { userId = bootData.self.id; xConsole.log('My Slack user id:', userId); } catch (e) { xConsole.error('Unable to get the logged in user id. Commands disabled.'); xConsole.log(JSON.stringify(bootData, null, 2)); } }); } xhrProtoOpen.apply(that, arguments); }; const objMatchesProto = (protoMsg, testObj, contains) => { return Object.keys(protoMsg).every(key => { if (protoMsg[key] === null) { // Nulls in the proto values can be wild, but must exist return typeof testObj[key] !== 'undefined'; } else if ((protoMsg[key] || {}).constructor === Array && (testObj[key] || {}).constructor === Array) { return testObj[key].includes(contains); } return protoMsg[key] === testObj[key]; }); }; const WebSocketProxy = new Proxy(window.WebSocket, { construct(wsTarget, wsArgs) { const ws = new wsTarget(...wsArgs); // Configurable hooks ws.hooks = { interceptSend: () => null, listenReceive: () => null }; // WS details ws.details = { _ws: ws, _console: {}, _wantsActive: true, _hasProblem: false, _isPingChannel: false, _lastPingSent: Date.now(), _lastTickleSent: Date.now(), _protoMessageEvent: undefined, debug() { return { _wantsActive: this._wantsActive, _hasProblem: this._hasProblem, _isPingChannel: this._isPingChannel, _lastPingSent: this._lastPingSent, _lastTickleSent: this._lastTickleSent, }; }, wantsActive() { return this._wantsActive === true; }, wantsAway() { return this._wantsActive === false; }, lastTickleElapsed() { return Date.now() - this._lastTickleSent; }, clearTickleTimestamp() { this._ws.console.debug('Clearing last tickle timestamp'); this._lastTickleSent = 0; }, lastPingElapsed() { return Date.now() - this._lastPingSent; }, isSocketReady() { return this._isPingChannel; }, hasTickleProblem() { // If a tickle hasn't been sent in a while, return false return this.lastTickleElapsed() > (INACTIVE_THRESHOLD_SECS + 120) * 1000; }, hasSocketProblem() { return this.lastPingElapsed() > PING_THRESHOLD_SECS * 1000; }, hasPresenceProblem() { return !(this.wantsActive() || this.wantsAway()); }, checkHasAnyInternalProblem() { return this.hasSocketProblem() && this.hasTickleProblem() && this.hasPresenceProblem(); }, updateState() { if (!this._hasProblem) { if (this.hasTickleProblem()) { this._hasProblem = true; statusDiv.setProblem('A tickle has not been sent lately'); } else if (this.hasSocketProblem()) { this._hasProblem = true; statusDiv.setProblem('Pings are not being sent on time'); } else if (this.hasPresenceProblem()) { this._hasProblem = true; statusDiv.setProblem(`Manual presence change type is unknown: ${this._wantsActive}`); } else if (this.isSocketReady()) { // Set the bar color to active or away if (this.wantsActive()) { statusDiv.setActive(); } else if (this.wantsAway()) { statusDiv.setAway(); } } } else if (!this.checkHasAnyInternalProblem()) { this._hasProblem = false; } } }; // Intercept send ws.send = new Proxy(ws.send, { apply(target, thisArg, args) { ws.hooks.interceptSend(args, ws); ws.details.updateState(); return target.apply(thisArg, args); } }); // Listen for messages ws.addEventListener('message', function (event) { ws.hooks.listenReceive(event, ws); }); // Connection opened ws.addEventListener('open', function (event) { ws.console.log(`Open: ${event.target.url}`); statusDiv.setBooting(); }); // Connection closed ws.addEventListener('close', function (event) { statusDiv.setBooting(); ws.console.log(`Close: ${event}`); errorOverwatch('Socket closed'); }); // Connection error ws.addEventListener('error', function (event) { statusDiv.setBooting(); errorOverwatch(event); }); ws.hooks.listenReceive = (event, currWs) => { const details = currWs.details; if (event && event.data) { let obj = JSON.parse(event.data); if (objMatchesProto(PONG_MSG, obj)) { // Get one pong message event as a prototype if (!details._protoMessageEvent) { mutateEvent(event); event.data = obj; details._protoMessageEvent = event; currWs.console.log('Got proto pong message event', details._protoMessageEvent); } } // Detect manually away else if (objMatchesProto(MANUAL_PRESENCE_AWAY_MSG, obj)) { currWs.console.debug(`Manual away change detected: ${event.data}`); details._wantsActive = false; details.updateState(); } // Detect manually active else if (objMatchesProto(MANUAL_PRESENCE_ACTIVE_MSG, obj)) { currWs.console.debug(`Manual active change detected: ${event.data}`); details._wantsActive = true; details.updateState(); } // Detect network away else if (objMatchesProto(PRESENCE_AWAY_MSG, obj, userId)) { currWs.console.debug(`Away update detected: ${event.data}`); details._wantsActive = false; details.updateState(); } // Detect network active else if (objMatchesProto(PRESENCE_ACTIVE_MSG, obj, userId)) { currWs.console.debug(`Active update detected: ${event.data}`); details._wantsActive = true; details.updateState(); } // Listen for user commands else if (objMatchesProto(TEXT_MSG, obj)) { const keys = Object.keys(TEXT_MSG); if (obj[keys[1]] === userId) { const msg = (obj[keys[2]] || '').trim().toLowerCase(); switch (msg) { case 'sigkill!': case 'sigterm!': currWs.console.log('User SIGKILL received. Closing this window.'); document.location.href = 'about:blank'; break; case 'sighup!': currWs.console.log('User SIGHUP received. Reloading this window.'); document.location = document.location; break; } } } } }; ws.hooks.interceptSend = (data, currWs) => { const details = currWs.details; if (data && data.constructor === Array) { let payload = data[0]; let obj = JSON.parse(payload); if (objMatchesProto(PING_MSG, obj)) { if (details._isPingChannel !== true) { details._isPingChannel = true; statusDiv.setBooting(); currWs.console.log(`Found the ping socket: ${data}`); } details._lastPingSent = Date.now(); // Hijack ping and replace with tickle if (ws.details.isSocketReady()) { details.updateState(); let tickleElapsed = ws.details.lastTickleElapsed(); if (tickleElapsed > INACTIVE_THRESHOLD_SECS * 1000) { currWs.console.log(`Last activity ${tickleElapsed / 1000}s ago. Sending activity notification`); details._lastTickleSent = Date.now(); // Pass by reference const typeKey = Object.keys(PING_MSG)[0]; const idKey = Object.keys(PING_MSG)[1]; obj[typeKey] = TICKLE_MSG[typeKey]; data[0] = JSON.stringify(obj); statusDiv.doPulse(); setTimeout((_ws, id) => { // Send a fake pong into the socket to fulfill the promise const replyKey = Object.keys(PONG_MSG)[1]; const pong = Object.assign({}, PONG_MSG, {[replyKey]: id}); _ws.console.debug('Sending a fake pong', pong); _ws.details._protoMessageEvent.data = pong; _ws.onmessage(_ws.details._protoMessageEvent); }, 500, currWs, obj[idKey]); } } } else if (objMatchesProto(TICKLE_MSG, obj) || objMatchesProto(TYPING_MSG, obj)) { currWs.console.log(`Genuine activity notification: ${data}`); details._lastTickleSent = Date.now(); } } } // Save reference window._websockets = window._websockets || []; window._websockets.push(ws); // One console per websocket ws.console = Object.assign({}, protoConsole, {_socketId: window._websockets.length - 1}); return ws; } }); // Catch oddball errors const errorOverwatch = (e) => { if (e && e.target && e.target === 'img') { return; } errorCount++; protoConsole.error(errorCount, e); if (errorCount >= PAGE_ERROR_THRESHOLD) { console.info("Too many errors. Reloading the page."); document.location = document.location; } }; ['error', 'unhandledrejection'].forEach((name) => { window.addEventListener(name, errorOverwatch, {capture: true}); }); window.error = errorOverwatch; // Do the magic window.WebSocket = WebSocketProxy; // Debug commands from the console window.slackasa = { ticklenow() { window._websockets.forEach((ws) => { ws.details.clearTickleTimestamp(); }); }, reload() { document.location = document.location; }, listsockets() { window._websockets.forEach((ws) => { ws.console.log(JSON.stringify( Object.assign({_isOpen: ws.readyState === ws.OPEN}, ws.details.debug()), null, 2)); }); }, triggererror() { window.setTimeout(() => { throw new Error("Expected error!") }, 0); }, triggerfatal() { errorCount = PAGE_ERROR_THRESHOLD - 1; this.triggererror(); } }; })(unsafeWindow || window, (immutableEvent) => { const isStrict = (function () { return !this; })(); if (isStrict) { throw new Error("This won't work in strict mode"); } // Outside of the strict scope Object.defineProperty(immutableEvent, "data", { _data: {}, set: function (obj) { this._data = JSON.stringify(obj); }, get: function () { return this._data; } }) }); |
Notes:
- There are over 10 million users of Tampermonkey. ↩