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

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.

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.

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

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

Truffle migrate --network bsc error: header not found

When trying to run truffle migrate --network bsc, truffle usually (not always) manages to deploy the migrations contract, then fails with an error: header not found.
Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({ code: -32000, message: 'header not found' })
at new NodeError (node:internal/errors:363:5)
at Web3ProviderEngine.emit (node:events:354:17)
at D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:54:14
at afterRequest (D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:148:21)
at D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:174:21
at D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:232:9
at D:\Contracts\novaria\node_modules\async\internal\once.js:12:16
at replenish (D:\Contracts\novaria\node_modules\async\internal\eachOfLimit.js:61:25)
at D:\Contracts\novaria\node_modules\async\internal\eachOfLimit.js:71:9
at eachLimit (D:\Contracts\novaria\node_modules\async\eachLimit.js:43:36)
at D:\Contracts\novaria\node_modules\async\internal\doLimit.js:9:16
at end (D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:211:5)
at Request._callback (D:\Contracts\novaria\node_modules\web3-provider-engine\subproviders\rpc.js:70:28)
at Request.self.callback (D:\Contracts\novaria\node_modules\request\request.js:185:22)
at Request.emit (node:events:365:28)
at Request.<anonymous> (D:\Contracts\novaria\node_modules\request\request.js:1154:10)
at Request.emit (node:events:365:28)
at IncomingMessage.<anonymous> (D:\Contracts\novaria\node_modules\request\request.js:1076:12)
at Object.onceWrapper (node:events:471:28)
at IncomingMessage.emit (node:events:377:35)
at endReadableNT (node:internal/streams/readable:1312:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
Here's the config for bsc network:
bsc: {
provider: () => { return new HDWalletProvider(mnemonic, `https://bsc-dataseed2.binance.org/`)},
network_id: 56,
confirmations: 10,
timeoutBlocks: 200,
skipDryRun: true,
},
compilers: {
solc: {
version: "0.8.7", // Fetch exact version from solc-bin (default: truffle's version)
// docker: true, // Use "0.5.1" you've installed locally with docker (default: false)
settings: { // See the solidity docs for advice about optimization and evmVersion
optimizer: {
enabled: true,
runs: 200
},
Deploying to testnet and development works without issue. I have in the past deployed to bsc with truffle (been a while though). I've tried changing RPC urls, and messed around with timeout and confirmations (pretty sure that doesn't make a difference for this error). After searching the internet for solutions, the only answer that seems to have worked for people is to change the RPC, but I haven't had any luck with that. Does anyone have any suggestions?
I had the same problem today. Fixed it by using the Websocket endpoint wss://bsc-ws-node.nariox.org:443 from the smart chain docs https://docs.binance.org/smart-chain/developer/rpc.html

How to get PostgreSQL dump database file using Node JS

I tried to generate postgresql dump file using Node JS. SO, I used secure-backup library to generate pg-dump file encrypted. I add this package in my project and I configured .pem file also. When I execute this file it's throwing some error. but I couldn't understand what type error is throwing and how to fix it I don't know. Any one give some suggestion how to resolve this issue to generate pg dump file using Node JS otherwise different library used to generate pg dump file.
CODE
let secureBackup = require('secure-backup');
let pgHandler = require('secure-backup/lib/handlers/pg')
console.log('hi')
let backup = secureBackup({
pubKeyPath: 'C:/Users/DELL/Desktop/Twilio_Phone/cert.pem', // path to your public key
outputPath: 'C:/Users/DELL/Desktop/DB_Dump', // where to output your encrypted backup
compress: true, // enable compression (gzip)
handler: pgHandler({
user: 'postgres',
password: '*****',
database: '****'
})
})
backup() // can be invoked directly
// or used with a cron-job module like node-schedule
Error
events.js:292
throw er; // Unhandled 'error' event
^
Error: spawn pg_dump ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:269:19)
at onErrorNT (internal/child_process.js:465:16)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
Emitted 'error' event on ChildProcess instance at:
at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
at onErrorNT (internal/child_process.js:465:16)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: -4058,
code: 'ENOENT',
syscall: 'spawn pg_dump',
path: 'pg_dump',
spawnargs: [ '-U', 'postgres', 'HP', 'hummapi' ]
}

Mongoose failure to connect to Heroku database locally and process.env.MONGOLAB_URI

I am following a book's instructions. I have no trouble connecting to the local database or to MongoLab online in terminal, but can't run my app locally using my Heroku database with: NODE_ENV=production nodemon bin/www
This is my check in my code to use the online database depending on how I start the app:
if (process.env.NODE_ENV === 'production') {
dbURI= process.env.MONGOLAB_URI;
}
I manually input: heroku config:set MONGOLAB_URI=[my uri] as well as used the heroku config:get MONGOLAB_URI and keep getting: Error: failed to connect to [undefined:27017]
Does anybody have any ideas why I can't connect?
~ $ node app.js
/app/node_modules/connect-mongo/node_modules/mongodb/lib/server.js:228
process.nextTick(function() { throw err; })
^
Error
at Error.MongoError (/app/node_modules/connect-mongo/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:13:17)
at Server.destroy (/app/node_modules/connect-mongo/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:629:47)
at Server.close (/app/node_modules/connect-mongo/node_modules/mongodb/lib/server.js:344:17)
at Db.close (/app/node_modules/connect-mongo/node_modules/mongodb/lib/db.js:267:19)
at /app/node_modules/connect-mongo/node_modules/mongodb/lib/db.js:196:12
at null.<anonymous> (/app/node_modules/connect-mongo/node_modules/mongodb/lib/server.js:226:9)
at g (events.js:180:16)
at emit (events.js:98:17)
at null.<anonymous> (/app/node_modules/connect-mongo/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:238:68)
at g (events.js:180:16)
at emit (events.js:98:17)
at null.<anonymous> (/app/node_modules/connect-mongo/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js:77:12)
at g (events.js:180:16)
at emit (events.js:98:17)
at Socket.<anonymous> (/app/node_modules/connect-mongo/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js:118:49)
at Socket.g (events.js:180:16)
~ $
^^ I am seeing the above
My connection:
omeMongodbServer: {
adapter: 'sails-mongo',
url: process.env.MONGOLAB_URI || 'mongodb://localhost/ts',
},

Resources