Skip to content

Commit

Permalink
fix: url validation in events websocket connection
Browse files Browse the repository at this point in the history
  • Loading branch information
rmrt1n committed Oct 22, 2024
1 parent 17afff6 commit fdf81f7
Showing 1 changed file with 31 additions and 22 deletions.
53 changes: 31 additions & 22 deletions src/routes/_cardinal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,30 +98,39 @@ function CardinalLayout() {
// setup websocket connection to receive events
useEffect(() => {
const wsCardinalUrl = cardinalUrl.replace(/https|http/, 'ws')
const ws = new WebSocket(`${wsCardinalUrl}${routeEvents}`)
ws.onopen = () => console.log('Connected to events ws')
ws.onmessage = (event) => {
const data = JSON.parse(event.data as string) as CardinalEvent
if (data.Events && data.Events.length > 0) {
// data.Events is an array of base64-ed JSON representation of an event
data.Events.forEach((evt) => {
let eventData = atob(evt)
try {
const json = JSON.parse(eventData) as { [k: string]: string }
eventData = json.event
} catch (_error) {
// this just means the backend used EmitStringEvent instead of EmitEvent,
// we can safely ignore this error
}
if (notifications) {
toast({ title: eventData })
} else {
console.log('Received event: ', eventData)
}
})
let ws: WebSocket;
try {
// this throws error if url scheme is not valid
ws = new WebSocket(`${wsCardinalUrl}${routeEvents}`)
ws.onopen = () => console.log('Connected to events ws')
ws.onmessage = (event) => {
const data = JSON.parse(event.data as string) as CardinalEvent
if (data.Events && data.Events.length > 0) {
// data.Events is an array of base64-ed JSON representation of an event
data.Events.forEach((evt) => {
let eventData = atob(evt)
try {
const json = JSON.parse(eventData) as { [k: string]: string }
eventData = json.event
} catch (_error) {
// this just means the backend used EmitStringEvent instead of EmitEvent,
// we can safely ignore this error
}
if (notifications) {
toast({ title: eventData })
} else {
console.log('Received event: ', eventData)
}
})
}
}
} catch (error) {
// no need to toast this error as it might be spammy
console.log(error)
}
return () => {
if (ws) ws.close()
}
return () => ws.close()
}, [cardinalUrl, toast, notifications])

return (
Expand Down

0 comments on commit fdf81f7

Please sign in to comment.