NodeJS 如何创建安全节点WebSocket客户端(无法验证第一个证书问题)

nfg76nw0  于 2023-01-16  发布在  Node.js
关注(0)|答案(1)|浏览(179)

什么在起作用

我使用WebSocket-Node创建了一个节点https/WebSocket服务器,下面是我如何添加key/cert的代码片段:

import WebSockerServer from "websocket";
import fs from "fs";

const httpsSignalServer = https.createServer(
  {
    key: fs.readFileSync("./server.private.key"),
    cert: fs.readFileSync("./server.crt"),
  },
  (req, res) => {
    console.log("signal server : we have received a request");
  }
);
const signalWebsocket = new WebSockerServer.server({
  httpServer: httpsSignalServer,
});

signalWebsocket.on("request", (request) => onRequest(request));

httpsSignalServer.listen(8080, () => console.log("My signal server is listening"));

我有一个React html网页,通过wss发送数据到上面的WebSocket Web API服务器:

new WebSocket("wss://192.168.230.138:8081");

我的react应用程序在https服务器上运行,目前一切正常。
∮ ∮什么不起作用∮
问题出在我的小节点WebSocket客户端上,我还在使用WebSocket-Nodeclient documentation显示了一个tlsOptions给构造函数。
客户端代码片段:

var WebSocketClient = require("websocket").client;
var fs = require("fs");

const tlsOptions = {
  key: "./server.private.key",
  cert: "./server.crt",
};

var client = new WebSocketClient({
  key: fs.readFileSync(tlsOptions.key),
  cert: fs.readFileSync(tlsOptions.cert),
});
.
. 
.
client.connect("wss://localhost:8080/", "");

客户端返回消息:
错误:无法验证第一个证书
有没有人知道如何使用tlsOptions进行客户端设置?
谢谢

bis0qfac

bis0qfac1#

我写了一个完美的功能简单的聊天脚本,它使用安全连接。我添加了一些简单的聊天命令,以启用或禁用聊天输入命令在聊天。你可以使用这个,如果你喜欢或它的一部分,甚至只是看看我是怎么做的。希望你找到一些使用它。

var maxLength = 100; // chars per chat
const port = 1441;
var JoinLeaveMsg = 1
var fs = require('fs');
const HTTPS = require('https');
const WebSocket = require('ws');

const server = new HTTPS.createServer({
  cert: fs.readFileSync('C:/Certbot/live/MyDomain.com/cert.pem'),
  key: fs.readFileSync('C:/Certbot/live/MyDomain.com/privkey.pem')
});
const wss = new WebSocket.Server({ server })

wss.on('connection', function connection(ws) {
const now = new Date();
const tDate = now.toDateString();
const date = new Date(now);
const currentDate = date.toLocaleTimeString();
console.log(tDate + ' - ' + currentDate + " - New User Connected");

        ws.send(JSON.stringify(
            {
                name: "welcome",
                message: "wanna chat?"
            }
        ));

ws.on('message', function(message){
    message = JSON.parse(message);
    const createDOMPurify = require('dompurify');
    const { JSDOM } = require('jsdom');
    const window = new JSDOM('').window;
    const DOMPurify = createDOMPurify(window);
// START CONNECT
    if(message.type == "name"){
// START CHECKS FOR DOUBLE LOGIN

        var dirty = message.data;
        const ConnectingUser = DOMPurify.sanitize(dirty);
        if (ConnectingUser != ''){
            wss.clients.forEach(function e(client) {
                var ConnectedUser = client.personName;
                if(ConnectedUser == ConnectingUser) {
                    client.send(JSON.stringify(
                        {
                            name: "***Server***",
                            message: "***We do not allow double logins!"
                        }
                    ));
                    client.send(JSON.stringify(
                        {
                            name: "***Server***",
                            message: "🔴 Disconnected..."
                        }
                    ));
                    client.close();
                }
            });
        }
// END CHECKS FOR DOUBLE LOGIN
        ws.personName = ConnectingUser;
        memberJoinedChatMsg(ws, ConnectingUser);
        return;
    }

// START INPUT DATA
    if(message.type == "message"){
        var ConnectedUser = ws.personName;
        if (ConnectedUser != ''){
            var dirty = message.message;
            const Message = DOMPurify.sanitize(dirty);
            var string = Message;
            var temp = string.split(" ");
            var CommandOne = temp[0];
            var CommandTwo = temp[1];
            var CommandThree = temp.slice(2).join(" ");
            // lets process the messages and send to users
            if((Message) != "") {
// START COMMANDS
                // Do join/leave msg disable--------------------------------------------------------------------            
                if((CommandOne) == "/jpenable" || (CommandOne) == "!jpenable"){
                    JoinLeaveMsg = "1";
                    Msg ='***Join/Part message has been Enabled!';
                    sendMsgToAll(Msg)
                    MessageString ="";
                }
                // Do join/leave msg enable--------------------------------------------------------------------
                if((CommandOne) == "/jpdisable" || (CommandOne) == "!jpdisable"){
                    JoinLeaveMsg = "0";
                    Msg ='***Join/Part message has been Disabled!';
                    sendMsgToAll(Msg)
                    MessageString ="";
                }

// END COMMANDS
                if ((Message).length < maxLength) {
                    wss.clients.forEach(function e(client) {
                        
                        client.send(JSON.stringify(
                            {
                                name: ConnectedUser,
                                message: Message
                            }
                        ));
                        console.log("Sent: "+ConnectedUser+" "+Message);
                    });
                }else{
                    wss.clients.forEach(function e(client) {
                        if(client === ws)
                        client.send(JSON.stringify(
                            {
                                name: '***Server***',
                                message: "*** Your message exceeds "+maxLength+" characters!"
                            }
                        ));
                    });         
                };
                
            }else{
                // dont process if empty line entered
            };
        }
    }

// END INPUT DATA
})
    ws.on('close', function(message) {
            if(ws.personName){
            memberLeftChatMsg(ws);
            }
            ws.close();
        //console.log("Client Disconnected");
    });
    // END CONNECT
})

server.listen(port, function() {
  console.log(`Server is listening on ${port}!`)
})

// FUNCTIONS
// complete Send Message To All
function sendMsgToAll(Msg){
    wss.clients.forEach(function e(client) {
        client.send(JSON.stringify(
            {
                name: "Server",
                message: Msg
            }
        ));
    }); 
};
// complete
function memberJoinedChatMsg(ws, ConnectingUser) {
    if(JoinLeaveMsg != "0"){
        wss.clients.forEach(function e(client) {
            client.send(JSON.stringify(
                {
                    name: "***Server***",
                    message: "🟢 &lt;<b>"+ConnectingUser+"</b>&gt; has entered chat!"
                }
            ));
        });
    }
};
// complete
function memberLeftChatMsg(ws) {
    if(JoinLeaveMsg != "0"){
        wss.clients.forEach(function e(client) {
            client.send(JSON.stringify(
                {
                    name: "***Server***",
                    message: "🔴 &lt;<b>"+ws.personName+"</b>&gt; has left chat!"
                }
            ));
        }); 
    }
};

我也安装了使用npm的Dompurify来帮助防止实体被张贴。记得打开防火墙中的端口或更改脚本中的端口号。如果您需要客户端脚本包括html,.css让我知道,我也可以上传那些:)

相关问题