Server-side Javascript functions - javascript

Ok guys. I've built a web application with some friends that is somehow complex and took us some time to built. It is entirely built using JavaScript
Now the application has some functions which we don't want to readily share with the world(view-source).
The application works by sending an input to an algorithm and receiving the output from that algorithm and displays it on a canvas. (Thats how all functions work anyway:) )
Okay i don't know much about node.js but from what i've heard its server-side JavaScript. Does that mean that i can transfer the function server-side and using POST-GET to send an input and receive an output? All without having the source code of that particular function readily visible to anyone?
Please don't get started about how i should be more worried about doing things better rather than worrying about the safety of our work. I already know that so consider my question as a complimentary safeguard, at least for the time being.
Obfuscation is not a very concrete option since many developers de-obfuscate code just for fun.
This application is not like a hen with a golden egg and i am not being grandiose about this, but i was just having this question in my mind for some time now so i just shoot it here to know in the future how things work.
Thanks guys!

If you're worried about protecting your ultra sweet super secret codes, you could host your app and use a little something called RPC. Remote. Procedure. Calls.
Check out this little guy
https://github.com/deoxxa/pillion
Easy as 1-2-3 or A-B-C or cake or strippers or whatever else is easy
% npm install pillion burro && echo omg that was so easy
DISCLAIMER
I'm about to reveal a super secret greeting function that says hello to our clients. This is ultra secret intellectual IP properties and should not be shared with anyone on the internets.
You could provide the function calls you need using something like this on the server
// server.js
var net = require("net"),
burro = require("burro"),
pillion = require("pillion");
var server = net.createServer(function(_socket) {
var socket = burro.wrap(_socket),
rpc = new pillion(socket);
rpc.provide("greet", function(name, cb) {
cb("hi there, " + name);
});
});
server.listen(3000);
Then on the client side
// client.js
var net = require("net"),
burro = require("burro"),
pillion = require("pillion");
var _socket = net.connect(3000),
socket = burro.wrap(_socket),
rpc = new pillion(socket);
rpc.callRemote("greet", "friend", function(res) {
console.log(res); // prints "hi there, friend"
});

Related

Generate bitcoin address from derivation scheme

I have a derivation scheme starting with tpub... for testnet and I want to be able to generate bitcoin addresses from derivation scheme. Also I want a method be applicable to mainnet, is any library available that could help me in this task. And code example how to do it what be great. I was thinking bitcore-lib would help, but didn't found anything useful for my task. But any solution would be fine. All useful information I found was a bunch of bips, but I doubt that I need to do that from scratch, and want to avoid it.
Have a time to publish a full answer now:
var runningNetwork = bjs.networks.testnet
const bip32 = require('bip32')
const bjs = require('bitcoinjs-lib')
let { address } = bjs.payments.p2wpkh({pubkey: bip32.fromBase58(dvScheme,runningNetwork).derive(0).derive(1).publicKey,})
console.log(`${address}`)

Candy Chat get User Groups from XMPP (openfire)

I need to get the XMPP-User Groups from all Users inside a MUC and the user itself ("me"). I'd like to use them to set some permissions inside the candy xmpp client.
There is no plugin for this issue. Inside candy.min.js I found this function:
Candy.Core.Contact.prototype.getGroups = function() {
return this.data.groups; };
I didn't found any notes about it in the docs nor any correlation inside the other code/plugins. So maybe, this function does not even work.
I tried to write my own plugin. But I'm not that deep in JS. Calling the getGroups() function did not work for me.
I am able to read the user groups data by using the REST API from openfire (xmpp server). So there is no issue with permissions or data. It's generally possible to get the user groups data in this configuration. But I'd really like to get a cleaner solution inside of a candy chat plugin.
There are some core functions in Candy, which allows to send queries via strophe.js. I don't get it, yet. But I think, there is a way to use these to get the userGroups. They look like this example to SET a user password.:
var pwChangeRequest = $iq({
type: 'set',
to: 'shakespeare.lit'
})
.c('query', {xmlns: 'jabber:iq:register'})
.c('username').t('bill').up()
.c('password').t('newpass');
Candy.Core.getConnection().sendIQ(
pwChangeRequest,
function () {
console.log("Password change was successful.")
},
function (responseStanza) {
console.log("Password change failed.");
console.log(responseStanza);
}
);
So, how do I need to change this snippet to request the XMPP user groups?
I'd also like to RTFM :) but i found nothing explaining for the CANDY <-> Candy Plugin <-> prototype / strophe /stanza <-> XMPP (openfire) communications. Got something to read for me?

Find free port not in use for apps - find some algorithm

I use the following API in my program to detrmine free port and provide it to application to run
portscanner.findAPortNotInUse(3000, 65000, '127.0.0.1', function(error, port) {
console.log('AVAILABLE PORT AT: ' + port)
})
https://github.com/baalexander/node-portscanner
This free port are given to application for use and working OK.
The problem is that if I provide a free port to application A and the application is doesn't occupied it yet(sometimes it takes some time...) and there is coming other application B and request a free port so it give to APP B the port of app A
Which cause to problem...
is there any elegant way to solve it?
my application doesn't have state so it cannot save to which app get which port...
There is solution that we can randomize the range but this is not robust ...
In my application Im getting the URL of the app that I should provide the free port to run.
update
I cannot use some broker or someting else that will controll this outside I need to find some algorithm (maybe with some smart random ) that can help me to do it internally i.e. my program is like singleton and I need some trick how to give port between 50000 to 65000 that will reduce the amount of collision of port that was provided to the apps
update 2
I've decided to try something like the following what do you think ?
using lodash https://lodash.com/docs/4.17.2#random to determine ports between with loops that provide 3(or more if that make sense) numbers for ranges like following
portscanner.findAPortNotInUse([50001, 60000, 600010], '127.0.0.1', function(err, port) {
if(err) {
console.log("error!!!-> " +err);
}else {
console.log('Port Not in Use ' + port);
}
//using that in a loop
var aa = _.random(50000, 65000);
Then If I got false in the port i.e. all 3 port are occupied ,run this process again for 3 other random number.comments suggestion are welcomed!!!
I try to find some way to avoid collision as much as possible...
I would simply accept the fact that things can go wrong in a distributed system and retry the operation (i.e., getting a free port) if it failed for whatever reason on the first attempt.
Luckily, there are lots of npm modules out there that do that already for you, e.g. retry.
Using this module you can retry an asynchronous operation until it succeeds, and configure waiting strategies, and how many times it should be retried maximally, and so on…
To provide a code example, it basically comes down to something such as:
const operation = retry.operation();
operation.attempt(currentAttempt => {
findAnUnusedPortAndUseIt(err => {
if (operation.retry(err)) {
return;
}
callback(err ? operation.mainError() : null);
});
});
The benefits of this solution are:
Works without locking, i.e. it is efficient and makes low usage of resources if everything is fine.
Works without a central broker or something like that.
Works for distributed systems of any size.
Uses a pattern that you can re-use in distributed systems for all kinds of problems.
Uses a battle-tested and solid npm module instead of handwriting all these things.
Does not require you to change your code in a major way, instead it is just adding a few lines.
Hope this helps :-)
If your applications can open ports with option like SO_REUSEADDR, but operation system keeps ports in the list in TIME_WAIT state, you can bind/open port you want to return with SO_REUSEADDR, instantly close it and give it back to application. So for TIME_WAIT period (depending on operation system it can be 30 seconds, and actual time should be decided/set up or found by experiment/administration) port list will show this port as occupied.
If your port finder does not give port numbers for ports in TIME_WAIT state, problem solved by relatively expensive open/close socket operation.
I'd advise you look for a way to retain state. Even temporary state, in memory, is better than nothing at all. This way you could at least avoid giving out ports you've already given out. Because those are very likely not free anymore. (This would be as simple as saving them and regenerating a random port if you notice you found a random port you've already given out). If you don't want collisions, build your module to have state so it can avoid them. If you don't want to do that, you'll have to accept there are going to be collisions sometimes when there don't need to be.
If the URLs you get are random, the best you can do is guess randomly. If you can derive some property in which the URLs uniquely and consistently differ, you could design something around that.
Code example:
function getUnusedPort(url) {
// range is [0, 65001). (inclusive zero, exclusive 65001)
const guessPort = () => Math.floor(Math.random() * 15001) + 50000;
let randomPort = guessPort();
while (checkPortInUse(randomPort)) {
randomPort = guessPort();
}
return randomPort;
}
Notes:
checkPortInUse will probably be asynchronous so you'll have to
accommodate for that.
You said 'between 50000 and 65000'. This is from 50000 up to and including 65000.
When managing multiple applications or multiple servers, where one must be right the first time (without retrying), you need a single source of truth. Applications on the same machine can talk to a database, a broker server or even a file, so long as the resource is "lockable". (Servers work in similar ways, though not with local files).
So your flow would be something like:
App A sends request to service to request lock.
When lock is confirmed, start port scanner
When port is used, release lock.
Again, this could be a "PortService" you write that hands out unused ports, or a simple lock in some shared resource so two things are getting the same port at the same time.
Hopefully you can find something suitable to work for your apps.
As you want to find an port that is not in use in your application, you could do is run following command:
netstat -tupln | awk '{print $4}' | cut -d ':' -f2
so in your application you will use this like:
const exec = require('child_process').exec;
exec('netstat -tupln | awk '{print $4}' | cut -d ':' -f2', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
var listPorts = stdout.split(/\n/)
console.log(listPorts); // list of all ports already in use
var aa = _.random(50000, 65000); // generate random port
var isFree = (listPorts.indexOf(aa)===-1) ? true : false;
if(isFree){
//start your appliation
}else{
// restart the search, write this in a function and start search again
}
});
this should give you list of all ports that are in use,so use any port except ones in the listPorts.

How to store Flash-based games data into server

I have this website, I'll be happy if I could store the game progress of the user, and then retrieve it to their respective users when they login. Is there any way to do this? Maybe storing the data to a DB. I was reading on Internet and I found something about Shared Objects. I don't know if it is useful, I hope it will.. Thanks in advance and sorry for my English.
EDIT: I publish external games, I didn't develop them.
You can use a SharedObject to store data locally, on the client side:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/SharedObject.html
This is very easy to implement:
var user_data_so:SharedObject = SharedObject.getLocal("myUserData");
user_data_so.data.name = "User Name";
user_data_so.data.score = user_score;
SharedObjects also work with a NetConnection (see getRemote), although I haven't used this method. Other than that, a server-side script in any language you're comfortable with can accept a POST (or GET) from the client:
var req:URLRequest = new URLRequest(user_data_url);
req.data = user_data_xml;
req.contentType = "text/xml";
req.method = URLRequestMethod.POST;
// either this (will ignore server response):
sendToURL(req);
// or (handles status, error, completion):
var url_loader = new URLLoader();
url_loader.addEventListener("complete",completion_handler);
url_loader.addEventListener("ioError",error_handler);
url_loader.addEventListener("securityError",error_handler);
url_loader.addEventListener("httpResponseStatus",status_handler);
url_loader.addEventListener("httpStatus",status_handler);
url_loader.load(req);

JSJaC + Openfire: no connection with some users

ok, I'm finally at my wits' end. I have a have an XMPP server (Openfire) running, and trying to connect via JavaScript using JSJaC. The strange thing is that I can establish a connection for some users, but not for all. I can reproduce the following behavior: create two accounts (username/password), namely r/pwd and rr/pwd with the result:
r/pwd works
rr/pwd doesn't work.
So far, each account with a user name consisting of only one character works. This is strange enough. On the other side, old accounts, e.g., alice/a work. The whole connection problem is quite new, and I cannot trace it to any changes I've made.
And to make my confusion complete with any instant messenger supporting XMPP, all accounts work, incl., e.g., rr/pwd. So assume, the error must be somewhere in my JavaScript code. Here's he relevant snippet:
...
oArgs = new Object();
oArgs.domain = this.server;
oArgs.resource = this.resource;
oArgs.username = "r";
oArgs.pass = "pwd";
this.connection.connect(oArgs);
The code above works, but setting oArgs.username = "rr", and it fails.
I would be grateful for any hints. I'm quite sure that it must be something really stupid I miss here.
Christian
Adding oArgs.authtype = 'nonsasl' to the argument list when creating the xmpp connection using JSJaC solved my problem. I haven't tried Joe's command to alter the SASL settings in Openfire; I'm scared to ruing my running system :).

Categories