Get password from input using node.js - input

How to get password from input using node.js? Which means you should not output password entered in console.

You can use the read module (disclosure: written by me) for this:
In your shell:
npm install read
Then in your JS:
var read = require('read')
read({ prompt: 'Password: ', silent: true }, function(er, password) {
console.log('Your password is: %s', password)
})

Update 2015 Dec 13: readline has replaced process.stdin and node_stdio was removed from Node 0.5.10.
var BACKSPACE = String.fromCharCode(127);
// Probably should use readline
// https://nodejs.org/api/readline.html
function getPassword(prompt, callback) {
if (prompt) {
process.stdout.write(prompt);
}
var stdin = process.stdin;
stdin.resume();
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
var password = '';
stdin.on('data', function (ch) {
ch = ch.toString('utf8');
switch (ch) {
case "\n":
case "\r":
case "\u0004":
// They've finished typing their password
process.stdout.write('\n');
stdin.setRawMode(false);
stdin.pause();
callback(false, password);
break;
case "\u0003":
// Ctrl-C
callback(true);
break;
case BACKSPACE:
password = password.slice(0, password.length - 1);
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(prompt);
process.stdout.write(password.split('').map(function () {
return '*';
}).join(''));
break;
default:
// More passsword characters
process.stdout.write('*');
password += ch;
break;
}
});
}
getPassword('Password: ', (ok, password) => { console.log([ok, password]) } );

To do this I found this excellent Google Group post
Which contains the following snippet:
var stdin = process.openStdin()
, stdio = process.binding("stdio")
stdio.setRawMode()
var password = ""
stdin.on("data", function (c) {
c = c + ""
switch (c) {
case "\n": case "\r": case "\u0004":
stdio.setRawMode(false)
console.log("you entered: "+password)
stdin.pause()
break
case "\u0003":
process.exit()
break
default:
password += c
break
}
})

Here is my tweaked version of nailer's from above, updated to get a callback and for node 0.8 usage:
/**
* Get a password from stdin.
*
* Adapted from <http://stackoverflow.com/a/10357818/122384>.
*
* #param prompt {String} Optional prompt. Default 'Password: '.
* #param callback {Function} `function (cancelled, password)` where
* `cancelled` is true if the user aborted (Ctrl+C).
*
* Limitations: Not sure if backspace is handled properly.
*/
function getPassword(prompt, callback) {
if (callback === undefined) {
callback = prompt;
prompt = undefined;
}
if (prompt === undefined) {
prompt = 'Password: ';
}
if (prompt) {
process.stdout.write(prompt);
}
var stdin = process.stdin;
stdin.resume();
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
var password = '';
stdin.on('data', function (ch) {
ch = ch + "";
switch (ch) {
case "\n":
case "\r":
case "\u0004":
// They've finished typing their password
process.stdout.write('\n');
stdin.setRawMode(false);
stdin.pause();
callback(false, password);
break;
case "\u0003":
// Ctrl-C
callback(true);
break;
default:
// More passsword characters
process.stdout.write('*');
password += ch;
break;
}
});
}

How to use read without a callback
With async/await, we can get rid of the annoying callback with the following standard pattern:
const readCb = require('read')
async function read(opts) {
return new Promise((resolve, reject) => {
readCb(opts, (err, line) => {
if (err) {
reject(err)
} else {
resolve(line)
}
})
})
}
;(async () => {
const password = await read({ prompt: 'Password: ', silent: true })
console.log(password)
})()
The annoyance is that then you have to propagate async/await to the entire call stack, but it is generally the way to go, as it clearly marks what is async or not.
Tested on "read": "1.0.7", Node.js v14.17.0.
TODO how to prevent EAGAIN error if you try to use stdin again later with fs.readFileSync(0)?
Both read and https://stackoverflow.com/a/10357818/895245 cause future attempts to read from stdin with fs.readFileSync(0) to break with EAGAIN. Not sure how to fix that. Reproduction:
const fs = require('fs')
const readCb = require('read')
async function read(opts) {
return new Promise((resolve, reject) => {
readCb(opts, (err, line) => {
resolve([err, line])
})
})
}
;(async () => {
const [err, password] = await read({ prompt: 'Password: ', silent: true })
console.log(password)
console.log(fs.readFileSync(0).toString())
})()
or:
#!/usr/bin/env node
const fs = require('fs')
var BACKSPACE = String.fromCharCode(127);
// Probably should use readline
// https://nodejs.org/api/readline.html
function getPassword(prompt, callback) {
if (prompt) {
process.stdout.write(prompt);
}
var stdin = process.stdin;
stdin.resume();
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
var password = '';
stdin.on('data', function (ch) {
ch = ch.toString('utf8');
switch (ch) {
case "\n":
case "\r":
case "\u0004":
// They've finished typing their password
process.stdout.write('\n');
stdin.setRawMode(false);
stdin.pause();
callback(false, password);
break;
case "\u0003":
// Ctrl-C
callback(true);
break;
case BACKSPACE:
password = password.slice(0, password.length - 1);
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(prompt);
process.stdout.write(password.split('').map(function () {
return '*';
}).join(''));
break;
default:
// More passsword characters
process.stdout.write('*');
password += ch;
break;
}
});
}
async function read(opts) {
return new Promise((resolve, reject) => {
getPassword(opts, (err, line) => {
resolve([err, line])
})
})
}
;(async () => {
const [err, password] = await read('Password: ')
console.log(password)
console.log(fs.readFileSync(0).toString())
})()
Error:
fs.js:614
handleErrorFromBinding(ctx);
^
Error: EAGAIN: resource temporarily unavailable, read
at Object.readSync (fs.js:614:3)
at tryReadSync (fs.js:383:20)
at Object.readFileSync (fs.js:420:19)
at /home/ciro/test/main.js:70:18
at processTicksAndRejections (internal/process/task_queues.js:95:5) {
errno: -11,
syscall: 'read',
code: 'EAGAIN'
}
Asked at: https://github.com/npm/read/issues/39

Related

Cloudflare ESI worker / TypeError: Body has already been used

I'm trying to use a CloudFlare worker to manage my backend ESI fragments but i get an error:
Uncaught (in promise) TypeError: Body has already been used. It can only be used once. Use tee() first if you need to read it twice.
Uncaught (in response) TypeError: Body has already been used. It can only be used once. Use tee() first if you need to read it twice.
I don't find where the body has already been used
The process is:
get a response with the parts
Transform the body by replacing parts fragments with sub Backend calls (streamTransformBody function)
return the response
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
});
const esiHeaders = {
"user-agent": "cloudflare"
}
async function handleRequest(request) {
// get cookies from the request
if(cookie = request.headers.get("Cookie")) {
esiHeaders["Cookie"] = cookie
console.log(cookie)
}
// Clone the request so that it's no longer immutable
newRequest = new Request(request)
// remove cookie from request
newRequest.headers.delete('Cookie')
// Add header to get <esi>
newRequest.headers.set("Surrogate-Capability", "abc=ESI/1.0")
console.log(newRequest.url);
const response = await fetch(newRequest);
let contentType = response.headers.get('content-type')
if (!contentType || !contentType.startsWith("text/")) {
return response
}
// Clone the response so that it's no longer immutable
const newResponse = new Response(response.body, response);
let { readable, writable } = new TransformStream()
streamTransformBody(newResponse.body, writable)
newResponse.headers.append('x-workers-hello', 'Hello from
Cloudflare Workers');
return newResponse;
}
async function streamTransformBody(readable, writable) {
const startTag = "<".charCodeAt(0);
const endTag = ">".charCodeAt(0);
let reader = readable.getReader();
let writer = writable.getWriter();
let templateChunks = null;
while (true) {
let { done, value } = await reader.read();
if (done) break;
while (value.byteLength > 0) {
if (templateChunks) {
let end = value.indexOf(endTag);
if (end === -1) {
templateChunks.push(value);
break;
} else {
templateChunks.push(value.subarray(0, end));
await writer.write(await translate(templateChunks));
templateChunks = null;
value = value.subarray(end + 1);
}
}
let start = value.indexOf(startTag);
if (start === -1) {
await writer.write(value);
break;
} else {
await writer.write(value.subarray(0, start));
value = value.subarray(start + 1);
templateChunks = [];
}
}
}
await writer.close();
}
async function translate(chunks) {
const decoder = new TextDecoder();
let templateKey = chunks.reduce(
(accumulator, chunk) =>
accumulator + decoder.decode(chunk, { stream: true }),
""
);
templateKey += decoder.decode();
return handleTemplate(new TextEncoder(), templateKey);
}
async function handleTemplate(encoder, templateKey) {
const linkRegex = /(esi:include.*src="(.*?)".*\/)/gm
let result = linkRegex.exec(templateKey);
let esi
if (!result) {
return encoder.encode(`<${templateKey}>`);
}
if (result[2]) {
esi = await subRequests(result[2]);
}
return encoder.encode(
`${esi}`
);
}
async function subRequests(target){
target = esiHost + target
const init = {
method: 'GET',
headers: esiHeaders
}
let response = await fetch(target, init)
if (!response.ok) {
return ''
}
let text = await response.text()
return '<!--esi-->' + text + '<!--/esi-->'
}

Discord.JS Purge.js command issue

Ok so my bot got rebuilt with a somewhat different code.
I'm using a somewhat more simplified fs command and events handler. My command works as intended.
But I'm wanting to add the amount pruned into the fields for the richEmbed and it keeps erroring out.
Here is my purge.js file
const Discord = require('discord.js')
module.exports = {
name: 'purge',
description: 'Purge up to 99 messages.',
execute(message, args) {
console.log("purging messages")
const embed = new Discord.RichEmbed()
.setTitle("Success")
.setColor(0x00AE86)
.setFooter("Guardian", "https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setThumbnail("https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setTimestamp()
.setURL("https://github.com/phantomdev-github/Resources/tree/master/Discord%20Bots/Guardian")
.addField("Bot Messages Purged", "missing code here", false)
.addField("User Pins Purged", "missing code here", false)
.addField("User Messages Purged", "missing code here", false)
.addField("Total Messages Purged", "missing code here", false)
message.channel.send({ embed });
const amount = parseInt(args[0]) + 1;
if (isNaN(amount)) {
return message.reply('that doesn\'t seem to be a valid number.');
} else if (amount <= 1 || amount > 100) {
return message.reply('you need to input a number between 1 and 99.');
}
message.channel.bulkDelete(amount, true).catch(err => {
console.error(err);
message.channel.send('there was an error trying to prune messages in this channel!');
});
},
};
If it helps this i my index.js
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
const { token } = require('./token.json');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
console.log(file,command)
}
fs.readdir('./events/', (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
if(!file.endsWith('.js')) return;
const eventFunction = require(`./events/${file}`);
console.log(eventFunction)
eventFunction.execute(client)
});
});
client.login(token);
and this is my message.js
const { prefix } = require('./prefix.json');
module.exports = {
name: 'message',
description: '',
execute:function(client) {
client.on('message',message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
})
}};
Basically I'm trying to figure out what to place into the "missing code here" sections. Also any way to lock it to people with Administrator permissions only would be useful as well. I attempted that but it failed to work with the embed.
If I understand you right you want to know how to get the amount of the purged pins, bot msgs and user msgs. For this you need to put your embed after you deleted the messages.
purge.js
const Discord = require('discord.js')
module.exports = {
name: 'purge',
description: 'Purge up to 99 messages.',
execute(message, args) {
console.log("purging messages")
const amount = parseInt(args[0]) + 1;
if (isNaN(amount)) {
return message.reply('that doesn\'t seem to be a valid number.');
} else if (amount <= 1 || amount > 100) {
return message.reply('you need to input a number between 1 and 99.');
}
message.channel.bulkDelete(amount, true).then(deletedMessages => {
// Filter the deleted messages with .filter()
var botMessages = deletedMessages.filter(m => m.author.bot);
var userPins = deletedMessages.filter(m => m.pinned);
var userMessages = deletedMessages.filter(m => !m.author.bot);
const embed = new Discord.RichEmbed()
.setTitle("Success")
.setColor(0x00AE86)
.setFooter("Guardian", "https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setThumbnail("https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setTimestamp()
.setURL("https://github.com/phantomdev-github/Resources/tree/master/Discord%20Bots/Guardian")
.addField("Bot Messages Purged", botMessages.size, false)
.addField("User Pins Purged", userPins.size, false)
.addField("User Messages Purged", userMessages.size, false)
.addField("Total Messages Purged", deletedMessages.size, false);
message.channel.send(embed);
}).catch(err => {
console.error(err);
message.channel.send('there was an error trying to prune messages in this channel!');
});
},
};

Angular 5 HttpRequest reportProgress

I have a block of code that when executed in every other browser including IE11 works just fine, but for whatever reason when Edge runs this code I don't get a progress like the other browsers.
Edge logs this:
progress-- true
event.type == 0
A long pause and then writes:
progress: true
loaded: xxx
total: xxx
type: 1
Code:
Upload(file : File, id:number, endPoint:string) : void {
const formData = new FormData();
formData.append(file.name, file);
var auth = "Bearer " + this.Auth.GetAuth();
var autoThumb = this.stagedThumb == null ? 'true' : 'false';
const uploadRequest = new HttpRequest('POST', endPoint + `?id=${id}&thumb=${autoThumb}`, formData, {
reportProgress: true,
headers: new HttpHeaders({
'Authorization': auth
})
});
this.PerformUpload(uploadRequest);
}
PerformUpload(uploadRequest : HttpRequest<FormData>, progress: boolean = true) : void {
this.http.request(uploadRequest).subscribe(event =>
{
console.log("Http Event Message -- Progress: " + progress);
console.log(event);
console.log("End Event Message");
if (progress)
{
if (event.type == HttpEventType.UploadProgress)
{
this.progress = Math.round(100 * event.loaded / event.total);
}
else if (event.type == HttpEventType.Response)
{
this.message = event.body.toString();
setTimeout(() => {
this.ResetForm();
}, 2*1000);
}
}
});
}
In case you have not found the root cause yet, it seems this is an open issue for MS Edge.
See https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/12224510/

sinon stub is not working

I'm quiet new into testing and I don't seem to succeed to succesfully stub a function. I'm trying to stub the connection to the database, but it keep's contacting it, instead of using the result from the stub:
Here's the function:
var self = module.exports = {
VerifyAuthentication: function (data){
var deferred = q.defer()
if(typeof(data.email)=='undefined'){
deferred.reject({data:{},errorcode:"",errormessage:"param 'email' is mandatory in input object"})
}else{
if(typeof(data.password)=='undefined'){
deferred.reject({data:{},errorcode:"",errormessage:"param 'password' is mandatory in input object"})
}else{
var SqlString = "select id, mail, password, origin from tbl_user where mail = ?"
var param = [data.email]
self.ExecuteSingleQuery(SqlString, param).then(function(results){
if(results.length > 0)
{
if (results[0].password == data.password)
{
deferred.resolve({data:{"sessionId":results[0].id},errorcode:"",errormessage:""})
}else{
deferred.reject({data:{},errorcode:"",errormessage:"bad password"})
}
}else{
deferred.reject({data:{},errorcode:"",errormessage:"unknown user"})
}
})
}
}
return deferred.promise
},
ExecuteSingleQuery: function (queryString, parameters){
var deferred = q.defer()
var connection = connect()
connection.query(queryString, parameters, function (error, results, fields){
if(error){ deferred.reject(error)};
deferred.resolve(results)
});
return deferred.promise
},
And here's the test:
var dbconnection = require('../lib/dbConnection.js')
describe("VerifyAuthentication", function(){
it("_Returns DbResult object when user name and password match", function(){
var expectedResult = {data:{"sessionKey":"b12ac0a5-967e-40f3-8c4d-aac0f98328b2"},errorcode:"",errormessage:""}
stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').returns(Promise.resolve(expectedResult))
return dbconnection.VerifyAuthentication({email:"correct#adres.com",password:"gtffr"}).then((result)=>{
expect(result.data.sessionId).to.not.be.undefined
expect(result.errorcode).to.not.be.undefined
expect(result.errormessage).to.not.be.undefined
stub.restore()
})
})
})
I always got an error 'unknown user', which is normal, because the user is indeed not in the database. However, I want to stub the 'ExecuteSingleQuery' function, avoiding it to connect to DB.
I have fixed a couple of issues in your code and posting the corrected files below.
dbConnection.js
var self = module.exports = {
VerifyAuthentication: function (data) {
var deferred = q.defer();
if (typeof (data.email) == 'undefined') {
deferred.reject({
data: {},
errorcode: '',
errormessage: "param 'email' is mandatory in input object"
});
} else {
if (typeof (data.password) == 'undefined') {
deferred.reject({
data: {},
errorcode: '',
errormessage: "param 'password' is mandatory in input object"
});
} else {
var SqlString = 'select id, mail, password, origin from tbl_user where mail = ?';
var param = [data.email];
self.ExecuteSingleQuery(SqlString, param).then(function (results) {
if (results.length > 0) {
if (results[0].password === data.password) {
deferred.resolve({
data: {
'sessionId': results[0].id
},
errorcode: '',
errormessage: ''
});
} else {
deferred.reject({
data: {},
errorcode: '',
errormessage: 'bad password'
});
}
} else {
deferred.reject({
data: {},
errorcode: '',
errormessage: 'unknown user'
});
}
});
}
}
return deferred.promise;
},
ExecuteSingleQuery: function (queryString, parameters) {
var deferred = q.defer();
var connection = connect();
connection.query(queryString, parameters, function (error, results, fields) {
if (error) {
deferred.reject(error);
}
deferred.resolve(results);
});
return deferred.promise;
}
};
dbConnection.test.js
describe('VerifyAuthentication', function () {
it('Returns DbResult object when user name and password match', function () {
var expectedResult = [{
id: '123',
password: 'gtffr'
}];
const stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').resolves(expectedResult);
return dbconnection.VerifyAuthentication({
email: 'correct#adres.com',
password: 'gtffr'
}).then((result) => {
expect(result.data.sessionId).to.not.be.undefined;
expect(result.errorcode).to.not.be.undefined;
expect(result.errormessage).to.not.be.undefined;
stub.restore();
});
});
});
I am outlining the problematic parts below:
The expectedResult variable had a wrong type of value. In the
self.ExecuteSingleQuery() implementation you check for an array with length > 0. The fixed result returned by the stub, was an object instead of an array and this is why it returned the unknown user exception
The array should contain an object with { id: 'xxx', password: 'gtffr' } attributes. Password is validated against the one used by the dbconnection.VerifyAuthentication({email:"correct#adres.com",password:"gtffr"}) call
Finally, I have changed the stub statement to resolve instead of return as shown here const stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').resolves(expectedResult); - this is the preferred method of resolving a promise

Failed to set local answer sdp: Called in wrong state: kStable

for a couple of days I'm now stuck with trying to get my webRTC client to work and I can't figure out what I'm doing wrong.
I'm trying to create multi peer webrtc client and am testing both sides with Chrome.
When the callee receives the call and create the Answer, I get the following error:
Failed to set local answer sdp: Called in wrong state: kStable
The receiving side correctly establishes both video connnections and is showing the local and remote streams. But the caller seems not to receive the callees answer. Can someone hint me what I am doing wrong here?
Here is the code I am using (it's a stripped version to just show the relevant parts and make it better readable)
class WebRTC_Client
{
private peerConns = {};
private sendAudioByDefault = true;
private sendVideoByDefault = true;
private offerOptions = {
offerToReceiveAudio: true,
offerToReceiveVideo: true
};
private constraints = {
"audio": true,
"video": {
frameRate: 5,
width: 256,
height: 194
}
};
private serversCfg = {
iceServers: [{
urls: ["stun:stun.l.google.com:19302"]
}]
};
private SignalingChannel;
public constructor(SignalingChannel){
this.SignalingChannel = SignalingChannel;
this.bindSignalingHandlers();
}
/*...*/
private gotStream(stream) {
(<any>window).localStream = stream;
this.videoAssets[0].srcObject = stream;
}
private stopLocalTracks(){}
private start() {
var self = this;
if( !this.isReady() ){
console.error('Could not start WebRTC because no WebSocket user connectionId had been assigned yet');
}
this.buttonStart.disabled = true;
this.stopLocalTracks();
navigator.mediaDevices.getUserMedia(this.getConstrains())
.then((stream) => {
self.gotStream(stream);
self.SignalingChannel.send(JSON.stringify({type: 'onReadyForTeamspeak'}));
})
.catch(function(error) { trace('getUserMedia error: ', error); });
}
public addPeerId(peerId){
this.availablePeerIds[peerId] = peerId;
this.preparePeerConnection(peerId);
}
private preparePeerConnection(peerId){
var self = this;
if( this.peerConns[peerId] ){
return;
}
this.peerConns[peerId] = new RTCPeerConnection(this.serversCfg);
this.peerConns[peerId].ontrack = function (evt) { self.gotRemoteStream(evt, peerId); };
this.peerConns[peerId].onicecandidate = function (evt) { self.iceCallback(evt, peerId); };
this.peerConns[peerId].onnegotiationneeded = function (evt) { if( self.isCallingTo(peerId) ) { self.createOffer(peerId); } };
this.addLocalTracks(peerId);
}
private addLocalTracks(peerId){
var self = this;
var localTracksCount = 0;
(<any>window).localStream.getTracks().forEach(
function (track) {
self.peerConns[peerId].addTrack(
track,
(<any>window).localStream
);
localTracksCount++;
}
);
trace('Added ' + localTracksCount + ' local tracks to remote peer #' + peerId);
}
private call() {
var self = this;
trace('Start calling all available new peers if any available');
// only call if there is anyone to call
if( !Object.keys(this.availablePeerIds).length ){
trace('There are no callable peers available that I know of');
return;
}
for( let peerId in this.availablePeerIds ){
if( !this.availablePeerIds.hasOwnProperty(peerId) ){
continue;
}
this.preparePeerConnection(peerId);
}
}
private createOffer(peerId){
var self = this;
this.peerConns[peerId].createOffer( this.offerOptions )
.then( function (offer) { return self.peerConns[peerId].setLocalDescription(offer); } )
.then( function () {
trace('Send offer to peer #' + peerId);
self.SignalingChannel.send(JSON.stringify({ "sdp": self.peerConns[peerId].localDescription, "remotePeerId": peerId, "type": "onWebRTCPeerConn" }));
})
.catch(function(error) { self.onCreateSessionDescriptionError(error); });
}
private answerCall(peerId){
var self = this;
trace('Answering call from peer #' + peerId);
this.peerConns[peerId].createAnswer()
.then( function (answer) { return self.peerConns[peerId].setLocalDescription(answer); } )
.then( function () {
trace('Send answer to peer #' + peerId);
self.SignalingChannel.send(JSON.stringify({ "sdp": self.peerConns[peerId].localDescription, "remotePeerId": peerId, "type": "onWebRTCPeerConn" }));
})
.catch(function(error) { self.onCreateSessionDescriptionError(error); });
}
private onCreateSessionDescriptionError(error) {
console.warn('Failed to create session description: ' + error.toString());
}
private gotRemoteStream(e, peerId) {
if (this.audioAssets[peerId].srcObject !== e.streams[0]) {
this.videoAssets[peerId].srcObject = e.streams[0];
trace('Added stream source of remote peer #' + peerId + ' to DOM');
}
}
private iceCallback(event, peerId) {
this.SignalingChannel.send(JSON.stringify({ "candidate": event.candidate, "remotePeerId": peerId, "type": "onWebRTCPeerConn" }));
}
private handleCandidate(candidate, peerId) {
this.peerConns[peerId].addIceCandidate(candidate)
.then(
this.onAddIceCandidateSuccess,
this.onAddIceCandidateError
);
trace('Peer #' + peerId + ': New ICE candidate: ' + (candidate ? candidate.candidate : '(null)'));
}
private onAddIceCandidateSuccess() {
trace('AddIceCandidate success.');
}
private onAddIceCandidateError(error) {
console.warn('Failed to add ICE candidate: ' + error.toString());
}
private hangup() {}
private bindSignalingHandlers(){
this.SignalingChannel.registerHandler('onWebRTCPeerConn', (signal) => this.handleSignals(signal));
}
private handleSignals(signal){
var self = this,
peerId = signal.connectionId;
if( signal.sdp ) {
trace('Received sdp from peer #' + peerId);
this.peerConns[peerId].setRemoteDescription(new RTCSessionDescription(signal.sdp))
.then( function () {
if( self.peerConns[peerId].remoteDescription.type === 'answer' ){
trace('Received sdp answer from peer #' + peerId);
} else if( self.peerConns[peerId].remoteDescription.type === 'offer' ){
trace('Received sdp offer from peer #' + peerId);
self.answerCall(peerId);
} else {
trace('Received sdp ' + self.peerConns[peerId].remoteDescription.type + ' from peer #' + peerId);
}
})
.catch(function(error) { trace('Unable to set remote description for peer #' + peerId + ': ' + error); });
} else if( signal.candidate ){
this.handleCandidate(new RTCIceCandidate(signal.candidate), peerId);
} else if( signal.closeConn ){
trace('Closing signal received from peer #' + peerId);
this.endCall(peerId,true);
}
}
}
I have been using a similar construct to build up the WebRTC connections between sender and receiver peers, by calling the method RTCPeerConnection.addTrack twice (one for the audio track, and one for the video track).
I used the same structure as shown in the Stage 2 example shown in The evolution of WebRTC 1.0:
let pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection(), stream, videoTrack, videoSender;
(async () => {
try {
stream = await navigator.mediaDevices.getUserMedia({video: true, audio: true});
videoTrack = stream.getVideoTracks()[0];
pc1.addTrack(stream.getAudioTracks()[0], stream);
} catch (e) {
console.log(e);
}
})();
checkbox.onclick = () => {
if (checkbox.checked) {
videoSender = pc1.addTrack(videoTrack, stream);
} else {
pc1.removeTrack(videoSender);
}
}
pc2.ontrack = e => {
video.srcObject = e.streams[0];
e.track.onended = e => video.srcObject = video.srcObject; // Chrome/Firefox bug
}
pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
pc1.onnegotiationneeded = async e => {
try {
await pc1.setLocalDescription(await pc1.createOffer());
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription(await pc2.createAnswer());
await pc1.setRemoteDescription(pc2.localDescription);
} catch (e) {
console.log(e);
}
}
Test it here: https://jsfiddle.net/q8Lw39fd/
As you'll notice, in this example the method createOffer is never called directly; instead, it is indirectly called via addTrack triggering an RTCPeerConnection.onnegotiationneeded event.
However, just as in your case, Chrome triggers this event twice, once for each track, and this causes the error message you mentioned:
DOMException: Failed to set local answer sdp: Called in wrong state: kStable
This doesn't happen in Firefox, by the way: it triggers the event only once.
The solution to this issue is to write a workaround for the Chrome behavior: a guard that prevents nested calls to the (re)negotiation mechanism.
The relevant part of the fixed example would be like this:
pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
var isNegotiating = false; // Workaround for Chrome: skip nested negotiations
pc1.onnegotiationneeded = async e => {
if (isNegotiating) {
console.log("SKIP nested negotiations");
return;
}
isNegotiating = true;
try {
await pc1.setLocalDescription(await pc1.createOffer());
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription(await pc2.createAnswer());
await pc1.setRemoteDescription(pc2.localDescription);
} catch (e) {
console.log(e);
}
}
pc1.onsignalingstatechange = (e) => { // Workaround for Chrome: skip nested negotiations
isNegotiating = (pc1.signalingState != "stable");
}
Test it here: https://jsfiddle.net/q8Lw39fd/8/
You should be able to easily implement this guard mechanism into your own code.
You're sending the answer here:
.then( function (answer) { return self.peerConns[peerId].setLocalDescription(answer); } )
Look at mine:
var callback = function (answer) {
createdDescription(answer, fromId);
};
peerConnection[fromId].createAnswer().then(callback).catch(errorHandler);
function createdDescription(description, fromId) {
console.log('Got description');
peerConnection[fromId].setLocalDescription(description).then(function() {
console.log("Sending SDP:", fromId, description);
serverConnection.emit('signal', fromId, {'sdp': description});
}).catch(errorHandler);
}