add keepalive message to prevent proxies closing the connection

This commit is contained in:
Elijah R 2024-07-12 14:57:10 -04:00
parent 6a3aedaf6a
commit 97932c4a93
3 changed files with 27 additions and 0 deletions

View file

@ -2,6 +2,7 @@ export * from './admin.js';
export enum MSAgentProtocolMessageType { export enum MSAgentProtocolMessageType {
// Client-to-server // Client-to-server
KeepAlive = "nop",
Join = "join", Join = "join",
Talk = "talk", Talk = "talk",
Admin = "admin", Admin = "admin",

View file

@ -25,6 +25,9 @@ export class Client extends EventEmitter {
room: MSAgentChatRoom; room: MSAgentChatRoom;
socket: WebSocket; socket: WebSocket;
nopTimer: NodeJS.Timeout | undefined;
nopLevel: number;
chatRateLimit: RateLimiter chatRateLimit: RateLimiter
constructor(socket: WebSocket, room: MSAgentChatRoom, ip: string) { constructor(socket: WebSocket, room: MSAgentChatRoom, ip: string) {
@ -35,6 +38,8 @@ export class Client extends EventEmitter {
this.username = null; this.username = null;
this.agent = null; this.agent = null;
this.admin = false; this.admin = false;
this.resetNop();
this.nopLevel = 0;
this.chatRateLimit = new RateLimiter(this.room.config.ratelimits.chat); this.chatRateLimit = new RateLimiter(this.room.config.ratelimits.chat);
@ -67,6 +72,20 @@ export class Client extends EventEmitter {
}); });
} }
private resetNop() {
clearInterval(this.nopTimer);
this.nopLevel = 0;
this.nopTimer = setInterval(() => {
if (this.nopLevel++ >= 3) {
this.socket.close();
} else {
this.send({
op: MSAgentProtocolMessageType.KeepAlive
});
}
}, 10000)
}
private async parseMessage(data: string) { private async parseMessage(data: string) {
let msg: MSAgentProtocolMessage; let msg: MSAgentProtocolMessage;
try { try {
@ -75,6 +94,7 @@ export class Client extends EventEmitter {
this.socket.close(); this.socket.close();
return; return;
} }
this.resetNop();
switch (msg.op) { switch (msg.op) {
case MSAgentProtocolMessageType.Join: { case MSAgentProtocolMessageType.Join: {
let joinMsg = msg as MSAgentJoinMessage; let joinMsg = msg as MSAgentJoinMessage;

View file

@ -249,6 +249,12 @@ export class MSAgentClient {
return; return;
} }
switch (msg.op) { switch (msg.op) {
case MSAgentProtocolMessageType.KeepAlive: {
this.send({
op: MSAgentProtocolMessageType.KeepAlive
});
break;
}
case MSAgentProtocolMessageType.Init: { case MSAgentProtocolMessageType.Init: {
let initMsg = msg as MSAgentInitMessage; let initMsg = msg as MSAgentInitMessage;
this.username = initMsg.data.username; this.username = initMsg.data.username;