1

Есть проэкт в котором разрабатываю видео чат. Он стандартно работает на socket.io и peerjs. Свервер создал на ՝nodejs՝ с реальными сертификатами SSL.

Все корректно работает . Но только в консоле peerjs выкидивает ошибку 401 (Unauthorized). В просторах интернета не могу найти в чем может быть проблема, и как его решить.

Вот кода сервера на nodejs

const dotenv = require('dotenv');
dotenv.config();
const HTTPS_KEY = process.env.HTTPS_KEY;
const HTTPS_CRT = process.env.HTTPS_CRT;
const fs = require('fs');
const https = require('https');
const cors = require("cors");
const bodyParser = require("body-parser");
const privateKey  = fs.readFileSync(HTTPS_KEY, 'utf8');
const certificate = fs.readFileSync(HTTPS_CRT, 'utf8');
const port = process.env.SOCKET_HTTPS_PORT || 2055;
const credentials = {
    key: privateKey,
    cert: certificate,
    ca: certificate,
    requestCert: true,
    rejectUnauthorized: false, /* This is necessary to accept self-signed certificates, we will perform the authentication ourselves */
    secure: true
};
const express = require('express');
const app = express();

// your express configuration here

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', process.env.SITE_URL);

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

const server = https.createServer(credentials, app);

server.listen(port, function() {
    console.log("HTTPS listening port CHECK: " + port);
});
module.exports.app = app;
module.exports.server = server;

Лог peer сервера

connection id Client {
  socket: <ref *1> WebSocket {
    _events: [Object: null prototype] {
      close: [Array],
      message: [Function (anonymous)]
    },
    _eventsCount: 2,
    _maxListeners: undefined,
    _binaryType: 'nodebuffer',
    _closeCode: 1006,
    _closeFrameReceived: false,
    _closeFrameSent: false,
    _closeMessage: '',
    _closeTimer: null,
    _extensions: {},
    _protocol: '',
    _readyState: 1,
    _receiver: Receiver {
      _writableState: [WritableState],
      _events: [Object: null prototype],
      _eventsCount: 6,
      _maxListeners: undefined,
      _binaryType: 'nodebuffer',
      _extensions: {},
      _isServer: true,
      _maxPayload: 104857600,
      _bufferedBytes: 0,
      _buffers: [],
      _compressed: false,
      _payloadLength: 0,
      _mask: undefined,
      _fragmented: 0,
      _masked: false,
      _fin: false,
      _opcode: 0,
      _totalPayloadLength: 0,
      _messageLength: 0,
      _fragments: [],
      _state: 0,
      _loop: false,
      [Symbol(kCapture)]: false,
      [Symbol(websocket)]: [Circular *1]
    },
    _sender: Sender {
      _extensions: {},
      _socket: [TLSSocket],
      _firstFragment: true,
      _compress: false,
      _bufferedBytes: 0,
      _deflating: false,
      _queue: []
    },
    _socket: TLSSocket {
      _tlsOptions: [Object],
      _secureEstablished: true,
      _securePending: false,
      _newSessionPending: false,
      _controlReleased: true,
      secureConnecting: false,
      _SNICallback: null,
      servername: 'somesite.com',
      alpnProtocol: false,
      authorized: false,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 7,
      connecting: false,
      _hadError: false,
      _parent: [Socket],
      _host: null,
      _readableState: [ReadableState],
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: [Server],
      _server: null,
      ssl: [TLSWrap],
      _requestCert: false,
      _rejectUnauthorized: true,
      timeout: 0,
      parser: null,
      on: [Function (anonymous)],
      addListener: [Function (anonymous)],
      prependListener: [Function: prependListener],
      _paused: false,
      [Symbol(res)]: [TLSWrap],
      [Symbol(verified)]: false,
      [Symbol(pendingSession)]: null,
      [Symbol(async_id_symbol)]: 20412,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(kSetNoDelay)]: true,
      [Symbol(lastWriteQueueSize)]: 129,
      [Symbol(timeout)]: Timeout {
        _idleTimeout: -1,
        _idlePrev: null,
        _idleNext: null,
        _idleStart: 3357675,
        _onTimeout: null,
        _timerArgs: undefined,
        _repeat: null,
        _destroyed: true,
        [Symbol(refed)]: false,
        [Symbol(kHasPrimitive)]: false,
        [Symbol(asyncId)]: 20413,
        [Symbol(triggerId)]: 6
      },
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(error-emitted)]: false,
      [Symbol(RequestTimeout)]: undefined,
      [Symbol(websocket)]: [Circular *1]
    },
    _isServer: true,
    [Symbol(kCapture)]: false
  },
  lastPing: 1648474552615,
  id: '2cef01b2-bcd2-4568-8fda-1624671d7456',
  token: 'gbarvwl72lh'
}

А это ошибки которые периодически вылезают в консоли.

введите сюда описание изображения

11
  • Не уверена, что у вас эта проблема, но я где-то месяц назад боролась с 401 ошибкой c peerjs. Помогло alive_timeout: 86400000. Попробуйте в credentials добавить
    – Hat
    28 мар 2022 в 13:52
  • @Hat а это где прописать в конфигах? 28 мар 2022 в 13:58
  • const http = require("http").createServer(app); const io = require('socket.io')(http); const { ExpressPeerServer } = require("peer"); const peerServer = ExpressPeerServer(http, { debug: true, alive_timeout: 86400000 }); app.use("/peer", peerServer);
    – Hat
    28 мар 2022 в 14:01
  • У меня так конфиг выглядел
    – Hat
    28 мар 2022 в 14:01
  • Я ещё раз посмотрела ваш код, вообще не вижу, где вы peerjs используете
    – Hat
    28 мар 2022 в 14:07

0

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Посмотрите другие вопросы с метками или задайте свой вопрос.