I am trying to establish a websocket connection to my server running on the Pterodactyl Software. But I don't know how to authorize myself to pterodactyl.
The docs say:
How to connect
Connect to the websocket address (in this example "wss://pterodactyl.file.properties:8080/api/servers/1a7ce997-259b-452e-8b4e-cecc464142ca/ws")
Send the token to the websocket like this: {"event":"auth","args":["eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImp0aSI6Ij..."]}
Tokens last about 10-15 minutes, and the websocket will notify you once you need to send a new token with {"event":"token expiring"} and {"event":"token expired"}
And I tried that in my Code:
const { WebSocket } = require('ws');
const ws = new WebSocket(`wss://example.com:8080/api/servers/myServerUUID/ws`);
ws.on(`open`, () => {
ws.send({ event: "auth", args: [`mySuperSecretToken`] });
});
ws.on(`error`, (err) => {
console.log(err);
});
ws.on(`message`, data => {
console.log(data);
});
But it always gives me this error:
Error: Unexpected server response: 403
at ClientRequest.<anonymous> (C:\Users\RappyTV\Documents\Bot\node_modules\ws\lib\websocket.js:886:7)
at ClientRequest.emit (node:events:527:28)
at HTTPParser.parserOnIncomingClient (node:_http_client:631:27)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
at TLSSocket.socketOnData (node:_http_client:494:22)
at TLSSocket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:324:12)
at readableAddChunk (node:internal/streams/readable:297:9)
at TLSSocket.Readable.push (node:internal/streams/readable:234:10)
at TLSWrap.onStreamRead (node:internal/stream_base_commons:190:23)
Fix:
I should have put the pterodactyl origin in an object as a second argument in the WebSocket
constructor:
const ws = new WebSocket('wss://example.com:8080/api/servers/myServerUUID/ws', { origin: 'https://example.com' });
And I forgot to stringify the message to the WebSocket:
ws.on(`open`, () => {
ws.send(JSON.stringify({ event: "auth", args: [`mySuperSecretToken`] }));
});