Websocket SSL connection - javascript

I am trying to test a secure websocket but I'm having trouble. Here is my test:
var WebSocket = require('ws');
describe('testing Web Socket', function() {
it('should do stuff', function(done) {
var ws = new WebSocket('wss://localhost:15449/', {
protocolVersion: 8,
origin: 'https://localhost:15449'
});
ws.on('open', function() {
console.log('open!!!');
done();
});
console.log(ws);
});
});
Here's the log of "ws" after it's created:
{ domain: null,
_events: { open: [Function] },
_maxListeners: undefined,
_socket: null,
_ultron: null,
_closeReceived: false,
bytesReceived: 0,
readyState: 0,
supports: { binary: true },
extensions: {},
_isServer: false,
url: 'wss://localhost:15449/',
protocolVersion: 8 }
I don't get a log back from open. I am running the project locally and when I use the Chrome Advanced Rest Client tool I am able to connect just fine.
Am I missing something? Please help.
Edit:
I added ws.on('error') and it logged out { [Error: self signed certificate] code: 'DEPTH_ZERO_SELF_SIGNED_CERT' }
I've also tried following this code but get the same error.

The https module is rejecting your self-signed cert (as one would hope). You can force it to stop checking by passing a rejectUnauthorized: false option (which WebSocket will pass down to https):
var ws = new WebSocket('wss://localhost:15449/', {
protocolVersion: 8,
origin: 'https://localhost:15449',
rejectUnauthorized: false
});

Related

Cannot read req.body in Next.js 13 middeware

In the code below I want to validate the request body with a schema from zod, currently, it will fail and catch. This is because req.body is returning a ReadableStream<Uint8Array> and not the object that it expects to parse.
export default async function middleware(req: NextRequest, res: NextResponse) {
const { pathname } = req.nextUrl;
if (pathname.startsWith('/api/user/create')) {
try {
createUserSchema.parse({
body: req.body,
params: req.nextUrl.searchParams,
});
return NextResponse.next();
} catch (error: any) {
console.log(req.body);
return NextResponse.json(
{ success: false, message: error },
{ status: 422, headers: { 'content-type': 'application/json' } }
);
}
}
return NextResponse.next();
}
this below is the output of the console.log(req.body);
<ref *1> ReadableStream {
_state: 'readable',
_reader: undefined,
_storedError: undefined,
_disturbed: false,
_readableStreamController: ReadableStreamDefaultController {
_controlledReadableStream: [Circular *1],
_queue: S {
_cursor: 0,
_size: 0,
_front: { _elements: [], _next: undefined },
_back: { _elements: [], _next: undefined }
},
_queueTotalSize: 0,
_started: false,
_closeRequested: false,
_pullAgain: false,
_pulling: false,
_strategySizeAlgorithm: [Function],
_strategyHWM: 1,
_pullAlgorithm: [Function],
_cancelAlgorithm: [Function]
}
}
I did some research and found that I need to run some kind of conversion method on this ReadableStream. The problem is that most of these include the Buffer module which cannot be run on the Edge and therefore cannot work in the middleware.ts. Is there perhaps a polyfill that I can use?
"next": "^13.0.7"
Node v16.17.0
Next.js middleware does not work the same as an Express middleware because it only runs on navigation and does not act as a catch-all for your API endpoints.
As per the documentation, you can only access cookies, access/modify request headers and perform redirects and rewrites using this feature.
You can use
const body = await req.json()

API communication in js web worker

I have a problem with my code:
I'm using RecorderJS, and I'm trying to permise this to send sound to my back-end, but as streaming, not as complete recording.
I'm using HTML 5 and the last versions of python and flask.
I found where I had to put my code for doing that, but my problem is the communication beetween my back and my worker.
I tried to use XMLHttpRequest :
function send_buffer_to_transcription(sound_buffer) {
// no jquery in workers
var request = new XMLHttpRequest();
var url = "'/updateSound2'";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
console.log("son transmis");
}
};
var data = {
audioBuffer:JSON.stringify(Array(new Int16Array(sound_buffer)))
}
request.send(data);
}
But I had an issue with that :
Uncaught DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL
at send_buffer_to_transcription (blob:http://127.0.0.1:5000/feb04c56-4e80-4418-885f-5f24bc7b9409:79:23)
at streaming_record (blob:http://127.0.0.1:5000/feb04c56-4e80-4418-885f-5f24bc7b9409:62:19)
at record (blob:http://127.0.0.1:5000/feb04c56-4e80-4418-885f-5f24bc7b9409:101:17)
at self.onmessage (blob:http://127.0.0.1:5000/feb04c56-4e80-4418-885f-5f24bc7b9409:27:25)
I tried with webSocket too :
let socket = new WebSocket("wss://127.0.0.1:5000/soudtesting");
socket.onerror = function (error) {
console.error(error);
}
function send_as_socket() {
socket.send('my message');
}
But here is the issue I've had :
7fdd8dd0-6354-467b-8b58-253c98412fdd:10 WebSocket connection to 'wss://127.0.0.1:5000/soudtesting' failed:
(nothing next)
the error looks :
isTrusted: true
bubbles: false
cancelBubble: false
cancelable: false
composed: false
currentTarget: WebSocket {url: 'wss://127.0.0.1:5000/soudtesting', readyState: 3, bufferedAmount: 0, onopen: null, onerror: ƒ, …}
defaultPrevented: false
eventPhase: 0
path: []
returnValue: true
srcElement: WebSocket {url: 'wss://127.0.0.1:5000/soudtesting', readyState: 3, bufferedAmount: 0, onopen: null, onerror: ƒ, …}
target: WebSocket {url: 'wss://127.0.0.1:5000/soudtesting', readyState: 3, bufferedAmount: 0, onopen: null, onerror: ƒ, …}
timeStamp: 0
type: "error"
[[Prototype]]: Event
Does someone has an explaination, and, if possible a solution please? Really needed.
=====
Oops, I forget this :
Here's the error which has occured in my back-end (I don't think this will be helpfull, but why not)
127.0.0.1 - - [06/Apr/2022 13:51:55] code 400, message Bad request version ('úú\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x01\x00\x01\x93êê\x00\x00\x00\x17\x00\x00ÿ\x01\x00\x01\x00\x00')
ax°×¥¡²DüöàO»Ëgïò&åf# úúÀ+À/À,À0̨̩ÀÀ / 5 êê ÿ " HTTPStatus.BAD_REQUEST -
127.0.0.1 - - [06/Apr/2022 13:51:55] code 400, message Bad request version ('êê\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x01\x00\x01\x93úú\x00\x00\x00\x17\x00\x00ÿ\x01\x00\x01\x00\x00')
èbÄÍdµÜQýH³¾²§¶E|}½eO ËX|Da¼j»-ÃñUxù©í弪v[` êêÀ+À/À,À0̨̩ÀÀ / 5 úú ÿ " HTTPStatus.BAD_REQUEST -

How to reconnect Pubnub after internet reconnect in javascript?

I have a Pubnub instance,
I want to know how to handle reconnection when internet does down and comes back up with like a given number of retries? The documentation definitely gives the appropriate docs but I am unable to put it into code.
Help would be greatly appreciated.
my code:
this.pubnub = new PubNub({
subscribeKey: this.serverDetails.authInfo.subscribeKey,
authKey: this.serverDetails.authInfo.authKey,
uuid,
restore: true,
ssl: true
});
this.listeners = {
message: msgEvent => {
console.log(msgEvent);
},
status: statusEvent => {
}
};
this.pubnub.addListener(this.listeners);
Set restore:true in your init code.
this.pubnub = new PubNub({
subscribeKey: this.serverDetails.authInfo.subscribeKey,
authKey: this.serverDetails.authInfo.authKey,
uuid,
ssl: true,
restore: true // this allows reconnect to restore your channel subscription
});

Unable to run the multichain-node (npm module) in client side(browser)

let multichain = require("multichain-node")({
port: 6001,
host:'localhost',
user:'myuser',
pass:'mypassword'
});
multichain.getInfo((error,info) => {
if(error){
throw error;
}
console.log(info);
})
output:version: '1.0',
nodeversion: 10000901,
protocolversion: 10008,
chainname: 'chain1',
description: 'chain1',
protocol: 'multichain',
port: 6001,
setupblocks: 60,
nodeaddress: 'mulmul#localhost:6001',
burnaddress: '1XXXXXXWh4XXXXXXXyXXXXXXZdXXXXXXYjGhfn',
incomingpaused: false,
miningpaused: false,
walletversion: 60000,
balance: 0,
walletdbversion: 2,
reindex: false,
blocks: 127,
timeoffset: 0,
connections: 0,
proxy: '',
difficulty: 6e-8,
testnet: false,
keypoololdest: 1506490805,
keypoolsize: 2,
paytxfee: 0,
relayfee: 0,
errors: '' }
this output displayed in command prompt, How can i execute this code in browser
multichain-node is a node module; it doesn't make sense to run it in the browser.
In particular it uses node's http module to make http requests; if you wanted to do that in the browser you'd need to use fetch or XMLHttpRequest to do that, and you would need CORS to be set up correctly.

socket.io-client on server to connect to another server

So I have been working on setting up redundant servers without a single point of failure. I have been looking through a lot of methods and I have settled on using socket.io-client on each server to handle passing messages back and forth between the 2 servers for redundant data. However, no matter what I do, I cannot get the server to connect to the other server. I even scrapped my entire project, started a new one, using extremely simplistic code, and still cannot get the 2 to talk to each other. I have seen multiple questions like this on SO, but none of them have resolved my issue, so I decided to ask and give code samples of my ridiculously simple setup and see if anyone can see why it doesn't connect. I'm telling you, if I didn't already shave my head, I would be ripping my hair out by now. So, here is my simplistic code that doesn't work....
SERVER 1
"use strict";
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const ioClient = require('socket.io-client');
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
var client = ioClient('10.0.0.234:3000');
client.on('connect', () => {
console.log('connected to server');
});
io.on('connection', (socket) => {
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
SERVER 2 -- exactly the same except for the line...
var client = ioClient('10.211.55.7:3000');
To point it at the other server. These are both on my local network, and both of them are running at the same time. I even put a client page on each server with a simple connection string, one to the server on that same machine, and one to the server on the other machine, like so...
CLIENT 1 (the 10.0.0.234 machine):
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io("10.0.0.234:3000");
socket.on('connect', function() {
console.log('connected to main server');
})
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
CLIENT 2 (the 10.211.55.7 machine) - exactly the same except for the connection line which is...
var socket = io('10.211.55.7:3000');
Both of the clients work, and can connect to their servers. I even switched the IP addresses on the clients so that machine 10.0.0.234's client was using...
var socket = io('10.211.55.7:3000');
and it connected perfectly. So each client can connect to either server, and it works perfectly, but no matter what I do, I cannot get the server to ever log the 'connected to server' part.
Seriously, am I losing my mind here? IS there some random bug in socket.io-client that won't allow a server to connect to another server, even if it is running the socket.io as a client? I am so very...very... confused, annoyed, fed up, beat up... and all the other adjectives you can think of.
Just in case anyone needs it, here is my package.json file that I am running on both servers...
PACKAGE.JSON...
{
"name": "simple-socket",
"version": "0.0.1",
"description": "socket server to socket server test",
"dependencies": {
"express": "4.10.2",
"socket.io": "1.2.0",
"socket.io-client": "^1.4.5"
}
}
I know there are other ways of handling redundant backups within node.js,the actual server is much more complex running sticky-session, cluster, redis, socket.io-redis, and others. I just created a simplistic example (actually just kind of used the socket.io chat example as a base) to try to get both servers to talk to each other. No matter what though, it never actually connects to the other server. Yet, somehow both clients can connect to either server, it is just the server will not connect to the other server. Thank you for all the help, and I apologize for the novel here, I am just trying to give all the information I possibly can. Nothing more annoying than trying to help someone who won't give you anything in terms of information, and won't even do some basic research.
Here is a console.log(client); right after the "var client = ioClient('10.0.0.234:3000');
Socket {
io:
Manager {
nsps: { '/': [Circular] },
subs: [ [Object], [Object], [Object] ],
opts:
{ path: '/socket.io',
hostname: '10.0.0.234',
secure: false,
port: '3333' },
_reconnection: true,
_reconnectionAttempts: Infinity,
_reconnectionDelay: 1000,
_reconnectionDelayMax: 5000,
_randomizationFactor: 0.5,
backoff: Backoff { ms: 1000, max: 5000, factor: 2, jitter: 0.5, attempts: 0 },
_timeout: 20000,
readyState: 'opening',
uri: 'http://10.0.0.234:3333',
connecting: [ [Circular] ],
lastPing: null,
encoding: false,
packetBuffer: [],
encoder: Encoder {},
decoder: Decoder { reconstructor: null },
autoConnect: true,
engine:
Socket {
secure: false,
agent: false,
hostname: '10.0.0.234',
port: '3333',
query: {},
upgrade: true,
path: '/socket.io/',
forceJSONP: false,
jsonp: true,
forceBase64: false,
enablesXDR: false,
timestampParam: 't',
timestampRequests: undefined,
transports: [Object],
readyState: 'opening',
writeBuffer: [],
policyPort: 843,
rememberUpgrade: false,
binaryType: null,
onlyBinaryUpgrades: undefined,
perMessageDeflate: [Object],
pfx: null,
key: null,
passphrase: null,
cert: null,
ca: null,
ciphers: null,
rejectUnauthorized: null,
transport: [Object],
_callbacks: [Object] },
skipReconnect: false,
_callbacks: { '$open': [Object], '$packet': [Object], '$close': [Object] } },
nsp: '/',
json: [Circular],
ids: 0,
acks: {},
receiveBuffer: [],
sendBuffer: [],
connected: false,
disconnected: true,
subs:
[ { destroy: [Function] },
{ destroy: [Function] },
{ destroy: [Function] } ],
_callbacks:
{ '$connecting': [ [Function: onConnecting] ],
'$connect': [ [Function] ] } }

Categories