fix typo, correctly perform auth, and close remote when local disconnects

This commit is contained in:
Danny Morabito 2025-08-06 02:11:48 +02:00
parent a8fd9eb96b
commit 3367cb929b
Signed by: dannym
GPG key ID: 7CC8056A5A04557E

View file

@ -20,7 +20,7 @@ async function validateAuthEvent(event: Event, challenge: string): boolean {
if (event.kind !== 22242) return false;
const last30Seconds = Math.floor(Date.now() / 1000) - 30;
if (event.created_at < last30Seconds) return false;
const challengeTag = event.tags.find(tag => tag[0] === 'challange')?.[1];
const challengeTag = event.tags.find(tag => tag[0] === 'challenge')?.[1];
if (challengeTag !== challenge) return false;
const file = Bun.file("./allowed-pubkeys.json");
if (!await file.exists()) return true;
@ -60,20 +60,31 @@ export function main(mainRelayUrl: string) {
const [event] = data;
const valid = await validateAuthEvent(event, ws.data.authToken);
if (!valid) return sendMessage(ws, ['NOTICE', "Invalid auth event"]);
sendMessage(ws, ['OK', event.id, true, "successully authenticated. welcome"]);
ws.data.authenticated = true;
return;
}
return sendAuth(ws);
} else if (ws.data.authenticated && command === "AUTH") {
const [event] = data;
return sendMessage(ws, ['OK', event.id, true, 'you were already authenticated'])
}
ws.data.remoteWs.send(msg);
},
open(ws) {
sendAuth(ws);
ws.data.remoteWs = new WebSocket(mainRelayUrl);
ws.data.remoteWs.onmessage = (data) => ws.send(data.data, true);
const remoteWs = new WebSocket(mainRelayUrl);
remoteWs.addEventListener("message", data => ws.send(data.data, true));
remoteWs.addEventListener("open", () => {
ws.data.remoteWs = remoteWs;
sendAuth(ws);
})
remoteWs.addEventListener("error", console.error)
},
perMessageDeflate: true,
perMessageDeflateCompressionLevel: 9
close(ws) {
ws.data.remoteWs?.close();
}
}
})
console.log('Server listening @', server.url.host)