taoensso / sente

Realtime web comms library for Clojure/Script
https://www.taoensso.com/sente
Eclipse Public License 1.0
1.74k stars 193 forks source link

The very first time #438

Closed danielsz closed 1 year ago

danielsz commented 1 year ago

Apologies in advance if I am missing something, but I was wondering if the observation I am going to describe is something others have experienced.

I have observed a problem with establishing a Websocket connection the very first time a Sente app is loaded in the browser. It does load after the refresh of the page, and it does load if I close the tab and reopen it subsequently. Only the very first load fails with a message:

sente.cljc:1315 WebSocket connection to 'ws://localhost:3125/chsk?client-id=a27c1f1e-f278-4aab-98c2-9fa8fa9dff28&csrf-token=Q%2FA4Qeve3lkGNloIpVTzdGVq691bzeZNxcrYCmWS8ZYIq1liI2hSBcxbPJGJR3qjBvWAJz6iOkH4I4Z%2B' failed

It is easy to brush off the problem because it only occurs once in a browser session. I have noticed that the problem manifests itself both in a local development setting with Figwheel, and in a production app with SSL and behind a reverse proxy.

The source code line that is being highlighted in the browser console is the following: https://github.com/taoensso/sente/blob/a51a54a6d0372e7284e0c322b2c75e3804dbe1f8/src/taoensso/sente.cljc#L1315

It looks like the server replies with a 403 the very first time a browser sends the request:

http://localhost:3125/chsk?udt=1695936337145&client-id=db434408-b56f-4842-b189-cccafb94d1e3&handshake%3F=true 

But why?

I am using the Undertow web server with the taoensso.sente.server-adapters.community.undertow adapter.

Any ideas? Thank you!

ptaoussanis commented 1 year ago

Hi Daniel!

A few questions:

Thanks

danielsz commented 1 year ago

Thank you for the leading questions. They helped me find the problem. And sorry about the drama.

So it turns out that I was requiring the Sente app (include-js "main.js") in the header of my HTML5 page, while the CSRF token was injected in the body of the HTML5 page. The bug was very much of my own doing, and is related to the mine-ridden execution order of scripts in Javascript. The very first load was failing, and then everything gets sorted out (in my client the CSRF token is a global Javascript var), which is why I didn't pay too much attention to the problem (until yesterday).

Again, sorry about the drama, but above all thank you for your kindness and patience.

ptaoussanis commented 1 year ago

No drama, and no problem at all - happy you found a solution! Thanks for following up, hope you're well Daniel!

Cheers :-)

danielsz commented 1 year ago

For posterity's sake, the trouble was not as indicated above, but rather the fact that I had multiple instances of the CSRF token middleware in my handler.