Unable to get information using https second time(Error: write EPROTO ... final_renegotiate:unsafe legacy renegotiation disabled) - node.js

I developed a server which works fine on my system. Then I got a VPS(Virtual Private Server) from my university to deploy the server there too!
To deploy my server on VPS I used docker but I got a strange result when I ran it! I debug the program and find where problem is but I don't know why it occurs and how to fix it.
I use a remote database to get safe primes. First time I get the information without any problem but when server tries to connect to the database for second time, it gets below error:
node:events:498
throw er; // Unhandled 'error' event
^
Error: write EPROTO 80B9B7E0587F0000:error:0A000152:SSL routines:final_renegotiate:unsafe legacy renegotiation disabled:../deps/openssl/openssl/ssl/statem/extensions.c:907:
at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:94:16)
Emitted 'error' event on ClientRequest instance at:
at TLSSocket.socketErrorListener (node:_http_client:442:9)
at TLSSocket.emit (node:events:520:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -71,
code: 'EPROTO',
syscall: 'write'
}
Node.js v17.4.0
npm notice
npm notice New minor version of npm available! 8.3.1 -> 8.5.2
npm notice Changelog: <https://github.com/npm/cli/releases/tag/v8.5.2>
npm notice Run `npm install -g npm#8.5.2` to update!
npm notice
The simplified server I used to test:
const express = require('express');
const debug = require('debug');
const https = require('https')
const log = debug('app::main-Interface');
const args = process.argv.slice(2);
const app = express();
const port = args[0] || process.env.port || 3000;
function sleep(toSleep){
return new Promise((resolve, reject)=>{
setTimeout(() => {
resolve(true)
}, toSleep);
})
}
async function initializeRemotely(lengthOfOrder = 4096){
return new Promise((resolve, reject)=>{
https.get(`https://2ton.com.au/getprimes/random/${lengthOfOrder}`,
(res)=>{
res.on('data', async (data)=>{
log('Data received!')
resolve(true);
})
}
)
})
}
async function DEBUG(){
let breakTime = 5000;
while(true){
await initializeRemotely()
log('First operation succeed')
await sleep(breakTime);
breakTime *= 2;
}
}
app.listen(port, async () => {
log(`Server started listening on port : ${port}`);
//schedulerPool.MSRulesWatcher(config.get('Times.schedulers'));
DEBUG()
});
I run this code on my system using below command line:
$ DEBUG=app::* node server.js
app::main-Interface Server started listening on port : 3000 +0ms
app::main-Interface Data received! +2s
app::main-Interface First operation succeed +4ms
app::main-Interface Data received! +6s
app::main-Interface First operation succeed +1ms
app::main-Interface Data received! +11s
app::main-Interface First operation succeed +2ms
^C
As you can see it works fine!
The docker file I use to deploy the server is as below(./deploy/Dockerfile):
FROM node:alpine
EXPOSE 3000
WORKDIR /interface
COPY package.json .
RUN npm install
COPY . .
And the content of ./docker-compose.yml:
version: "3"
services:
interface:
image: interface
container_name: interface
build:
context: .
dockerfile: ./deploy/Dockerfile
entrypoint: ["npm", "run", "development"]
Then I run the docker image in VPS using below commands:
$ sudo docker-compose build
$ sudo docker-compose up -d
And the log of server is shown below:
$ sudo docker logs [container-name]
> export NODE_ENV=development; export DEBUG=app:*; node server.js
2022-02-25T17:06:37.963Z app::main-Interface Server started listening on port : 3000
2022-02-25T17:06:40.992Z app::main-Interface Data received!
2022-02-25T17:06:40.998Z app::main-Interface First operation succeed
node:events:498
throw er; // Unhandled 'error' event
^
Error: write EPROTO 80B991E6EB7F0000:error:0A000152:SSL routines:final_renegotiate:unsafe legacy renegotiation disabled:../deps/openssl/openssl/ssl/statem/extensions.c:907:
at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:94:16)
Emitted 'error' event on ClientRequest instance at:
at TLSSocket.socketErrorListener (node:_http_client:442:9)
at TLSSocket.emit (node:events:520:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -71,
code: 'EPROTO',
syscall: 'write'
}
Node.js v17.4.0
npm notice
npm notice New minor version of npm available! 8.3.1 -> 8.5.2
npm notice Changelog: <https://github.com/npm/cli/releases/tag/v8.5.2>
npm notice Run `npm install -g npm#8.5.2` to update!
npm notice
Which indicates server can connect to the database first time but second time it gets this error.
MY QUESTIONS:
First of all, I'm really curious to find out why this problem occurs?
How can I fix it?
INFORMATION
VPS information:
$ uname -a
Linux vote 5.4.0-26-generic #30-Ubuntu SMP Mon Apr 20 16:58:30 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
My system information:
$ uname -a
Linux milad-pc 5.4.178-1-MANJARO #1 SMP PREEMPT Tue Feb 8 20:03:41 UTC 2022 x86_64 GNU/Linux

Related

Can't get a ws WebSocket server to run on Vite dev server. WS_ERR_INVALID_CLOSE_CODE

I'm trying to get a WebSocket server to run on top of Vite's built-in dev server. I'm grabbing the httpServer instance directly from Vite and asking ws to listen on it, and it gives a fatal error which I can't find mentioned anywhere on the web.
I tried manually listening for "upgrade" events on Vite's httpServer and calling ws.Server.handleUpgrade() myself, but that gives me the same exact error. If I run all the code and simply leave off the call to handleUpgrade() then it will stop giving any errors. The error definitely seems to come from handleUpgrade(), I just have no clue what the error means or how to fix it.
It should be noted that I'm using SvelteKit and TypeScript in this project. This is my vite.config.ts file:
import type { UserConfig } from 'vite';
import { sveltekit } from '#sveltejs/kit/vite';
import { WebSocketServer } from "ws";
const config: UserConfig = {
plugins: [
sveltekit(),
{
name: "webSocketServer",
configureServer: (viteDevServer: any) => {
const webSocketServer = new WebSocketServer({
server: viteDevServer.httpServer
});
}
}
]
};
export default config;
This is the error I get when running the npm run dev command:
node:events:491
throw er; // Unhandled 'error' event
^
RangeError: Invalid WebSocket frame: invalid status code 16001
at Receiver.controlMessage (C:\Users\MSJim\Documents\programming-data\visual-studio-code\frontends\sveltekit-websockets-chat\node_modules\ws\lib\receiver.js:566:18)
at Receiver.getData (C:\Users\MSJim\Documents\programming-data\visual-studio-code\frontends\sveltekit-websockets-chat\node_modules\ws\lib\receiver.js:442:42)
at Receiver.startLoop (C:\Users\MSJim\Documents\programming-data\visual-studio-code\frontends\sveltekit-websockets-chat\node_modules\ws\lib\receiver.js:158:22)
at Receiver._write (C:\Users\MSJim\Documents\programming-data\visual-studio-code\frontends\sveltekit-websockets-chat\node_modules\ws\lib\receiver.js:84:10)
at writeOrBuffer (node:internal/streams/writable:392:12)
at _write (node:internal/streams/writable:333:10)
at Writable.write (node:internal/streams/writable:337:10)
at Socket.socketOnData (C:\Users\MSJim\Documents\programming-data\visual-studio-code\frontends\sveltekit-websockets-chat\node_modules\ws\lib\websocket.js:1274:35)
at Socket.emit (node:events:525:35)
at addChunk (node:internal/streams/readable:324:12)
Emitted 'error' event on WebSocket instance at:
at Receiver.receiverOnError (C:\Users\MSJim\Documents\programming-data\visual-studio-code\frontends\sveltekit-websockets-chat\node_modules\ws\lib\websocket.js:1160:13)
at Receiver.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'WS_ERR_INVALID_CLOSE_CODE',
[Symbol(status-code)]: 1002
}
Where it reads invalid status code 16001, the 16001 seems to change every time I run it. I have gotten 39338, 38329, and 29320 when running it 3 additional times.

Firebase Auth testing with jest and emulator calling the login throws Error: Headers X-Client-Version forbidden

I try to login a dummy user with the firebase js sdk localy. I have the default firebase emulator running. After calling the function i get following exception:
Error: Headers X-Client-Version forbidden
at dispatchError (C:\Users\user\Documents\Projekte\Backend\functions\node_modules\jsdom\lib\jsdom\living\xhr\xhr-utils.js:62:19)
at validCORSPreflightHeaders (C:\Users\user\Documents\Projekte\Backend\functions\node_modules\jsdom\lib\jsdom\living\xhr\xhr-utils.js:99:5)
at Request.<anonymous> (C:\Users\user\Documents\Projekte\Backend\functions\node_modules\jsdom\lib\jsdom\living\xhr\xhr-utils.js:367:12)
at Request.emit (events.js:315:20)
at Request.onRequestResponse (C:\Users\user\Documents\Projekte\Backend\functions\node_modules\request\request.js:1059:10)
at ClientRequest.emit (events.js:315:20)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:641:27)
at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)
at Socket.socketOnData (_http_client.js:509:22)
at Socket.emit (events.js:315:20) undefined
at VirtualConsole.<anonymous> (node_modules/jsdom/lib/jsdom/virtual-console.js:29:45)
at dispatchError (node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:65:53)
at validCORSPreflightHeaders (node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:99:5)
at Request.<anonymous> (node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:367:12)
at Request.onRequestResponse (node_modules/request/request.js:1059:10)
console.log
t {
code: 'auth/network-request-failed',
message: 'A network error (such as timeout, interrupted connection or unreachable host) has occurred.',
a: null
}
at Object.<anonymous> (test/test.ts:275:12)
If i try to connect to my online project it works fine, but i want to perform my testing localy with the emulator.
Example Code:
const app = firebase.initializeApp(firebaseConfig);
app.auth().useEmulator("http://localhost:9099");
app.firestore().settings({
host: "localhost:8080",
ssl: false,
});
test('Example test case', async () => {
try {
const cred: UserCredential = await app.auth().signInWithEmailAndPassword("foo#bar.de", "bla2377");
expect(cred).toBeTruthy();
expect(cred.user).toBeTruthy();
} catch (e) {
console.log(e);
expect(true).toBeFalsy();
}
});
Enviorment Informations:
Operating System version: Windows 10 Home 10.0.18363 Build 18363
Firebase SDK version: 8.2.3
Jest Version: 26.6.3
Node Version: 14
jsdom doesn't support wildcard access-control-allow-headers, which are used by firebase. This answer fixes the exception.

Node.js child_process has no access to global modules

I have installed a npm packages globally in my Kubuntu 19.04
$ npm install -g cordova
/home/username/.npm-global/bin/cordova -> /home/username/.npm-global/lib/node_modules/cordova/bin/cordova
+ cordova#9.0.0
updated 1 package in 7.299s
I can access it from shell
$ cordova -v
9.0.0 (cordova-lib#9.0.1)
But I can't access it from a simple node script with spawn:
const { spawn } = require( 'child_process' );
const cmd = spawn( 'cordova', [ '-v' ] );
cmd.stdout.on( 'data', data => {
console.log( `stdout: ${data}` );
} );
Running it results in the following:
$ node test1.js
events.js:298
throw er; // Unhandled 'error' event
^
Error: spawn cordova ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)
at onErrorNT (internal/child_process.js:467:16)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Emitted 'error' event on ChildProcess instance at:
at Process.ChildProcess._handle.onexit (internal/child_process.js:273:12)
at onErrorNT (internal/child_process.js:467:16)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
errno: -2,
code: 'ENOENT',
syscall: 'spawn cordova',
path: 'cordova',
spawnargs: [ '-v' ]
}
But when using absolute path:
const { spawn } = require( 'child_process' );
const cmd = spawn( '/home/username/.npm-global/bin/cordova', [ '-v' ] );
cmd.stdout.on( 'data', data => {
console.log( `stdout: ${data}` );
} );
I get the expected result:
$ node test1.js
stdout: 9.0.0 (cordova-lib#9.0.1)
My script above is just a testcase, since I have problem to add/run cordova specific stuff in vue-cli-plugin-cordova and quasar. I tracked it down, that the global path is the problem.
Update
I think I found the problem, but not sure how to solve it. When setting /bin/bash as shell, it works:
cmd = spawn('cordova', ['-v'], {
shell: '/bin/bash'
});
Not sure, why this is needed and why the packages vue-cli-plugin-cordova and quasar don't do it.
Ok, after hours of research and tryouts, I have uninstalled node, installed nvm and latest node, set
nvm use --delete-prefix v13.7.0 --silent >> /dev/null
and added this to ~/.bashrc
and now everything works
how I solve my error, I changed the environment variable PATH: to C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;{plus program paths}
which is
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\nodejs
in my PATH

Not able to connect a rabbitmq docker with appl docker

I have a simple app (simple.js), written in nodejs,
var amqp = require('amqplib/callback_api');
amqp.connect('amqp://localhost', function(err, conn) {
conn.createChannel(function(err, ch) {
var q = 'hello';
ch.assertQueue(q, {durable: false});
// Note: on Node 6 Buffer.from(msg) should be used
ch.sendToQueue(q, new Buffer('Hello World!'));
console.log(" [x] Sent 'Hello World!'");
});
setTimeout(function() { conn.close(); process.exit(0) }, 500);
});
And I have dockerized it (simple-app). Then I pulled rabbitmq docker from docker hub.
When I try to link these in following manner :
docker run -d --name rabbitmq-server rabbitmq:latest
docker build -t simple-app .
docker run -d -P --name myapp --link rabbitmq-server:rabbitmq-server simple-app
docker logs a8789193af523b
I get the below mentioned error :
/usr/src/server/simple.js:3
conn.createChannel(function(err, ch) {
^
TypeError: Cannot read property 'createChannel' of undefined
at /usr/src/server/simple.js:3:7
at /usr/src/server/node_modules/amqplib/callback_api.js:16:10
at Socket.<anonymous> (/usr/src/server/node_modules/amqplib/lib/connect.js:167:18)
at Socket.g (events.js:292:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at emitErrorNT (net.js:1277:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
I have tried many ways in order to resolve :
1. Exposed all ports with -P option using --links
2. Did mapping of specific ports with -p option --links
3. created network with bridge as driver and used that n/w for starting all my dockers.
None of the above methods seem to work, I am continuosly getting same error.
I am trying this on AWS (EC2) .. amazon linux.
Also, if I try to run the simple.js directly on linux, it is successfully connecting to my rabbitmq server (which is dockerized).
Please help me out here !!

Getting Error: spawn ./node_modules/.bin/grunt ENOENT when running grunt

I have a project that is started in development by
yarn start
It runs a index.js that starts a grunt process and get this error:
$ yarn start
yarn start v0.23.2
$ node ./development
grunt_arguments [ '--force', '--notify', '--verbose', '--debug', '--stack' ]
=======================================
Open http://localhost:8000 to start developing
events.js:141
throw er; // Unhandled 'error' event
^
Error: spawn ./node_modules/.bin/grunt ENOENT
at exports._errnoException (util.js:907:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:189:32)
at onErrorNT (internal/child_process.js:355:16)
at nextTickCallbackWith2Args (node.js:458:9)
at process._tickCallback (node.js:372:17)
at Function.Module.runMain (module.js:443:11)
at startup (node.js:139:18)
at node.js:990:3
error Command failed with exit code 1.
No idea what can it be. Environment is:
Win10
Running with MINGW64
I usually monkey patch child_process to help me debug that kind of issues. Add something like this in the beginning of your index.js file:
const util = require('util')
const childProcess = require("child_process");
const originalSpawn = childProcess.spawn;
childProcess.spawn = function() {
console.trace('SPAWN');
console.log('ARGS');
console.log(util.inspect(arguments, false, null)); // showHidden = false, depth = null
return originalSpawn.apply(this, arguments);
};
If your run, childProcess.spawn('ls', ['-lh', '/usr']) you will see something like:
Trace: SPAWN
at Object.childProcess.spawn (repl:2:9)
at myFunction (repl:2:14)
at repl:1:1
at REPLServer.defaultEval (repl.js:164:27)
at bound (domain.js:250:14)
at REPLServer.runBound [as eval] (domain.js:263:12)
at REPLServer.<anonymous> (repl.js:392:12)
at emitOne (events.js:82:20)
at REPLServer.emit (events.js:169:7)
at REPLServer.Interface._onLine (readline.js:210:10)
ARGS
{ '0': 'ls', '1': [ '-lh', '/usr' ] }
Maybe after running it you can update your question with the new information.

Resources